diff --git a/BUILD.gn b/BUILD.gn index f334150b7b10a5f69643740bf143b0ba266f705d..32147476ac439751c154179ce6868d565f80159d 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -19,13 +19,19 @@ group("accesstoken_build_module_test") { deps = [] if (is_standard_system) { deps += [ + "//base/security/access_token/frameworks/accesstoken/test:unittest", + "//base/security/access_token/frameworks/privacy/test:unittest", "//base/security/access_token/interfaces/innerkits/accesstoken/test:unittest", "//base/security/access_token/interfaces/innerkits/nativetoken/test:unittest", "//base/security/access_token/interfaces/innerkits/privacy/test:unittest", "//base/security/access_token/interfaces/innerkits/token_callback/test:unittest", "//base/security/access_token/interfaces/innerkits/token_setproc/test:unittest", "//base/security/access_token/services/accesstokenmanager/test:unittest", + "//base/security/access_token/services/common/database/test:unittest", ] + if (ability_base_enable == true) { + deps += [ "//base/security/access_token/services/privacymanager/test/unittest:unittest" ] + } } if (token_sync_enable == true) { deps += [ diff --git a/frameworks/accesstoken/test/BUILD.gn b/frameworks/accesstoken/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ae8260e81de44d87e46886cf0008943bcd9f2a64 --- /dev/null +++ b/frameworks/accesstoken/test/BUILD.gn @@ -0,0 +1,116 @@ +# 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("//base/security/access_token/access_token.gni") +import("//build/test.gni") + +config("accesstoken_test_config") { + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//third_party/googletest/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/frameworks/common/include", + ] +} +ohos_unittest("libpermission_state_change_info_parcel_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + sources = [ "unittest/src/permission_state_change_info_parcel_test.cpp" ] + + configs = [ + ":accesstoken_test_config", + "//base/security/access_token/config:coverage_flags", + ] + + deps = [ "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx" ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "ipc:ipc_single", + ] +} + +ohos_unittest("libpermission_state_change_scope_parcel_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + sources = [ "unittest/src/permission_state_change_scope_parcel_test.cpp" ] + + configs = [ + ":accesstoken_test_config", + "//base/security/access_token/config:coverage_flags", + ] + + deps = [ "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx" ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "ipc:ipc_single", + ] +} + +ohos_unittest("libhap_info_parcel_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + sources = [ "unittest/src/hap_info_parcel_test.cpp" ] + + configs = [ + ":accesstoken_test_config", + "//base/security/access_token/config:coverage_flags", + ] + + deps = [ "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx" ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "ipc:ipc_single", + ] +} + +ohos_unittest("libhap_policy_parcel_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + sources = [ "unittest/src/hap_policy_parcel_test.cpp" ] + + configs = [ + ":accesstoken_test_config", + "//base/security/access_token/config:coverage_flags", + ] + + deps = [ "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx" ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "ipc:ipc_single", + ] +} +group("unittest") { + testonly = true + deps = [ + ":libhap_info_parcel_test", + ":libhap_policy_parcel_test", + ":libpermission_state_change_info_parcel_test", + ":libpermission_state_change_scope_parcel_test", + ] +} diff --git a/frameworks/accesstoken/test/unittest/src/hap_info_parcel_test.cpp b/frameworks/accesstoken/test/unittest/src/hap_info_parcel_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58e4cb85ad9097bd1364978a859e82ac9de7c660 --- /dev/null +++ b/frameworks/accesstoken/test/unittest/src/hap_info_parcel_test.cpp @@ -0,0 +1,75 @@ +/* + * 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 "access_token.h" +#include "hap_info_parcel.h" +#include "parcel.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr int32_t DEFAULT_API_VERSION = 8; +} +class HapInfoParcelTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void HapInfoParcelTest::SetUpTestCase(void) {} +void HapInfoParcelTest::TearDownTestCase(void) {} +void HapInfoParcelTest::SetUp(void) {} +void HapInfoParcelTest::TearDown(void) {} + +/** + * @tc.name: HapInfoParcel001 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token function. + * @tc.type: FUNC + * @tc.require: I5QKZF + */ +HWTEST_F(HapInfoParcelTest, HapInfoParcel001, TestSize.Level1) +{ + HapInfoParcel hapinfoParcel; + hapinfoParcel.hapInfoParameter = { + .userID = 1, + .bundleName = "accesstoken_test", + .instIndex = 0, + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION, + }; + + Parcel parcel; + EXPECT_EQ(true, hapinfoParcel.Marshalling(parcel)); + + std::shared_ptr readedData(HapInfoParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(hapinfoParcel.hapInfoParameter.userID, readedData->hapInfoParameter.userID); + EXPECT_EQ(true, hapinfoParcel.hapInfoParameter.bundleName == readedData->hapInfoParameter.bundleName); + EXPECT_EQ(hapinfoParcel.hapInfoParameter.instIndex, readedData->hapInfoParameter.instIndex); + EXPECT_EQ(true, hapinfoParcel.hapInfoParameter.appIDDesc == readedData->hapInfoParameter.appIDDesc); + EXPECT_EQ(hapinfoParcel.hapInfoParameter.apiVersion, readedData->hapInfoParameter.apiVersion); +} +} +} +} \ No newline at end of file diff --git a/frameworks/accesstoken/test/unittest/src/hap_policy_parcel_test.cpp b/frameworks/accesstoken/test/unittest/src/hap_policy_parcel_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f232e6700a3c92ca84679868a159e0bfdb78d3c0 --- /dev/null +++ b/frameworks/accesstoken/test/unittest/src/hap_policy_parcel_test.cpp @@ -0,0 +1,146 @@ +/* + * 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 "access_token.h" +#include "hap_policy_parcel.h" +#include "hap_token_info.h" +#include "parcel.h" +#include "permission_state_full.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static const std::string TEST_PERMISSION_NAME_ALPHA = "ohos.permission.ALPHA"; +static const std::string TEST_PERMISSION_NAME_BETA = "ohos.permission.BETA"; + +PermissionDef g_permDefAlpha = { + .permissionName = TEST_PERMISSION_NAME_ALPHA, + .bundleName = "accesstoken_test", + .grantMode = 1, + .availableLevel = APL_NORMAL, + .label = "label", + .labelId = 1, + .description = "annoying", + .descriptionId = 1 +}; +PermissionDef g_permDefBeta = { + .permissionName = TEST_PERMISSION_NAME_BETA, + .bundleName = "accesstoken_test", + .grantMode = 1, + .availableLevel = APL_NORMAL, + .label = "label", + .labelId = 1, + .description = "so trouble", + .descriptionId = 1 +}; + +PermissionStateFull g_permStatAlpha = { + .permissionName = TEST_PERMISSION_NAME_ALPHA, + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_USER_SET} +}; +PermissionStateFull g_permStatBeta = { + .permissionName = TEST_PERMISSION_NAME_BETA, + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED} +}; +} +class HapPolicyParcelTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void HapPolicyParcelTest::SetUpTestCase(void) {} +void HapPolicyParcelTest::TearDownTestCase(void) {} +void HapPolicyParcelTest::SetUp(void) {} +void HapPolicyParcelTest::TearDown(void) {} + +/** + * @tc.name: HapPolicyParcel001 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token function. + * @tc.type: FUNC + * @tc.require: I5QKZF + */ +HWTEST_F(HapPolicyParcelTest, HapPolicyParcel001, TestSize.Level1) +{ + HapPolicyParcel hapPolicyParcel; + + hapPolicyParcel.hapPolicyParameter.apl = ATokenAplEnum::APL_NORMAL; + hapPolicyParcel.hapPolicyParameter.domain = "test.domain"; + hapPolicyParcel.hapPolicyParameter.permList.emplace_back(g_permDefAlpha); + hapPolicyParcel.hapPolicyParameter.permList.emplace_back(g_permDefBeta); + hapPolicyParcel.hapPolicyParameter.permStateList.emplace_back(g_permStatAlpha); + hapPolicyParcel.hapPolicyParameter.permStateList.emplace_back(g_permStatBeta); + + Parcel parcel; + EXPECT_EQ(true, hapPolicyParcel.Marshalling(parcel)); + + std::shared_ptr readedData(HapPolicyParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.apl, readedData->hapPolicyParameter.apl); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.domain, readedData->hapPolicyParameter.domain); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList.size(), readedData->hapPolicyParameter.permList.size()); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permStateList.size(), + readedData->hapPolicyParameter.permStateList.size()); + + for(int32_t i = 0; i < hapPolicyParcel.hapPolicyParameter.permList.size(); i++) { + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList[i].permissionName, + readedData->hapPolicyParameter.permList[i].permissionName); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList[i].bundleName, + readedData->hapPolicyParameter.permList[i].bundleName); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList[i].grantMode, + readedData->hapPolicyParameter.permList[i].grantMode); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList[i].availableLevel, + readedData->hapPolicyParameter.permList[i].availableLevel); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList[i].label, + readedData->hapPolicyParameter.permList[i].label); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList[i].labelId, + readedData->hapPolicyParameter.permList[i].labelId); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList[i].description, + readedData->hapPolicyParameter.permList[i].description); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permList[i].descriptionId, + readedData->hapPolicyParameter.permList[i].descriptionId); + } + + for(int32_t i = 0; i < hapPolicyParcel.hapPolicyParameter.permStateList.size(); i++) { + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permStateList[i].permissionName, + readedData->hapPolicyParameter.permStateList[i].permissionName); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permStateList[i].isGeneral, + readedData->hapPolicyParameter.permStateList[i].isGeneral); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permStateList[i].resDeviceID, + readedData->hapPolicyParameter.permStateList[i].resDeviceID); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permStateList[i].grantStatus, + readedData->hapPolicyParameter.permStateList[i].grantStatus); + EXPECT_EQ(hapPolicyParcel.hapPolicyParameter.permStateList[i].grantFlags, + readedData->hapPolicyParameter.permStateList[i].grantFlags); + } +} +} +} +} \ No newline at end of file diff --git a/frameworks/accesstoken/test/unittest/src/permission_state_change_info_parcel_test.cpp b/frameworks/accesstoken/test/unittest/src/permission_state_change_info_parcel_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0e69baab53ba0b05035ea49a267b876f7c37d79 --- /dev/null +++ b/frameworks/accesstoken/test/unittest/src/permission_state_change_info_parcel_test.cpp @@ -0,0 +1,70 @@ +/* + * 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 "parcel.h" +#include "permission_state_change_info_parcel.h" +#include "permission_state_change_info.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr int32_t TEST_PERMSTATE_CHANGE_TYPE = 10001; +static constexpr AccessTokenID TEST_TOKEN_ID = 10002; +static const std::string TEST_PERMISSION_NAME = "ohos.permission.PERMISSION_STATE_CHANGE_INFO"; +} +class PermissionStateChangeInfoParcelTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PermissionStateChangeInfoParcelTest::SetUpTestCase(void) {} +void PermissionStateChangeInfoParcelTest::TearDownTestCase(void) {} +void PermissionStateChangeInfoParcelTest::SetUp(void) {} +void PermissionStateChangeInfoParcelTest::TearDown(void) {} + +/** + * @tc.name: PermissionStateChangeInfoParcel001 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token function. + * @tc.type: FUNC + * @tc.require: I5QKZF + */ +HWTEST_F(PermissionStateChangeInfoParcelTest, PermissionStateChangeInfoParcel001, TestSize.Level1) +{ + PermissionStateChangeInfoParcel permissionStateParcel; + permissionStateParcel.changeInfo.PermStateChangeType = TEST_PERMSTATE_CHANGE_TYPE; + permissionStateParcel.changeInfo.tokenID = TEST_TOKEN_ID; + permissionStateParcel.changeInfo.permissionName = TEST_PERMISSION_NAME; + + Parcel parcel; + EXPECT_EQ(true, permissionStateParcel.Marshalling(parcel)); + + std::shared_ptr readedData(PermissionStateChangeInfoParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + EXPECT_EQ(permissionStateParcel.changeInfo.PermStateChangeType, readedData->changeInfo.PermStateChangeType); + EXPECT_EQ(permissionStateParcel.changeInfo.tokenID, readedData->changeInfo.tokenID); + EXPECT_EQ(permissionStateParcel.changeInfo.permissionName, readedData->changeInfo.permissionName); +} +} +} +} \ No newline at end of file diff --git a/frameworks/accesstoken/test/unittest/src/permission_state_change_scope_parcel_test.cpp b/frameworks/accesstoken/test/unittest/src/permission_state_change_scope_parcel_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4f812a766ecec0e19babd635310535919137195 --- /dev/null +++ b/frameworks/accesstoken/test/unittest/src/permission_state_change_scope_parcel_test.cpp @@ -0,0 +1,74 @@ +/* + * 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 "parcel.h" +#include "permission_state_change_scope_parcel.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr AccessTokenID TEST_TOKEN_ID = 10002; +static const std::string TEST_PERMISSION_NAME = "ohos.permission.PERMISSION_STATE_CHANGE_INFO"; +} +class PermStateChangeScopeParcelTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PermStateChangeScopeParcelTest::SetUpTestCase(void) {} +void PermStateChangeScopeParcelTest::TearDownTestCase(void) {} +void PermStateChangeScopeParcelTest::SetUp(void) {} +void PermStateChangeScopeParcelTest::TearDown(void) {} + +/** + * @tc.name: PermStateChangeScopeParcel001 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token function. + * @tc.type: FUNC + * @tc.require: I5QKZF + */ +HWTEST_F(PermStateChangeScopeParcelTest, PermStateChangeScopeParcel001, TestSize.Level1) +{ + PermStateChangeScopeParcel permStateChangeScopeParcel; + permStateChangeScopeParcel.scope.tokenIDs.emplace_back(TEST_TOKEN_ID); + permStateChangeScopeParcel.scope.permList.emplace_back(TEST_PERMISSION_NAME); + + Parcel parcel; + EXPECT_EQ(true, permStateChangeScopeParcel.Marshalling(parcel)); + + std::shared_ptr readedData(PermStateChangeScopeParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(true, permStateChangeScopeParcel.scope.tokenIDs.size() == readedData->scope.tokenIDs.size()); + EXPECT_EQ(true, permStateChangeScopeParcel.scope.permList.size() == readedData->scope.permList.size()); + + for(int32_t i = 0; i < readedData->scope.tokenIDs.size(); i++) { + EXPECT_EQ(permStateChangeScopeParcel.scope.tokenIDs[i], readedData->scope.tokenIDs[i]); + } + for(int32_t i = 0; i < readedData->scope.permList.size(); i++) { + EXPECT_EQ(true, permStateChangeScopeParcel.scope.permList[i] == readedData->scope.permList[i]); + } +} +} +} +} \ No newline at end of file diff --git a/frameworks/privacy/test/BUILD.gn b/frameworks/privacy/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b749dbe5c67eaeaad74248218f0cbc31fdd09fdf --- /dev/null +++ b/frameworks/privacy/test/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("//base/security/access_token/access_token.gni") +import("//build/test.gni") + +config("accesstoken_test_config") { + include_dirs = [ + "//third_party/googletest/include", + "//base/security/access_token/frameworks/privacy/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + ] +} + +ohos_unittest("libprivacy_parcel_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + sources = [ "unittest/src/privacy_parcel_test.cpp" ] + + configs = [ + ":accesstoken_test_config", + "//base/security/access_token/config:coverage_flags", + ] + + deps = [ "//base/security/access_token/frameworks/privacy:privacy_communication_adapter_cxx" ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_single", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libprivacy_parcel_test" ] +} diff --git a/frameworks/privacy/test/unittest/src/privacy_parcel_test.cpp b/frameworks/privacy/test/unittest/src/privacy_parcel_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..906e902387009f66105a19077c4662126f4228b2 --- /dev/null +++ b/frameworks/privacy/test/unittest/src/privacy_parcel_test.cpp @@ -0,0 +1,332 @@ +/* + * 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 "privacy_parcel_test.h" + +#include +#include + +#include "bundle_used_record_parcel.h" +#include "parcel.h" +#include "perm_active_response_parcel.h" +#include "permission_used_record_parcel.h" +#include "permission_used_request_parcel.h" +#include "permission_used_result_parcel.h" +#include "used_record_detail_parcel.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +UsedRecordDetail g_accessRecord1 = { + .status = 0, + .timestamp = 0L, + .accessDuration = 0L, +}; + +UsedRecordDetail g_accessRecord2 = { + .status = 1, + .timestamp = 1L, + .accessDuration = 1L, +}; + +UsedRecordDetail g_rejectRecord1 = { + .status = 2, + .timestamp = 2L, + .accessDuration = 2L, +}; + +UsedRecordDetail g_rejectRecord2 = { + .status = 3, + .timestamp = 3L, + .accessDuration = 3L, +}; + +PermissionUsedRecord g_permissionRecord1 = { + .permissionName = "ohos.permission.CAMERA", + .accessCount = 2, + .rejectCount = 2, + .lastAccessTime = 0L, + .lastRejectTime = 0L, + .lastAccessDuration = 0L, +}; + +PermissionUsedRecord g_permissionRecord2 = { + .permissionName = "ohos.permission.LOCATION", + .accessCount = 2, + .rejectCount = 2, + .lastAccessTime = 1L, + .lastRejectTime = 1L, + .lastAccessDuration = 1L, +}; + +BundleUsedRecord g_bundleUsedRecord1 = { + .tokenId = 100, + .isRemote = false, + .deviceId = "you guess", + .bundleName = "com.ohos.camera", +}; + +BundleUsedRecord g_bundleUsedRecord2 = { + .tokenId = 101, + .isRemote = false, + .deviceId = "i want to know too", + .bundleName = "com.ohos.permissionmanager", +}; +} + +void PrivacyParcelTest::SetUpTestCase() +{ +} + +void PrivacyParcelTest::TearDownTestCase() +{ +} + +void PrivacyParcelTest::SetUp() +{ +} + +void PrivacyParcelTest::TearDown() +{ +} + +/** + * @tc.name: BundleUsedRecordParcel001 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token function. + * @tc.type: FUNC + * @tc.require: issueI5RUCC + */ +HWTEST_F(PrivacyParcelTest, BundleUsedRecordParcel001, TestSize.Level1) +{ + BundleUsedRecordParcel bundleUsedRecordParcel; + + bundleUsedRecordParcel.bundleRecord = { + .tokenId = 100, + .isRemote = false, + .deviceId = "you guess", + .bundleName = "com.ohos.permissionmanager", + }; + + g_permissionRecord1.accessRecords.emplace_back(g_accessRecord1); + g_permissionRecord1.accessRecords.emplace_back(g_accessRecord2); + g_permissionRecord2.rejectRecords.emplace_back(g_rejectRecord1); + g_permissionRecord2.rejectRecords.emplace_back(g_rejectRecord2); + + bundleUsedRecordParcel.bundleRecord.permissionRecords.emplace_back(g_permissionRecord1); + bundleUsedRecordParcel.bundleRecord.permissionRecords.emplace_back(g_permissionRecord2); + + Parcel parcel; + EXPECT_EQ(true, bundleUsedRecordParcel.Marshalling(parcel)); + + std::shared_ptr readedData(BundleUsedRecordParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(bundleUsedRecordParcel.bundleRecord.tokenId, readedData->bundleRecord.tokenId); + EXPECT_EQ(bundleUsedRecordParcel.bundleRecord.isRemote, readedData->bundleRecord.isRemote); + EXPECT_EQ(bundleUsedRecordParcel.bundleRecord.deviceId, readedData->bundleRecord.deviceId); + EXPECT_EQ(bundleUsedRecordParcel.bundleRecord.bundleName, readedData->bundleRecord.bundleName); +} + +/** + * @tc.name: ActiveChangeResponseParcel001 + * @tc.desc: Verify ActiveChangeResponseParcel Marshalling and Unmarshalling function. + * @tc.type: FUNC + * @tc.require: issueI5RRLJ + */ +HWTEST_F(PrivacyParcelTest, ActiveChangeResponseParcel001, TestSize.Level1) +{ + ActiveChangeResponseParcel activeChangeResponseParcel; + + activeChangeResponseParcel.changeResponse = { + .tokenID = 100, + .permissionName = "ohos.permission.CAMERA", + .deviceId = "you guess", + .type = PERM_INACTIVE, + }; + + Parcel parcel; + EXPECT_EQ(true, activeChangeResponseParcel.Marshalling(parcel)); + + std::shared_ptr readedData(ActiveChangeResponseParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(activeChangeResponseParcel.changeResponse.tokenID, readedData->changeResponse.tokenID); + EXPECT_EQ(activeChangeResponseParcel.changeResponse.permissionName, readedData->changeResponse.permissionName); + EXPECT_EQ(activeChangeResponseParcel.changeResponse.deviceId, readedData->changeResponse.deviceId); + EXPECT_EQ(activeChangeResponseParcel.changeResponse.type, readedData->changeResponse.type); +} + +/** + * @tc.name: PermissionUsedRecordParcel001 + * @tc.desc: Verify the PermissionUsedRecordParcel Marshalling and Unmarshalling function. + * @tc.type: FUNC + * @tc.require: issueI5RUCC + */ +HWTEST_F(PrivacyParcelTest, PermissionUsedRecordParcel001, TestSize.Level1) +{ + PermissionUsedRecordParcel permissionUsedRecordParcel; + + permissionUsedRecordParcel.permissionRecord = { + .permissionName = "ohos.permission.CAMERA", + .accessCount = 2, + .rejectCount = 2, + .lastAccessTime = 0L, + .lastRejectTime = 0L, + .lastAccessDuration = 0L, + }; + permissionUsedRecordParcel.permissionRecord.accessRecords.emplace_back(g_accessRecord1); + permissionUsedRecordParcel.permissionRecord.accessRecords.emplace_back(g_accessRecord2); + permissionUsedRecordParcel.permissionRecord.rejectRecords.emplace_back(g_rejectRecord1); + permissionUsedRecordParcel.permissionRecord.rejectRecords.emplace_back(g_rejectRecord2); + + Parcel parcel; + EXPECT_EQ(true, permissionUsedRecordParcel.Marshalling(parcel)); + + std::shared_ptr readedData(PermissionUsedRecordParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.permissionName, readedData->permissionRecord.permissionName); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.accessCount, readedData->permissionRecord.accessCount); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.rejectCount, readedData->permissionRecord.rejectCount); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.lastAccessTime, readedData->permissionRecord.lastAccessTime); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.lastRejectTime, readedData->permissionRecord.lastRejectTime); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.lastAccessDuration, + readedData->permissionRecord.lastAccessDuration); + + for(uint32_t i = 0; i < permissionUsedRecordParcel.permissionRecord.accessRecords.size(); i++) { + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.accessRecords[i].status, + readedData->permissionRecord.accessRecords[i].status); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.accessRecords[i].timestamp, + readedData->permissionRecord.accessRecords[i].timestamp); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.accessRecords[i].accessDuration, + readedData->permissionRecord.accessRecords[i].accessDuration); + } + + for(uint32_t i = 0; i < permissionUsedRecordParcel.permissionRecord.rejectRecords.size(); i++) { + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.rejectRecords[i].status, + readedData->permissionRecord.rejectRecords[i].status); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.rejectRecords[i].timestamp, + readedData->permissionRecord.rejectRecords[i].timestamp); + EXPECT_EQ(permissionUsedRecordParcel.permissionRecord.rejectRecords[i].accessDuration, + readedData->permissionRecord.rejectRecords[i].accessDuration); + } +} + +/** + * @tc.name: PermissionUsedRequestParcel001 + * @tc.desc: Verify the PermissionUsedRequestParcel Marshalling and Unmarshalling function. + * @tc.type: FUNC + * @tc.require: issueI5RUP1 + */ +HWTEST_F(PrivacyParcelTest, PermissionUsedRequestParcel001, TestSize.Level1) +{ + PermissionUsedRequestParcel permissionUsedRequestParcel; + + permissionUsedRequestParcel.request = { + .tokenId = 100, + .isRemote = false, + .deviceId = "you guess", + .bundleName = "com.ohos.permissionmanager", + .beginTimeMillis = 0L, + .endTimeMillis = 0L, + .flag = FLAG_PERMISSION_USAGE_SUMMARY, + }; + permissionUsedRequestParcel.request.permissionList.emplace_back("ohos.permission.CAMERA"); + permissionUsedRequestParcel.request.permissionList.emplace_back("ohos.permission.LOCATION"); + + Parcel parcel; + EXPECT_EQ(true, permissionUsedRequestParcel.Marshalling(parcel)); + + std::shared_ptr readedData(PermissionUsedRequestParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(permissionUsedRequestParcel.request.tokenId, readedData->request.tokenId); + EXPECT_EQ(permissionUsedRequestParcel.request.isRemote, readedData->request.isRemote); + EXPECT_EQ(permissionUsedRequestParcel.request.deviceId, readedData->request.deviceId); + EXPECT_EQ(permissionUsedRequestParcel.request.bundleName, readedData->request.bundleName); + EXPECT_EQ(permissionUsedRequestParcel.request.beginTimeMillis, readedData->request.beginTimeMillis); + EXPECT_EQ(permissionUsedRequestParcel.request.endTimeMillis, readedData->request.endTimeMillis); + EXPECT_EQ(permissionUsedRequestParcel.request.flag, readedData->request.flag); + + for(uint32_t i = 0; i < permissionUsedRequestParcel.request.permissionList.size(); i++) { + EXPECT_EQ(permissionUsedRequestParcel.request.permissionList[i], readedData->request.permissionList[i]); + } +} + +/** + * @tc.name: PermissionUsedResultParcel001 + * @tc.desc: Verify the PermissionUsedResultParcel Marshalling and Unmarshalling function. + * @tc.type: FUNC + * @tc.require: issueI5RWP4 + */ +HWTEST_F(PrivacyParcelTest, PermissionUsedResultParcel001, TestSize.Level1) +{ + PermissionUsedResultParcel permissionUsedResultParcel; + + permissionUsedResultParcel.result = { + .beginTimeMillis = 0L, + .endTimeMillis = 0L, + }; + + g_bundleUsedRecord1.permissionRecords.emplace_back(g_permissionRecord1); + g_bundleUsedRecord1.permissionRecords.emplace_back(g_permissionRecord2); + g_bundleUsedRecord2.permissionRecords.emplace_back(g_permissionRecord1); + g_bundleUsedRecord2.permissionRecords.emplace_back(g_permissionRecord2); + + permissionUsedResultParcel.result.bundleRecords.emplace_back(g_bundleUsedRecord1); + permissionUsedResultParcel.result.bundleRecords.emplace_back(g_bundleUsedRecord2); + + Parcel parcel; + EXPECT_EQ(true, permissionUsedResultParcel.Marshalling(parcel)); + + std::shared_ptr readedData(PermissionUsedResultParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(permissionUsedResultParcel.result.beginTimeMillis, readedData->result.beginTimeMillis); + EXPECT_EQ(permissionUsedResultParcel.result.endTimeMillis, readedData->result.endTimeMillis); +} + +/** + * @tc.name: UsedRecordDetailParcel001 + * @tc.desc: Verify the UsedRecordDetailParcel Marshalling and Unmarshalling function. + * @tc.type: FUNC + * @tc.require: issueI5RWP4 + */ +HWTEST_F(PrivacyParcelTest, UsedRecordDetailParcel001, TestSize.Level1) +{ + UsedRecordDetailParcel usedRecordDetailParcel; + + usedRecordDetailParcel.detail = { + .status = 0, + .timestamp = 0L, + .accessDuration = 0L, + }; + + Parcel parcel; + EXPECT_EQ(true, usedRecordDetailParcel.Marshalling(parcel)); + + std::shared_ptr readedData(UsedRecordDetailParcel::Unmarshalling(parcel)); + EXPECT_EQ(true, readedData != nullptr); + + EXPECT_EQ(usedRecordDetailParcel.detail.status, readedData->detail.status); + EXPECT_EQ(usedRecordDetailParcel.detail.timestamp, readedData->detail.timestamp); + EXPECT_EQ(usedRecordDetailParcel.detail.accessDuration, readedData->detail.accessDuration); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.h b/frameworks/privacy/test/unittest/src/privacy_parcel_test.h similarity index 82% rename from services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.h rename to frameworks/privacy/test/unittest/src/privacy_parcel_test.h index 8f6f83d318ffc07700083e1b442c73945c12461d..f18f664a9a8b6ddf0e0adca897836c9b1fb52c8a 100644 --- a/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.h +++ b/frameworks/privacy/test/unittest/src/privacy_parcel_test.h @@ -12,26 +12,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef ADD_PERMISSION_USED_RECORD_TEST_H -#define ADD_PERMISSION_USED_RECORD_TEST_H - + #include namespace OHOS { namespace Security { namespace AccessToken { -class AddPermissionUsedRecordTest : public testing::Test { +class PrivacyParcelTest : public testing::Test { public: static void SetUpTestCase(); - static void TearDownTestCase(); void SetUp(); - void TearDown(); }; } // namespace AccessToken } // namespace Security } // namespace OHOS -#endif // ADD_PERMISSION_USED_RECORD_TEST_H diff --git a/interfaces/innerkits/accesstoken/include/accesstoken_kit.h b/interfaces/innerkits/accesstoken/include/accesstoken_kit.h index ff0632e343c386ce412caddbbc78c2a8fb30a7a9..e623226e9053eed4ed65452970a05207e9e32edd 100644 --- a/interfaces/innerkits/accesstoken/include/accesstoken_kit.h +++ b/interfaces/innerkits/accesstoken/include/accesstoken_kit.h @@ -61,6 +61,7 @@ public: static int32_t RegisterPermStateChangeCallback( const std::shared_ptr& callback); static int32_t UnRegisterPermStateChangeCallback(const std::shared_ptr& callback); + static int32_t GetVersion(void); static int32_t GetHapDlpFlag(AccessTokenID tokenID); static int32_t ReloadNativeTokenInfo(); static AccessTokenID GetNativeTokenId(const std::string& processName); @@ -70,7 +71,7 @@ public: static int GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes); static int SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync); static int SetRemoteNativeTokenInfo(const std::string& deviceID, - std::vector& nativeTokenInfoList); + const std::vector& nativeTokenInfoList); static int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); static AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); static int DeleteRemoteDeviceTokens(const std::string& deviceID); diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp index 6736123e156c460e76ed69c6110d0ba1541c73f0..04c0e9c8f4d2f487106ee7f810a9b75a33ac8038 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp @@ -320,7 +320,7 @@ int32_t AccessTokenKit::ReloadNativeTokenInfo() AccessTokenID AccessTokenKit::GetNativeTokenId(const std::string& processName) { if (!DataValidator::IsProcessNameValid(processName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "processName is invalid"); + ACCESSTOKEN_LOG_ERROR(LABEL, "processName is invalid, processName=%{public}s", processName.c_str()); return INVALID_TOKENID; } return AccessTokenManagerClient::GetInstance().GetNativeTokenId(processName); @@ -354,7 +354,7 @@ int AccessTokenKit::SetRemoteHapTokenInfo(const std::string& deviceID, } int AccessTokenKit::SetRemoteNativeTokenInfo(const std::string& deviceID, - std::vector& nativeTokenInfoList) + const std::vector& nativeTokenInfoList) { ACCESSTOKEN_LOG_DEBUG(LABEL, "called, deviceID=%{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); return AccessTokenManagerClient::GetInstance().SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoList); @@ -386,6 +386,11 @@ void AccessTokenKit::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); AccessTokenManagerClient::GetInstance().DumpTokenInfo(tokenID, dumpInfo); } + +int32_t AccessTokenKit::GetVersion(void) +{ + return DEFAULT_TOKEN_VERSION; +} } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp index 4b2bbb3e49d17c9ca27847faf0f592beaede8fc0..9f0e9ce3ad0a3e9c75e938fccbc8e9ec3cd05335 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp @@ -429,7 +429,7 @@ int AccessTokenManagerClient::SetRemoteHapTokenInfo(const std::string& deviceID, } int AccessTokenManagerClient::SetRemoteNativeTokenInfo(const std::string& deviceID, - std::vector& nativeTokenInfoList) + const std::vector& nativeTokenInfoList) { auto proxy = GetProxy(); if (proxy == nullptr) { diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h index 7d5a2d44f0067ca075a58ce6add0312f53e1d897..514194be6242b2b67d955d4e39824099c8236dee 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h @@ -66,7 +66,7 @@ public: int32_t ReloadNativeTokenInfo(); AccessTokenID GetNativeTokenId(const std::string& processName); int32_t RegisterPermStateChangeCallback( - const std::shared_ptr& customizedCallback); + const std::shared_ptr& customizedCb); int32_t UnRegisterPermStateChangeCallback( const std::shared_ptr& customizedCb); @@ -75,7 +75,7 @@ public: int GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes); int SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync); int SetRemoteNativeTokenInfo(const std::string& deviceID, - std::vector& nativeTokenInfoList); + const std::vector& nativeTokenInfoList); int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); int DeleteRemoteDeviceTokens(const std::string& deviceID); @@ -87,7 +87,7 @@ public: private: AccessTokenManagerClient(); int32_t CreatePermStateChangeCallback( - const std::shared_ptr& customizedCallback, + const std::shared_ptr& customizedCb, sptr& callback); DISALLOW_COPY_AND_MOVE(AccessTokenManagerClient); diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h index a5b53e08cca91a0bfe154f6dab623a15526d1ae7..3aa6de5e97d53669b568952352ff2beb4d06c34d 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h @@ -48,7 +48,7 @@ public: int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) override; int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; - PermissionOper GetSelfPermissionsState(std::vector& permList) override; + PermissionOper GetSelfPermissionsState(std::vector& permListParcel) override; int ClearUserGrantedPermissionState(AccessTokenID tokenID) override; int GetTokenType(AccessTokenID tokenID) override; int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) override; @@ -57,7 +57,7 @@ public: AccessTokenIDEx AllocHapToken(const HapInfoParcel& hapInfo, const HapPolicyParcel& policyParcel) override; int DeleteToken(AccessTokenID tokenID) override; int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, - const HapPolicyParcel& policyPar) override; + const HapPolicyParcel& policyParcel) override; int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) override; int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) override; int32_t ReloadNativeTokenInfo() override; diff --git a/interfaces/innerkits/accesstoken/src/permission_state_change_callback.h b/interfaces/innerkits/accesstoken/src/permission_state_change_callback.h index 8ee416fad2238760fcbdb0c9a890f49d38a8bc21..ce623cf323c563cad9f7118060f2b71a4e2ed3fa 100644 --- a/interfaces/innerkits/accesstoken/src/permission_state_change_callback.h +++ b/interfaces/innerkits/accesstoken/src/permission_state_change_callback.h @@ -26,7 +26,7 @@ namespace Security { namespace AccessToken { class PermissionStateChangeCallback : public PermissionStateChangeCallbackStub { public: - explicit PermissionStateChangeCallback(const std::shared_ptr& scope); + explicit PermissionStateChangeCallback(const std::shared_ptr& customizedCallback); ~PermissionStateChangeCallback() override; void PermStateChangeCallback(PermStateChangeInfo& result) override; diff --git a/interfaces/innerkits/accesstoken/test/BUILD.gn b/interfaces/innerkits/accesstoken/test/BUILD.gn index 6069ca1382eb7b5accb77266f577ae491515d095..468d6af8eaead2f63a3da48dae4b88ef96e39feb 100644 --- a/interfaces/innerkits/accesstoken/test/BUILD.gn +++ b/interfaces/innerkits/accesstoken/test/BUILD.gn @@ -28,7 +28,10 @@ ohos_unittest("libaccesstoken_sdk_test") { "//base/security/access_token/frameworks/common/include", ] - sources = [ "unittest/src/accesstoken_kit_test.cpp" ] + sources = [ + "unittest/src/accesstoken_kit_test.cpp", + "unittest/src/remote_token_kit_test.cpp", + ] cflags_cc = [ "-DHILOG_ENABLE" ] diff --git a/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp index cd314d88bee2341b1b468fb55e8abeb6f448509d..666fb8152304ada7a9eae43230e4621bb0aad094 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp @@ -223,6 +223,32 @@ PermissionStateFull g_locationTestStateAccurate12 = { }; } +void NativeTokenGet() +{ + uint64_t tokenId; + const char **perms = new const char *[4]; + perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; + perms[1] = "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"; + perms[2] = "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"; + perms[3] = "ohos.permission.GET_SENSITIVE_PERMISSIONS"; + + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 4, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .aplStr = "system_core", + }; + + infoInstance.processName = "TestCase"; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + void AccessTokenKitTest::SetUpTestCase() { // make test case clean @@ -233,6 +259,8 @@ void AccessTokenKitTest::SetUpTestCase() tokenID = AccessTokenKit::GetHapTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenKit::DeleteToken(tokenID); + + NativeTokenGet(); } void AccessTokenKitTest::TearDownTestCase() @@ -948,6 +976,21 @@ HWTEST_F(AccessTokenKitTest, GrantPermission003, TestSize.Level0) } } +/** + * @tc.name: GrantPermission004 + * @tc.desc: GrantPermission function abnormal branch + * @tc.type: FUNC + * @tc.require:Issue I5RJBB + */ +HWTEST_F(AccessTokenKitTest, GrantPermission004, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int32_t invalidFlag = -1; + int32_t ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, invalidFlag); + ASSERT_EQ(RET_FAILED, ret); +} + /** * @tc.name: RevokePermission001 * @tc.desc: Revoke permission that has ohos.permission.GRANT_SENSITIVE_PERMISSIONS @@ -1024,6 +1067,21 @@ HWTEST_F(AccessTokenKitTest, RevokePermission003, TestSize.Level0) } } +/** + * @tc.name: RevokePermission004 + * @tc.desc: Revoke permission abnormal branch. + * @tc.type: FUNC + * @tc.require:Issue I5RJBB + */ +HWTEST_F(AccessTokenKitTest, RevokePermission004, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int invalidFlag = -1; + int32_t ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_ALPHA, invalidFlag); + ASSERT_EQ(RET_FAILED, ret); +} + /** * @tc.name: ClearUserGrantedPermissionState001 * @tc.desc: Clear user/system granted permission after ClearUserGrantedPermissionState has been invoked. @@ -1156,6 +1214,32 @@ HWTEST_F(AccessTokenKitTest, GetTokenType001, TestSize.Level0) DeleteTestToken(); } +/** + * @tc.name: GetTokenType002 + * @tc.desc: get the token type abnormal branch. + * @tc.type: FUNC + * @tc.require Issue I5RJBB + */ +HWTEST_F(AccessTokenKitTest, GetTokenType002, TestSize.Level0) +{ + AccessTokenID tokenID = 0; + int32_t ret = AccessTokenKit::GetTokenType(tokenID); + ASSERT_EQ(TOKEN_INVALID, ret); +} + +/** + * @tc.name: GetHapDlpFlag001 + * @tc.desc: GetHapDlpFlag function abnormal branch. + * @tc.type: FUNC + * @tc.require Issue Number:I5RJBB + */ +HWTEST_F(AccessTokenKitTest, GetHapDlpFlag001, TestSize.Level0) +{ + AccessTokenID tokenID = 0; + int32_t ret = AccessTokenKit::GetHapDlpFlag(tokenID); + ASSERT_EQ(INVALID_DLP_TOKEN_FLAG, ret); +} + /** * @tc.name: GetHapTokenInfo001 * @tc.desc: get the token info and verify. @@ -3704,6 +3788,18 @@ HWTEST_F(AccessTokenKitTest, UnRegisterPermStateChangeCallback002, TestSize.Leve res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); ASSERT_EQ(RET_FAILED, res); } + +/** + * @tc.name: GetVersion001 + * @tc.desc: GetVersion001 test. + * @tc.type: FUNC + * @tc.require: issueI5NT1X + */ +HWTEST_F(AccessTokenKitTest, GetVersion001, TestSize.Level1) +{ + int32_t res = AccessTokenKit::GetVersion(); + ASSERT_EQ(DEFAULT_TOKEN_VERSION, res); +} } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/test/unittest/src/remote_token_kit_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/src/remote_token_kit_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53ceb84d910ba89f87d5c7d130a51009472b9fcb --- /dev/null +++ b/interfaces/innerkits/accesstoken/test/unittest/src/remote_token_kit_test.cpp @@ -0,0 +1,1225 @@ +/* + * 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 "remote_token_kit_test.h" +#include + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "nativetoken_kit.h" +#include "softbus_bus_center.h" +#include "token_setproc.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "RemoteTokenKitTest"}; + +static const std::string TEST_BUNDLE_NAME = "ohos"; +static const std::string TEST_PERMISSION_NAME_ALPHA = "ohos.permission.ALPHA"; +static const std::string TEST_PERMISSION_NAME_BETA = "ohos.permission.BETA"; +static const std::string TEST_PERMISSION_NAME_GAMMA = "ohos.permission.GAMMA"; +static const std::string TEST_PKG_NAME = "com.softbus.test"; +static const int TEST_USER_ID = 0; + +PermissionStateFull g_grantPermissionReq = { + .permissionName = "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED} +}; +PermissionStateFull g_revokePermissionReq = { + .permissionName = "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED} +}; + +PermissionDef g_infoManagerTestPermDef1 = { + .permissionName = "ohos.permission.test1", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "open the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +PermissionDef g_infoManagerTestPermDef2 = { + .permissionName = "ohos.permission.test2", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "break the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +PermissionStateFull g_infoManagerTestState1 = { + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"} +}; + +PermissionStateFull g_infoManagerTestState2 = { + .permissionName = "ohos.permission.test2", + .isGeneral = false, + .grantFlags = {1, 2}, + .grantStatus = {PermissionState::PERMISSION_GRANTED, PermissionState::PERMISSION_GRANTED}, + .resDeviceID = {"device 1", "device 2"} +}; + +HapInfoParams g_infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .appIDDesc = "testtesttesttest" +}; + +HapPolicyParams g_infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, + .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} +}; + +HapInfoParams g_infoManagerTestInfoParmsBak = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .appIDDesc = "testtesttesttest" +}; + +HapPolicyParams g_infoManagerTestPolicyPramsBak = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, + .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} +}; +} + +void NativeTokenGet() +{ + uint64_t tokenId; + tokenId = AccessTokenKit::GetNativeTokenId("token_sync_service"); + ASSERT_NE(tokenId, 0); + SetSelfTokenID(tokenId); +} + +void RemoteTokenKitTest::SetUpTestCase() +{ + // make test case clean + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenID); + + tokenID = AccessTokenKit::GetHapTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + AccessTokenKit::DeleteToken(tokenID); + + NativeTokenGet(); +} + +void RemoteTokenKitTest::TearDownTestCase() +{ +} + +void RemoteTokenKitTest::SetUp() +{ + selfTokenId_ = GetSelfTokenID(); + g_infoManagerTestInfoParms = g_infoManagerTestInfoParmsBak; + g_infoManagerTestPolicyPrams = g_infoManagerTestPolicyPramsBak; + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenID); + + NodeBasicInfo deviceInfo; + int32_t res = ::GetLocalNodeDeviceInfo(TEST_PKG_NAME.c_str(), &deviceInfo); + ASSERT_EQ(res, RET_SUCCESS); + char udid[128] = {0}; // 128 is udid length + ::GetNodeKeyInfo(TEST_PKG_NAME.c_str(), deviceInfo.networkId, + NodeDeviceInfoKey::NODE_KEY_UDID, (uint8_t *)udid, 128); // 128 is udid length + + udid_.append(udid); + networkId_.append(deviceInfo.networkId); + + ACCESSTOKEN_LOG_INFO(LABEL, "SetUp ok."); +} + +void RemoteTokenKitTest::TearDown() +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); + udid_.clear(); + networkId_.clear(); +} + +unsigned int RemoteTokenKitTest::GetAccessTokenID(int userID, std::string bundleName, int instIndex) +{ + return AccessTokenKit::GetHapTokenID(userID, bundleName, instIndex); +} + +void RemoteTokenKitTest::DeleteTestToken() const +{ + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + int ret = AccessTokenKit::DeleteToken(tokenID); + if (tokenID != 0) { + ASSERT_EQ(RET_SUCCESS, ret); + } +} + +void RemoteTokenKitTest::AllocTestToken() const +{ + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); +} + +#ifdef TOKEN_SYNC_ENABLE +/** + * @tc.name: SetRemoteHapTokenInfo001 + * @tc.desc: set remote hap token info success + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo001 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = deviceID, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + // Get local map token ID + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + // check local map token + HapTokenInfo resultInfo; + ret = AccessTokenKit::GetHapTokenInfo(mapID, resultInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(resultInfo.apl, remoteTokenInfo.baseInfo.apl); + ASSERT_EQ(resultInfo.ver, remoteTokenInfo.baseInfo.ver); + ASSERT_EQ(resultInfo.userID, remoteTokenInfo.baseInfo.userID); + ASSERT_EQ(resultInfo.bundleName, remoteTokenInfo.baseInfo.bundleName); + ASSERT_EQ(resultInfo.instIndex, remoteTokenInfo.baseInfo.instIndex); + ASSERT_EQ(resultInfo.appID, remoteTokenInfo.baseInfo.appID); + ASSERT_EQ(resultInfo.deviceID, remoteTokenInfo.baseInfo.deviceID); + ASSERT_NE(resultInfo.tokenID, remoteTokenInfo.baseInfo.tokenID); // tokenID already is map tokenID + ASSERT_EQ(resultInfo.tokenAttr, remoteTokenInfo.baseInfo.tokenAttr); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_GRANTED); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo002 + * @tc.desc: set remote hap token info, token info is wrong + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo002 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo rightBaseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + HapTokenInfo wrongBaseInfo = rightBaseInfo; + wrongBaseInfo.apl = (ATokenAplEnum)11; // wrong apl + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = wrongBaseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_NE(ret, RET_SUCCESS); + + std::string wrongStr(10241, 'x'); + + wrongBaseInfo = rightBaseInfo; + wrongBaseInfo.appID = wrongStr; // wrong appID + remoteTokenInfo.baseInfo = wrongBaseInfo; + ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_NE(ret, RET_SUCCESS); + + wrongBaseInfo = rightBaseInfo; + wrongBaseInfo.bundleName = wrongStr; // wrong bundleName + remoteTokenInfo.baseInfo = wrongBaseInfo; + ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_NE(ret, RET_SUCCESS); + + wrongBaseInfo = rightBaseInfo; + wrongBaseInfo.deviceID = wrongStr; // wrong deviceID + remoteTokenInfo.baseInfo = wrongBaseInfo; + ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_NE(ret, RET_SUCCESS); + + wrongBaseInfo = rightBaseInfo; + wrongBaseInfo.tokenID = 0; // wrong tokenID + remoteTokenInfo.baseInfo = wrongBaseInfo; + ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_NE(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo003 + * @tc.desc: set remote hap token wrong permission grant + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo003, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo003 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {11}, // wrong flags + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + // Get local map token ID + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_DENIED); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo004 + * @tc.desc: update remote hap token when remote exist + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo004, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo004 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, // first denied + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + // Get local map token ID + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_DENIED); + + remoteTokenInfo.permStateList[0].grantStatus[0] = PermissionState::PERMISSION_GRANTED; // second granted + ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_GRANTED); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo005 + * @tc.desc: add remote hap token, it can not grant by GrantPermission + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo005, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo005 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, // first denied + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + // Get local map token ID + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_DENIED); + + ret = AccessTokenKit::GrantPermission(mapID, "ohos.permission.test1", PermissionFlag::PERMISSION_SYSTEM_FIXED); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_DENIED); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo006 + * @tc.desc: add remote hap token, it can not revoke by RevokePermission + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo006, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo006 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, // first grant + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + // Get local map token ID + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_GRANTED); + + ret = AccessTokenKit::RevokePermission(mapID, "ohos.permission.test1", PermissionFlag::PERMISSION_SYSTEM_FIXED); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_GRANTED); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo007 + * @tc.desc: add remote hap token, it can not delete by DeleteToken + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo007, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo007 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, // first denied + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + // Get local map token ID + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + ret = AccessTokenKit::DeleteToken(mapID); + ASSERT_EQ(ret, RET_FAILED); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo008 + * @tc.desc: add remote hap token, it can not update by UpdateHapToken + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo008, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo008 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + int32_t DEFAULT_API_VERSION = 8; + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, // first denied + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + // Get local map token ID + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + HapPolicyParams policy; + + ret = AccessTokenKit::UpdateHapToken(mapID, "updateFailed", DEFAULT_API_VERSION, policy); + ASSERT_EQ(ret, RET_FAILED); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo009 + * @tc.desc: add remote hap token, it can not clear by ClearUserGrantedPermissionState + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo009, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo009 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + // Get local map token ID + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_GRANTED); + + ret = AccessTokenKit::ClearUserGrantedPermissionState(mapID); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = AccessTokenKit::VerifyAccessToken(mapID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_GRANTED); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteHapTokenInfo010 + * @tc.desc: tokenID is not hap token + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteHapTokenInfo010, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteHapTokenInfo009 start."); + std::string deviceID = udid_; + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x28100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_NE(ret, RET_SUCCESS); +} + +/** + * @tc.name: DeleteRemoteDeviceToken001 + * @tc.desc: delete exist device mapping tokenId + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, DeleteRemoteDeviceToken001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "DeleteRemoteDeviceTokens001 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = deviceID, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + HapTokenInfo info; + ret = AccessTokenKit::GetHapTokenInfo(mapID, info); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = AccessTokenKit::GetHapTokenInfo(mapID, info); + ASSERT_NE(ret, RET_SUCCESS); +} + +/** + * @tc.name: DeleteRemoteDeviceToken002 + * @tc.desc: delete exist device mapping tokenId + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, DeleteRemoteDeviceToken002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "DeleteRemoteDeviceTokens001 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = deviceID, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + HapTokenInfo info; + ret = AccessTokenKit::GetHapTokenInfo(mapID, info); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0); + ASSERT_NE(ret, RET_SUCCESS); + + // deviceID is wrong + std::string wrongStr(10241, 'x'); + deviceID = wrongStr; + ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_NE(ret, RET_SUCCESS); +} + +/** + * @tc.name: DeleteRemoteDeviceToken003 + * @tc.desc: delete exist device mapping tokenId + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, DeleteRemoteDeviceToken003, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "DeleteRemoteDeviceToken003 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + + int ret = AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + ASSERT_NE(ret, RET_SUCCESS); +} + +/** + * @tc.name: DeleteRemoteDeviceTokens001 + * @tc.desc: delete all mapping tokens of exist device + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, DeleteRemoteDeviceTokens001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "DeleteRemoteDeviceTokens001 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100001); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + HapTokenInfoForSync remoteTokenInfo1 = remoteTokenInfo; + remoteTokenInfo1.baseInfo.tokenID = 0x20100001; + remoteTokenInfo1.baseInfo.bundleName = "com.ohos.access_token1"; + ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo1); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + AccessTokenID mapID1 = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100001); + ASSERT_NE(mapID1, 0); + + ret = AccessTokenKit::DeleteRemoteDeviceTokens(deviceID); + ASSERT_EQ(ret, RET_SUCCESS); + + HapTokenInfo info; + ret = AccessTokenKit::GetHapTokenInfo(mapID, info); + ASSERT_NE(ret, RET_SUCCESS); + ret = AccessTokenKit::GetHapTokenInfo(mapID1, info); + ASSERT_NE(ret, RET_SUCCESS); +} + +/** + * @tc.name: DeleteRemoteDeviceTokens002 + * @tc.desc: delete all mapping tokens of NOT exist device + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, DeleteRemoteDeviceTokens002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "DeleteRemoteDeviceTokens002 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100001); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + HapTokenInfoForSync remoteTokenInfo1 = remoteTokenInfo; + remoteTokenInfo1.baseInfo.tokenID = 0x20100001; + remoteTokenInfo1.baseInfo.bundleName = "com.ohos.access_token1"; + ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo1); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + AccessTokenID mapID1 = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100001); + ASSERT_NE(mapID1, 0); + + ret = AccessTokenKit::DeleteRemoteDeviceTokens("1111111"); + ASSERT_NE(ret, RET_SUCCESS); + + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100001); +} + +/** + * @tc.name: GetHapTokenInfoFromRemote001 + * @tc.desc: get normal local tokenInfo + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, GetHapTokenInfoFromRemote001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetHapTokenInfoFromRemote001 start."); + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + AccessTokenID localTokenID = tokenIdEx.tokenIdExStruct.tokenID; + + HapTokenInfoForSync infoSync; + int ret = AccessTokenKit::GetHapTokenInfoFromRemote(localTokenID, infoSync); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(infoSync.baseInfo.apl, g_infoManagerTestPolicyPrams.apl); + ASSERT_EQ(infoSync.permStateList.size(), 2); + ASSERT_EQ(infoSync.permStateList[1].grantFlags.size(), 2); + + ASSERT_EQ(infoSync.permStateList[0].permissionName, g_infoManagerTestPolicyPrams.permStateList[0].permissionName); + ASSERT_EQ(infoSync.permStateList[0].grantFlags[0], g_infoManagerTestPolicyPrams.permStateList[0].grantFlags[0]); + ASSERT_EQ(infoSync.permStateList[0].grantStatus[0], g_infoManagerTestPolicyPrams.permStateList[0].grantStatus[0]); + ASSERT_EQ(infoSync.permStateList[0].resDeviceID[0], g_infoManagerTestPolicyPrams.permStateList[0].resDeviceID[0]); + ASSERT_EQ(infoSync.permStateList[0].isGeneral, g_infoManagerTestPolicyPrams.permStateList[0].isGeneral); + + ASSERT_EQ(infoSync.permStateList[1].permissionName, g_infoManagerTestPolicyPrams.permStateList[1].permissionName); + ASSERT_EQ(infoSync.permStateList[1].grantFlags[0], g_infoManagerTestPolicyPrams.permStateList[1].grantFlags[0]); + ASSERT_EQ(infoSync.permStateList[1].grantStatus[0], g_infoManagerTestPolicyPrams.permStateList[1].grantStatus[0]); + ASSERT_EQ(infoSync.permStateList[1].resDeviceID[0], g_infoManagerTestPolicyPrams.permStateList[1].resDeviceID[0]); + ASSERT_EQ(infoSync.permStateList[1].isGeneral, g_infoManagerTestPolicyPrams.permStateList[1].isGeneral); + + ASSERT_EQ(infoSync.permStateList[1].grantFlags[1], g_infoManagerTestPolicyPrams.permStateList[1].grantFlags[1]); + ASSERT_EQ(infoSync.permStateList[1].grantStatus[1], g_infoManagerTestPolicyPrams.permStateList[1].grantStatus[1]); + ASSERT_EQ(infoSync.permStateList[1].resDeviceID[1], g_infoManagerTestPolicyPrams.permStateList[1].resDeviceID[1]); + + ASSERT_EQ(infoSync.baseInfo.bundleName, g_infoManagerTestInfoParms.bundleName); + ASSERT_EQ(infoSync.baseInfo.userID, g_infoManagerTestInfoParms.userID); + ASSERT_EQ(infoSync.baseInfo.instIndex, g_infoManagerTestInfoParms.instIndex); + ASSERT_EQ(infoSync.baseInfo.appID, g_infoManagerTestInfoParms.appIDDesc); + ASSERT_EQ(infoSync.baseInfo.ver, 1); + ASSERT_EQ(infoSync.baseInfo.tokenID, localTokenID); + ASSERT_EQ(infoSync.baseInfo.tokenAttr, 0); + + AccessTokenKit::DeleteToken(localTokenID); +} + +/** + * @tc.name: GetHapTokenInfoFromRemote002 + * @tc.desc: get remote mapping tokenInfo + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, GetHapTokenInfoFromRemote002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetHapTokenInfoFromRemote002 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); + + HapTokenInfoForSync infoSync; + ret = AccessTokenKit::GetHapTokenInfoFromRemote(mapID, infoSync); + ASSERT_NE(ret, RET_SUCCESS); + + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); +} + +/** + * @tc.name: GetHapTokenInfoFromRemote003 + * @tc.desc: get wrong tokenInfo + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, GetHapTokenInfoFromRemote003, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetHapTokenInfoFromRemote003 start."); + HapTokenInfoForSync infoSync; + int ret = AccessTokenKit::GetHapTokenInfoFromRemote(0, infoSync); + ASSERT_NE(ret, RET_SUCCESS); +} + +/** + * @tc.name: AllocLocalTokenID001 + * @tc.desc: get already mapping tokenInfo, makesure ipc right + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, AllocLocalTokenID001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "AllocLocalTokenID001 start."); + std::string deviceID = udid_; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = udid_, + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkId_, 0x20100000); + ASSERT_NE(mapID, 0); +} + +/** + * @tc.name: GetAllNativeTokenInfo001 + * @tc.desc: get all native token with dcaps + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, GetAllNativeTokenInfo001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetAllNativeTokenInfo001 start."); + + std::vector nativeTokenInfosRes; + int ret = AccessTokenKit::GetAllNativeTokenInfo(nativeTokenInfosRes); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SetRemoteNativeTokenInfo001 + * @tc.desc: set already mapping tokenInfo + * @tc.type: FUNC + * @tc.require:issue I5R4UF + */ +HWTEST_F(RemoteTokenKitTest, SetRemoteNativeTokenInfo001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SetRemoteNativeTokenInfo001 start."); + std::string deviceID = udid_; + + NativeTokenInfoForSync native1 = { + .baseInfo.apl = APL_NORMAL, + .baseInfo.ver = 1, + .baseInfo.processName = "native_test1", + .baseInfo.dcap = {"SYSDCAP", "DMSDCAP"}, + .baseInfo.tokenID = 0x28000000, + .baseInfo.tokenAttr = 0, + .baseInfo.nativeAcls = {"ohos.permission.DISTRIBUTED_DATASYNC"}, + }; + + std::vector nativeTokenInfoList; + nativeTokenInfoList.emplace_back(native1); + + int ret = AccessTokenKit::SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoList); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::GetRemoteNativeTokenID(deviceID, 0x28000000); + ASSERT_NE(mapID, 0); + + NativeTokenInfo resultInfo; + ret = AccessTokenKit::GetNativeTokenInfo(mapID, resultInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + ASSERT_EQ(resultInfo.apl, native1.baseInfo.apl); + ASSERT_EQ(resultInfo.ver, native1.baseInfo.ver); + ASSERT_EQ(resultInfo.processName, native1.baseInfo.processName); + ASSERT_EQ(resultInfo.dcap.size(), 2); + ASSERT_EQ(resultInfo.dcap[0], "SYSDCAP"); + ASSERT_EQ(resultInfo.dcap[1], "DMSDCAP"); + ASSERT_EQ(resultInfo.nativeAcls.size(), 1); + ASSERT_EQ(resultInfo.nativeAcls[0], "ohos.permission.DISTRIBUTED_DATASYNC"); + ASSERT_EQ(resultInfo.tokenID, mapID); + ASSERT_EQ(resultInfo.tokenAttr, native1.baseInfo.tokenAttr); +} +#endif \ No newline at end of file diff --git a/interfaces/innerkits/accesstoken/test/unittest/src/remote_token_kit_test.h b/interfaces/innerkits/accesstoken/test/unittest/src/remote_token_kit_test.h new file mode 100644 index 0000000000000000000000000000000000000000..0c7a6921dd3ce0620077742821134fbdc906e516 --- /dev/null +++ b/interfaces/innerkits/accesstoken/test/unittest/src/remote_token_kit_test.h @@ -0,0 +1,46 @@ +/* + * 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 REMOTE_TOKEN_KIT_TEST_H +#define REMOTE_TOKEN_KIT_TEST_H + +#include +#include "access_token.h" +#include "permission_def.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RemoteTokenKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + unsigned int GetAccessTokenID(int userID, std::string bundleName, int instIndex); + void DeleteTestToken() const; + void AllocTestToken() const; + uint64_t selfTokenId_; + std::string udid_; + std::string networkId_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // REMOTE_TOKEN_KIT_TEST_H \ No newline at end of file diff --git a/interfaces/innerkits/nativetoken/src/nativetoken.c b/interfaces/innerkits/nativetoken/src/nativetoken.c index 3136a16e28403d3664a1e9c1b8450ed6dc801974..ae9cc4186d68a36b75bf63ea36a6199933ebd3a7 100644 --- a/interfaces/innerkits/nativetoken/src/nativetoken.c +++ b/interfaces/innerkits/nativetoken/src/nativetoken.c @@ -281,13 +281,11 @@ static NativeAtId CreateNativeTokenId(const char *processName) { uint32_t rand; NativeAtId tokenId; - int32_t ret; AtInnerInfo *innerId = (AtInnerInfo *)(&tokenId); int32_t retry = MAX_RETRY_TIMES; while (retry > 0) { - ret = GetRandomTokenId(&rand); - if (ret != ATRET_SUCCESS) { + if (GetRandomTokenId(&rand) != ATRET_SUCCESS) { return INVALID_TOKEN_ID; } if (IsTokenUniqueIdExist(rand & (TOKEN_RANDOM_MASK)) == 0) { @@ -333,9 +331,6 @@ static int32_t GetAplLevel(const char *aplStr) static void WriteToFile(const cJSON *root) { - size_t strLen; - ssize_t writtenLen; - char *jsonStr = NULL; jsonStr = cJSON_PrintUnformatted(root); if (jsonStr == NULL) { @@ -350,8 +345,8 @@ static void WriteToFile(const cJSON *root) AT_LOG_ERROR("[ATLIB-%s]:open failed.", __func__); break; } - strLen = strlen(jsonStr); - writtenLen = write(fd, (void *)jsonStr, (size_t)strLen); + size_t strLen = strlen(jsonStr); + ssize_t writtenLen = write(fd, (void *)jsonStr, (size_t)strLen); close(fd); if (writtenLen < 0 || (size_t)writtenLen != strLen) { AT_LOG_ERROR("[ATLIB-%s]:write failed, writtenLen is %zu.", __func__, writtenLen); diff --git a/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp b/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp index bfc684e18ea57ad52ae81b93ebae9cfe6e825919..558cb0cf841bd0b5f2b01725a188360f81d59741 100644 --- a/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp +++ b/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp @@ -738,7 +738,6 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback001, TestSize.Level1) ASSERT_EQ(PERM_INACTIVE, callbackPtr->type_); } - class CbCustomizeTest3 : public PermActiveStatusCustomizedCbk { public: explicit CbCustomizeTest3(const std::vector &permList) @@ -759,7 +758,6 @@ public: * @tc.type: FUNC * @tc.require: issueI5NT1X issueI5P4IU issueI5P530 */ - HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback002, TestSize.Level1) { std::vector permList1 = {"ohos.permission.CAMERA"}; @@ -820,7 +818,6 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback002, TestSize.Level1) * @tc.type: FUNC * @tc.require: issueI5NT1X */ - HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback003, TestSize.Level1) { std::vector permList; @@ -845,7 +842,6 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback003, TestSize.Level1) * @tc.type: FUNC * @tc.require: issueI5NT1X */ - HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback004, TestSize.Level1) { std::vector permList = {"ohos.permission.CAMERA"}; @@ -877,7 +873,6 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback004, TestSize.Level1) * @tc.type: FUNC * @tc.require: issueI5NT1X */ - HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback005, TestSize.Level1) { std::vector permList = {"ohos.permission.INVALD"}; @@ -900,10 +895,8 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback005, TestSize.Level1) * @tc.type: FUNC * @tc.require: issueI5NT1X */ - HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback006, TestSize.Level1) { - std::vector permList = {"ohos.permission.CAMERA"}; auto callbackPtr = std::make_shared(permList); int32_t res = PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr); @@ -916,7 +909,6 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback006, TestSize.Level1) * @tc.type: FUNC * @tc.require: issueI5NT1X */ - HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback007, TestSize.Level1) { std::vector permList = {"ohos.permission.CAMERA"}; @@ -931,6 +923,21 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback007, TestSize.Level1) ASSERT_EQ(RET_ERROR, res); } +/** + * @tc.name: IsAllowedUsingPermission001 + * @tc.desc: IsAllowedUsingPermission with invalid tokenId or permission. + * @tc.type: FUNC + * @tc.require: issueI5RWX3 issueI5RWX8 + */ +HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission001, TestSize.Level1) +{ + std::string permissionName = "ohos.permission.CAMERA"; + bool ret = PrivacyKit::IsAllowedUsingPermission(g_TokenId_E, permissionName); + ASSERT_EQ(false, ret); + ret = PrivacyKit::IsAllowedUsingPermission(0, permissionName); + ASSERT_EQ(false, ret); +} + /** * @tc.name: StartUsingPermission001 * @tc.desc: StartUsingPermission with invalid tokenId or permission. @@ -966,7 +973,6 @@ HWTEST_F(PrivacyKitTest, StartUsingPermission002, TestSize.Level1) ASSERT_EQ(RET_NO_ERROR, ret); } - /** * @tc.name: StopUsingPermission003 * @tc.desc: Add record when StopUsingPermission is called. diff --git a/interfaces/kits/accesstoken/napi/include/napi_atmanager.h b/interfaces/kits/accesstoken/napi/include/napi_atmanager.h index d208a4912e70aeeada61d1651014d9cfe0687c39..976eeda60361e1b04b0e4cb3933ee616199af886 100644 --- a/interfaces/kits/accesstoken/napi/include/napi_atmanager.h +++ b/interfaces/kits/accesstoken/napi/include/napi_atmanager.h @@ -104,6 +104,7 @@ private: static napi_value GrantUserGrantedPermission(napi_env env, napi_callback_info info); static napi_value RevokeUserGrantedPermission(napi_env env, napi_callback_info info); static napi_value GetPermissionFlags(napi_env env, napi_callback_info info); + static napi_value GetVersion(napi_env env, napi_callback_info info); static void ParseInputVerifyPermissionOrGetFlag(const napi_env env, const napi_callback_info info, AtManagerAsyncContext& asyncContext); @@ -111,11 +112,13 @@ private: static void VerifyAccessTokenComplete(napi_env env, napi_status status, void *data); static void ParseInputGrantOrRevokePermission(const napi_env env, const napi_callback_info info, AtManagerAsyncContext& asyncContext); - static void GrantUserGrantedPermissionExcute(napi_env env, void *data); + static void GrantUserGrantedPermissionExecute(napi_env env, void *data); static void GrantUserGrantedPermissionComplete(napi_env env, napi_status status, void *data); - static void RevokeUserGrantedPermissionExcute(napi_env env, void *data); + static void RevokeUserGrantedPermissionExecute(napi_env env, void *data); static void RevokeUserGrantedPermissionComplete(napi_env env, napi_status status, void *data); - static void GetPermissionFlagsExcute(napi_env env, void *data); + static void GetVersionExecute(napi_env env, void *data); + static void GetVersionComplete(napi_env env, napi_status status, void *data); + static void GetPermissionFlagsExecute(napi_env env, void *data); static void GetPermissionFlagsComplete(napi_env env, napi_status status, void *data); static void SetNamedProperty(napi_env env, napi_value dstObj, const int32_t objValue, const char *propName); static bool ParseInputToRegister(const napi_env env, napi_callback_info cbInfo, diff --git a/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp b/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp index aa0628df1748a3c487e78de68055ce979c44a5b2..b88c100156ec59c2f9f4afb554c153ac95da6afc 100644 --- a/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp +++ b/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp @@ -167,6 +167,7 @@ napi_value NapiAtManager::Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getPermissionFlags", GetPermissionFlags), DECLARE_NAPI_FUNCTION("on", RegisterPermStateChangeCallback), DECLARE_NAPI_FUNCTION("off", UnregisterPermStateChangeCallback), + DECLARE_NAPI_FUNCTION("getVersion", GetVersion), }; napi_value cons = nullptr; @@ -410,7 +411,7 @@ void NapiAtManager::ParseInputGrantOrRevokePermission(const napi_env env, const asyncContext.tokenId, asyncContext.permissionName, asyncContext.flag); } -void NapiAtManager::GrantUserGrantedPermissionExcute(napi_env env, void *data) +void NapiAtManager::GrantUserGrantedPermissionExecute(napi_env env, void *data) { AtManagerAsyncContext* asyncContext = reinterpret_cast(data); PermissionDef permissionDef; @@ -474,6 +475,54 @@ void NapiAtManager::GrantUserGrantedPermissionComplete(napi_env env, napi_status delete asyncContext; } +napi_value NapiAtManager::GetVersion(napi_env env, napi_callback_info info) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetVersion begin."); + + auto *asyncContext = new (std::nothrow) AtManagerAsyncContext(); // for async work deliver data + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + std::unique_ptr context {asyncContext}; + asyncContext->result = AT_PERM_OPERA_FAIL; + + napi_value result = nullptr; + NAPI_CALL(env, napi_create_promise(env, &(asyncContext->deferred), &result)); + + napi_value resource = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, "GetVersion", NAPI_AUTO_LENGTH, &resource)); + + NAPI_CALL(env, napi_create_async_work(env, nullptr, resource, GetVersionExecute, GetVersionComplete, + reinterpret_cast(asyncContext), &(asyncContext->work))); + NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work)); + + context.release(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetVersion end."); + return result; +} + +void NapiAtManager::GetVersionExecute(napi_env env, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + asyncContext->result = AccessTokenKit::GetVersion(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "version result = %{public}d.", asyncContext->result); +} + +void NapiAtManager::GetVersionComplete(napi_env env, napi_status status, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + napi_value result; + + ACCESSTOKEN_LOG_DEBUG(LABEL, "version result = %{public}d.", asyncContext->result); + + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, asyncContext->result, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncContext->deferred, result)); + + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, asyncContext->work)); + delete asyncContext; +} + napi_value NapiAtManager::GrantUserGrantedPermission(napi_env env, napi_callback_info info) { ACCESSTOKEN_LOG_DEBUG(LABEL, "GrantUserGrantedPermission begin."); @@ -507,7 +556,7 @@ napi_value NapiAtManager::GrantUserGrantedPermission(napi_env env, napi_callback napi_create_string_utf8(env, "GrantUserGrantedPermission", NAPI_AUTO_LENGTH, &resource); napi_create_async_work( // define work - env, nullptr, resource, GrantUserGrantedPermissionExcute, GrantUserGrantedPermissionComplete, + env, nullptr, resource, GrantUserGrantedPermissionExecute, GrantUserGrantedPermissionComplete, reinterpret_cast(asyncContext), &(asyncContext->work)); napi_queue_async_work(env, asyncContext->work); // add async work handle to the napi queue and wait for result @@ -517,7 +566,7 @@ napi_value NapiAtManager::GrantUserGrantedPermission(napi_env env, napi_callback return result; } -void NapiAtManager::RevokeUserGrantedPermissionExcute(napi_env env, void *data) +void NapiAtManager::RevokeUserGrantedPermissionExecute(napi_env env, void *data) { AtManagerAsyncContext* asyncContext = reinterpret_cast(data); PermissionDef permissionDef; @@ -614,7 +663,7 @@ napi_value NapiAtManager::RevokeUserGrantedPermission(napi_env env, napi_callbac napi_create_string_utf8(env, "RevokeUserGrantedPermission", NAPI_AUTO_LENGTH, &resource); napi_create_async_work( // define work - env, nullptr, resource, RevokeUserGrantedPermissionExcute, RevokeUserGrantedPermissionComplete, + env, nullptr, resource, RevokeUserGrantedPermissionExecute, RevokeUserGrantedPermissionComplete, reinterpret_cast(asyncContext), &(asyncContext->work)); napi_queue_async_work(env, asyncContext->work); // add async work handle to the napi queue and wait for result @@ -624,7 +673,7 @@ napi_value NapiAtManager::RevokeUserGrantedPermission(napi_env env, napi_callbac return result; } -void NapiAtManager::GetPermissionFlagsExcute(napi_env env, void *data) +void NapiAtManager::GetPermissionFlagsExecute(napi_env env, void *data) { AtManagerAsyncContext* asyncContext = reinterpret_cast(data); @@ -676,7 +725,7 @@ napi_value NapiAtManager::GetPermissionFlags(napi_env env, napi_callback_info in napi_create_string_utf8(env, "VerifyAccessToken", NAPI_AUTO_LENGTH, &resource); napi_create_async_work( // define work - env, nullptr, resource, GetPermissionFlagsExcute, GetPermissionFlagsComplete, + env, nullptr, resource, GetPermissionFlagsExecute, GetPermissionFlagsComplete, reinterpret_cast(asyncContext), &(asyncContext->work)); napi_queue_async_work(env, asyncContext->work); // add async work handle to the napi queue and wait for result diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h index 6fb115250644bf122d75fb13971fc53f09643fb6..2c80e16c60252edc0c434acc2e359de50a139944 100644 --- a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h @@ -71,13 +71,16 @@ private: void DumpTokenInfoInner(MessageParcel& data, MessageParcel& reply); - bool IsAuthorizedCalling() const; - bool IsAccessTokenCalling() const; + bool IsPrivilegedCalling() const; + bool IsAccessTokenCalling(); bool IsNativeProcessCalling(); + bool IsFoundationCalling() const; static const int32_t SYSTEM_UID = 1000; static const int32_t ROOT_UID = 0; static const int32_t ACCESSTOKEN_UID = 3020; + AccessTokenID tokenSyncId_ = 0; + using RequestFuncType = void (AccessTokenManagerStub::*)(MessageParcel &data, MessageParcel &reply); std::map requestFuncMap_; }; diff --git a/services/accesstokenmanager/main/cpp/src/callback/callback_manager.cpp b/services/accesstokenmanager/main/cpp/src/callback/callback_manager.cpp index 208e9b73b850d39a44539bd586d908c104baa4e5..c77bc8caa805a22f0f8ac5ef5b8a88bc854c469b 100644 --- a/services/accesstokenmanager/main/cpp/src/callback/callback_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/callback/callback_manager.cpp @@ -102,12 +102,8 @@ bool CallbackManager::CalledAccordingToTokenIdLlist( if (tokenIDList.empty()) { return true; } - for (const auto& id : tokenIDList) { - if (id == tokenID) { - return true; - } - } - return false; + return std::any_of(tokenIDList.begin(), tokenIDList.end(), + [tokenID](AccessTokenID id) { return id == tokenID; }); } bool CallbackManager::CalledAccordingToPermLlist(const std::vector& permList, const std::string& permName) @@ -115,12 +111,8 @@ bool CallbackManager::CalledAccordingToPermLlist(const std::vector& if (permList.empty()) { return true; } - for (const auto& perm : permList) { - if (perm == permName) { - return true; - } - } - return false; + return std::any_of(permList.begin(), permList.end(), + [permName](const std::string& perm) { return perm == permName; }); } void CallbackManager::ExecuteCallbackAsync(AccessTokenID tokenID, const std::string& permName, int32_t changeType) diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp index 932c6515bcd81c61cb580ff174d684542333d32f..42a3ad1e2d88d3a1d0b8d4c1dceb4ea7349665dd 100644 --- a/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp @@ -149,7 +149,6 @@ void PermissionDefinitionCache::GetDefPermissionsByTokenId(std::vector& permDefRes) { - std::vector permDataList; for (const GenericValues& defValue : permDefRes) { PermissionDef def; AccessTokenID tokenId = (AccessTokenID)defValue.GetInt(FIELD_TOKEN_ID); diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp index 545e9dc8c2bed1b4747ef4d986c471c1aee9e0c4..536d95bcc497f670686d79f9a0593cd13b77c5e9 100644 --- a/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp @@ -234,16 +234,17 @@ void PermissionManager::GetSelfPermissionState(std::vector return; } - for (const auto& perm : permsList) { - if (perm.permissionName == permState.permissionName) { - ACCESSTOKEN_LOG_INFO(LABEL, "find goal permission: %{public}s, status: %{public}d, flag: %{public}d", - permState.permissionName.c_str(), perm.grantStatus[0], perm.grantFlags[0]); - foundGoal = true; - goalGrantStatus = perm.grantStatus[0]; - goalGrantFlags = static_cast(perm.grantFlags[0]); - break; - } + auto iter = std::find_if(permsList.begin(), permsList.end(), [permState](const PermissionStateFull& perm) { + return permState.permissionName == perm.permissionName; + }); + if (iter != permsList.end()) { + ACCESSTOKEN_LOG_INFO(LABEL, "find goal permission: %{public}s, status: %{public}d, flag: %{public}d", + permState.permissionName.c_str(), iter->grantStatus[0], iter->grantFlags[0]); + foundGoal = true; + goalGrantStatus = iter->grantStatus[0]; + goalGrantFlags = static_cast(iter->grantFlags[0]); } + if (foundGoal == false) { ACCESSTOKEN_LOG_WARN(LABEL, "can not find permission: %{public}s define!", permState.permissionName.c_str()); diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp index c0b766dde6fb739ec3b18c1f2c563f8138502c8e..383f5de97fa3e9e8a440a523faf53dedeb8a9137 100644 --- a/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp @@ -61,12 +61,15 @@ void PermissionPolicySet::Update(const std::vector& permSta PermissionValidator::FilterInvalidPermissionState(permStateList, permStateFilterList); Utils::UniqueWriteGuard infoGuard(this->permPolicySetLock_); + for (PermissionStateFull& permStateNew : permStateFilterList) { - for (const PermissionStateFull& permStateOld : permStateList_) { - if (permStateNew.permissionName == permStateOld.permissionName) { - UpdatePermStateFull(permStateOld, permStateNew); - break; - } + auto iter = std::find_if(permStateList_.begin(), permStateList_.end(), + [permStateNew](const PermissionStateFull& permStateOld) { + return permStateNew.permissionName == permStateOld.permissionName; + }); + if (iter != permStateList_.end()) { + UpdatePermStateFull(*iter, permStateNew); + break; } } permStateList_ = permStateFilterList; @@ -186,19 +189,20 @@ bool PermissionPolicySet::UpdatePermissionStatus(const std::string& permissionNa bool ret = false; Utils::UniqueWriteGuard infoGuard(this->permPolicySetLock_); - for (auto& perm : permStateList_) { - if (perm.permissionName == permissionName) { - if (perm.isGeneral) { - int32_t oldStatus = perm.grantStatus[0]; - perm.grantStatus[0] = isGranted ? PERMISSION_GRANTED : PERMISSION_DENIED; - uint32_t currFlag = static_cast(perm.grantFlags[0]); - uint32_t newFlag = flag | (currFlag & PERMISSION_GRANTED_BY_POLICY); - perm.grantFlags[0] = static_cast(newFlag); - ret = (oldStatus == perm.grantStatus[0]) ? false : true; - } else { - ACCESSTOKEN_LOG_WARN(LABEL, "perm isGeneral is false."); - } - break; + auto iter = std::find_if(permStateList_.begin(), permStateList_.end(), + [permissionName](const PermissionStateFull& permState) { + return permissionName == permState.permissionName; + }); + if (iter != permStateList_.end()) { + if (iter->isGeneral) { + int32_t oldStatus = iter->grantStatus[0]; + iter->grantStatus[0] = isGranted ? PERMISSION_GRANTED : PERMISSION_DENIED; + uint32_t currFlag = static_cast(iter->grantFlags[0]); + uint32_t newFlag = flag | (currFlag & PERMISSION_GRANTED_BY_POLICY); + iter->grantFlags[0] = static_cast(newFlag); + ret = (oldStatus == iter->grantStatus[0]) ? false : true; + } else { + ACCESSTOKEN_LOG_WARN(LABEL, "perm isGeneral is false."); } } diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp index f51a99ec35d5e88824281d30cae5d457816f3095..5973700701fa48f413309dac1382cce9968839bb 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp @@ -15,6 +15,7 @@ #include "accesstoken_manager_service.h" +#include #include #include #include @@ -372,10 +373,9 @@ int AccessTokenManagerService::SetRemoteNativeTokenInfo(const std::string& devic ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); std::vector nativeList; - - for (const auto& nativeParcel : nativeTokenInfoForSyncParcel) { - nativeList.emplace_back(nativeParcel.nativeTokenInfoForSyncParams); - } + std::transform(nativeTokenInfoForSyncParcel.begin(), + nativeTokenInfoForSyncParcel.end(), std::back_inserter(nativeList), + [](const auto& nativeParcel) { return nativeParcel.nativeTokenInfoForSyncParams; }); return AccessTokenInfoManager::GetInstance().SetRemoteNativeTokenInfo(deviceID, nativeList); } diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp index a678b578255ba731b6b6b74bd32be09edbd9e9d6..a9d6572b1b2f275d6e6c1c297f1178a43c3304d0 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp @@ -59,7 +59,7 @@ int32_t AccessTokenManagerStub::OnRemoteRequest( void AccessTokenManagerStub::DeleteTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling()) { + if (!IsFoundationCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); reply.WriteInt32(RET_FAILED); return; @@ -148,7 +148,7 @@ void AccessTokenManagerStub::GetPermissionFlagInner(MessageParcel& data, Message ACCESSTOKEN_LOG_INFO(LABEL, "callingTokenID: %{public}u", callingTokenID); AccessTokenID tokenID = data.ReadUint32(); std::string permissionName = data.ReadString(); - if (!IsAuthorizedCalling() && + if (!IsPrivilegedCalling() && VerifyAccessToken(callingTokenID, GRANT_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED && VerifyAccessToken(callingTokenID, REVOKE_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED && VerifyAccessToken(callingTokenID, GET_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED) { @@ -167,7 +167,7 @@ void AccessTokenManagerStub::GrantPermissionInner(MessageParcel& data, MessagePa AccessTokenID tokenID = data.ReadUint32(); std::string permissionName = data.ReadString(); int flag = data.ReadInt32(); - if (!IsAuthorizedCalling() && + if (!IsPrivilegedCalling() && !IsFoundationCalling() && VerifyAccessToken(callingTokenID, GRANT_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED) { HiviewDFX::HiSysEvent::Write(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_VERIFY_REPORT", HiviewDFX::HiSysEvent::EventType::SECURITY, "CODE", VERIFY_PERMISSION_ERROR, @@ -187,7 +187,7 @@ void AccessTokenManagerStub::RevokePermissionInner(MessageParcel& data, MessageP AccessTokenID tokenID = data.ReadUint32(); std::string permissionName = data.ReadString(); int flag = data.ReadInt32(); - if (!IsAuthorizedCalling() && + if (!IsPrivilegedCalling() && !IsFoundationCalling() && VerifyAccessToken(callingTokenID, REVOKE_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED) { HiviewDFX::HiSysEvent::Write(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_VERIFY_REPORT", HiviewDFX::HiSysEvent::EventType::SECURITY, "CODE", VERIFY_PERMISSION_ERROR, @@ -202,6 +202,16 @@ void AccessTokenManagerStub::RevokePermissionInner(MessageParcel& data, MessageP void AccessTokenManagerStub::ClearUserGrantedPermissionStateInner(MessageParcel& data, MessageParcel& reply) { + uint32_t callingTokenID = IPCSkeleton::GetCallingTokenID(); + if (!IsPrivilegedCalling() && !IsFoundationCalling() && + VerifyAccessToken(callingTokenID, REVOKE_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED) { + HiviewDFX::HiSysEvent::Write(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_VERIFY_REPORT", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CODE", VERIFY_PERMISSION_ERROR, + "CALLER_TOKENID", callingTokenID); + ACCESSTOKEN_LOG_ERROR(LABEL, "permission denied(tokenID=%{public}d)", callingTokenID); + reply.WriteInt32(RET_FAILED); + return; + } AccessTokenID tokenID = data.ReadUint32(); int result = this->ClearUserGrantedPermissionState(tokenID); reply.WriteInt32(result); @@ -210,7 +220,7 @@ void AccessTokenManagerStub::ClearUserGrantedPermissionStateInner(MessageParcel& void AccessTokenManagerStub::AllocHapTokenInner(MessageParcel& data, MessageParcel& reply) { AccessTokenIDEx res = {0}; - if (!IsAuthorizedCalling()) { + if (!IsFoundationCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -236,7 +246,7 @@ void AccessTokenManagerStub::GetTokenTypeInner(MessageParcel& data, MessageParce void AccessTokenManagerStub::CheckNativeDCapInner(MessageParcel& data, MessageParcel& reply) { - if (!IsNativeProcessCalling()) { + if (!IsNativeProcessCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -249,7 +259,7 @@ void AccessTokenManagerStub::CheckNativeDCapInner(MessageParcel& data, MessagePa void AccessTokenManagerStub::GetHapTokenIDInner(MessageParcel& data, MessageParcel& reply) { - if (!IsNativeProcessCalling()) { + if (!IsNativeProcessCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(INVALID_TOKENID); return; @@ -263,7 +273,7 @@ void AccessTokenManagerStub::GetHapTokenIDInner(MessageParcel& data, MessageParc void AccessTokenManagerStub::AllocLocalTokenIDInner(MessageParcel& data, MessageParcel& reply) { - if ((!IsAuthorizedCalling()) && (!IsNativeProcessCalling())) { + if ((!IsNativeProcessCalling()) && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(INVALID_TOKENID); return; @@ -276,7 +286,7 @@ void AccessTokenManagerStub::AllocLocalTokenIDInner(MessageParcel& data, Message void AccessTokenManagerStub::UpdateHapTokenInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling()) { + if (!IsFoundationCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -296,7 +306,7 @@ void AccessTokenManagerStub::UpdateHapTokenInner(MessageParcel& data, MessagePar void AccessTokenManagerStub::GetHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - if (!IsNativeProcessCalling()) { + if (!IsNativeProcessCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -310,7 +320,7 @@ void AccessTokenManagerStub::GetHapTokenInfoInner(MessageParcel& data, MessagePa void AccessTokenManagerStub::GetNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - if (!IsNativeProcessCalling()) { + if (!IsNativeProcessCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -325,8 +335,7 @@ void AccessTokenManagerStub::GetNativeTokenInfoInner(MessageParcel& data, Messag void AccessTokenManagerStub::RegisterPermStateChangeCallbackInner(MessageParcel& data, MessageParcel& reply) { uint32_t callingTokenID = IPCSkeleton::GetCallingTokenID(); - if (!IsAuthorizedCalling() && - VerifyAccessToken(callingTokenID, GET_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED) { + if (VerifyAccessToken(callingTokenID, GET_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED) { ACCESSTOKEN_LOG_ERROR(LABEL, "permission denied(tokenID=%{public}d)", callingTokenID); reply.WriteInt32(RET_FAILED); return; @@ -349,8 +358,7 @@ void AccessTokenManagerStub::RegisterPermStateChangeCallbackInner(MessageParcel& void AccessTokenManagerStub::UnRegisterPermStateChangeCallbackInner(MessageParcel& data, MessageParcel& reply) { uint32_t callingTokenID = IPCSkeleton::GetCallingTokenID(); - if (!IsAuthorizedCalling() && - VerifyAccessToken(callingTokenID, GET_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED) { + if (VerifyAccessToken(callingTokenID, GET_SENSITIVE_PERMISSIONS) == PERMISSION_DENIED) { ACCESSTOKEN_LOG_ERROR(LABEL, "permission denied(tokenID=%{public}d)", callingTokenID); reply.WriteInt32(RET_FAILED); return; @@ -367,13 +375,18 @@ void AccessTokenManagerStub::UnRegisterPermStateChangeCallbackInner(MessageParce void AccessTokenManagerStub::ReloadNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) { + if (!IsPrivilegedCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteUint32(RET_FAILED); + return; + } int32_t result = this->ReloadNativeTokenInfo(); reply.WriteInt32(result); } void AccessTokenManagerStub::GetNativeTokenIdInner(MessageParcel& data, MessageParcel& reply) { - if (!IsNativeProcessCalling()) { + if (!IsNativeProcessCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteUint32(INVALID_TOKENID); return; @@ -390,7 +403,7 @@ void AccessTokenManagerStub::GetNativeTokenIdInner(MessageParcel& data, MessageP #ifdef TOKEN_SYNC_ENABLE void AccessTokenManagerStub::GetHapTokenInfoFromRemoteInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + if (!IsAccessTokenCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -405,7 +418,7 @@ void AccessTokenManagerStub::GetHapTokenInfoFromRemoteInner(MessageParcel& data, void AccessTokenManagerStub::GetAllNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + if (!IsAccessTokenCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -421,7 +434,7 @@ void AccessTokenManagerStub::GetAllNativeTokenInfoInner(MessageParcel& data, Mes void AccessTokenManagerStub::SetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + if (!IsAccessTokenCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -439,7 +452,7 @@ void AccessTokenManagerStub::SetRemoteHapTokenInfoInner(MessageParcel& data, Mes void AccessTokenManagerStub::SetRemoteNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + if (!IsAccessTokenCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -469,7 +482,7 @@ void AccessTokenManagerStub::SetRemoteNativeTokenInfoInner(MessageParcel& data, void AccessTokenManagerStub::DeleteRemoteTokenInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + if (!IsAccessTokenCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -483,7 +496,7 @@ void AccessTokenManagerStub::DeleteRemoteTokenInner(MessageParcel& data, Message void AccessTokenManagerStub::GetRemoteNativeTokenIDInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + if (!IsAccessTokenCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(INVALID_TOKENID); return; @@ -497,7 +510,7 @@ void AccessTokenManagerStub::GetRemoteNativeTokenIDInner(MessageParcel& data, Me void AccessTokenManagerStub::DeleteRemoteDeviceTokensInner(MessageParcel& data, MessageParcel& reply) { - if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + if (!IsAccessTokenCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -511,7 +524,7 @@ void AccessTokenManagerStub::DeleteRemoteDeviceTokensInner(MessageParcel& data, void AccessTokenManagerStub::DumpTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - if (!IsNativeProcessCalling()) { + if (!IsNativeProcessCalling() && !IsPrivilegedCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -522,28 +535,34 @@ void AccessTokenManagerStub::DumpTokenInfoInner(MessageParcel& data, MessageParc reply.WriteString(dumpInfo); } -bool AccessTokenManagerStub::IsAuthorizedCalling() const +bool AccessTokenManagerStub::IsPrivilegedCalling() const { - int callingUid = IPCSkeleton::GetCallingUid(); + // shell process is root in debug mode. + int32_t callingUid = IPCSkeleton::GetCallingUid(); ACCESSTOKEN_LOG_INFO(LABEL, "Calling uid: %{public}d", callingUid); - return callingUid == SYSTEM_UID || callingUid == ROOT_UID || callingUid == FOUNDATION_UID; + return callingUid == SYSTEM_UID || callingUid == ROOT_UID; } -bool AccessTokenManagerStub::IsAccessTokenCalling() const +bool AccessTokenManagerStub::IsFoundationCalling() const { - int callingUid = IPCSkeleton::GetCallingUid(); - return callingUid == ACCESSTOKEN_UID; + int32_t callingUid = IPCSkeleton::GetCallingUid(); + ACCESSTOKEN_LOG_INFO(LABEL, "Calling uid: %{public}d", callingUid); + return callingUid == FOUNDATION_UID; +} + +bool AccessTokenManagerStub::IsAccessTokenCalling() +{ + int tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenSyncId_ == 0) { + tokenSyncId_ = this->GetNativeTokenId("token_sync_service"); + } + return tokenCaller == tokenSyncId_; } bool AccessTokenManagerStub::IsNativeProcessCalling() { AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - int32_t type = this->GetTokenType(tokenCaller); - ACCESSTOKEN_LOG_DEBUG(LABEL, "Calling tokenID: %{public}d, type: %{public}d", tokenCaller, type); - if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { - return false; - } - return true; + return this->GetTokenType(tokenCaller) == TOKEN_NATIVE; } AccessTokenManagerStub::AccessTokenManagerStub() diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp index 1dc737bcdab4cbb9add47486c565b6e782750add..828590b30f33ca5cee171fe07b18408e89af8d94 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp @@ -100,9 +100,11 @@ int AccessTokenRemoteTokenManager::GetDeviceAllRemoteTokenID(const std::string& return RET_FAILED; } - for (const auto& mapEntry : remoteDeviceMap_[deviceID].MappingTokenIDPairMap_) { - remoteIDs.emplace_back(mapEntry.first); - } + std::transform(remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.begin(), + remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.end(), + std::back_inserter(remoteIDs), [](const auto& mapEntry) { + return mapEntry.first; + }); return RET_SUCCESS; } diff --git a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp index 2ec3bc325ee5de3440444fb34e696cf0705282b3..c41e277cf82e85d6424723170361af208769a3b8 100644 --- a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp @@ -155,9 +155,7 @@ int NativeTokenInfoInner::RestoreNativeTokenInfo(AccessTokenID tokenId, const Ge SetNativeAcls(inGenericValues.GetString(FIELD_NATIVE_ACLS)); tokenInfoBasic_.tokenAttr = (uint32_t)inGenericValues.GetInt(FIELD_TOKEN_ATTR); - std::vector permDefRes = {}; - permPolicySet_ = PermissionPolicySet::RestorePermissionPolicy(tokenId, - permStateRes); + permPolicySet_ = PermissionPolicySet::RestorePermissionPolicy(tokenId, permStateRes); return RET_SUCCESS; } diff --git a/services/accesstokenmanager/test/BUILD.gn b/services/accesstokenmanager/test/BUILD.gn index 14a41d363b5a2bd5864f1c8a78d260684ba8a180..0db7414dce863811772204d4fce4bce4770de84d 100644 --- a/services/accesstokenmanager/test/BUILD.gn +++ b/services/accesstokenmanager/test/BUILD.gn @@ -39,6 +39,7 @@ ohos_unittest("libaccesstoken_manager_service_standard_test") { sources = [ "unittest/cpp/src/accesstoken_info_manager_test.cpp", "unittest/cpp/src/native_token_receptor_test.cpp", + "unittest/cpp/src/permission_grant_event_test.cpp", ] cflags_cc = [ "-DHILOG_ENABLE" ] @@ -49,6 +50,10 @@ ohos_unittest("libaccesstoken_manager_service_standard_test") { configs = [ "//base/security/access_token/config:coverage_flags" ] + if (token_sync_enable == true) { + cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] + } + deps = [ "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", "//base/security/access_token/services/accesstokenmanager/:accesstoken_manager_service", @@ -59,6 +64,7 @@ ohos_unittest("libaccesstoken_manager_service_standard_test") { external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", + "safwk:system_ability_fwk", ] } diff --git a/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp index fbe8f922a2c8c95e24469d510bb711e4753eb80e..61753f75169abf7568ebd5bd352973775277b3b6 100644 --- a/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp +++ b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp @@ -26,8 +26,10 @@ #undef private #endif #include "permission_manager.h" +#include "string_ex.h" using namespace testing::ext; +using namespace OHOS; using namespace OHOS::Security::AccessToken; namespace { @@ -174,10 +176,15 @@ void AccessTokenInfoManagerTest::TearDownTestCase() {} void AccessTokenInfoManagerTest::SetUp() -{} +{ + atManagerService_ = DelayedSingleton::GetInstance(); + EXPECT_NE(nullptr, atManagerService_); +} void AccessTokenInfoManagerTest::TearDown() -{} +{ + atManagerService_ = nullptr; +} HWTEST_F(AccessTokenInfoManagerTest, Init001, TestSize.Level1) { @@ -227,6 +234,93 @@ HWTEST_F(AccessTokenInfoManagerTest, CreateHapTokenInfo001, TestSize.Level1) ASSERT_EQ(nullptr, tokenInfo); } +/** + * @tc.name: IsTokenIdExist001 + * @tc.desc: Verify the IsTokenIdExist exist accesstokenid. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, IsTokenIdExist001, TestSize.Level1) +{ + AccessTokenID testId = 1; + ASSERT_EQ(AccessTokenInfoManager::GetInstance().IsTokenIdExist(testId), false); +} + +/** + * @tc.name: GetHapTokenInfo001 + * @tc.desc: Verify the GetHapTokenInfo abnormal and normal branch. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, GetHapTokenInfo001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int result; + HapTokenInfo hapInfo; + result = AccessTokenInfoManager::GetInstance().GetHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID, hapInfo); + ASSERT_EQ(result, RET_FAILED); + + result = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( + g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, result); + GTEST_LOG_(INFO) << "add a hap token"; + result = AccessTokenInfoManager::GetInstance().GetHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID, hapInfo); + ASSERT_EQ(result, RET_SUCCESS); + result = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, result); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: GetHapTokenInfo001 + * @tc.desc: Verify the GetHapTokenInfo abnormal and normal branch. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, GetHapPermissionPolicySet001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(permPolicySet, nullptr); + + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( + g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + permPolicySet = AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(permPolicySet != nullptr, true); + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: GetNativePermissionPolicySet001 + * @tc.desc: Verify the GetNativePermissionPolicySet abnormal branch tokenID is invalid. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, GetNativePermissionPolicySet001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetNativePermissionPolicySet(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(permPolicySet, nullptr); +} + +/** + * @tc.name: RemoveHapTokenInfo001 + * @tc.desc: Verify the RemoveHapTokenInfo abnormal branch tokenID type is not true. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, RemoveHapTokenInfo001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + ASSERT_EQ(AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID), RET_FAILED); +} + /** * @tc.name: CreateHapTokenInfo002 * @tc.desc: Verify the CreateHapTokenInfo add one hap token twice function. @@ -325,6 +419,157 @@ HWTEST_F(AccessTokenInfoManagerTest, UpdateHapToken001, TestSize.Level1) GTEST_LOG_(INFO) << "remove the token info"; } +/** + * @tc.name: UpdateHapToken002 + * @tc.desc: Verify the UpdateHapToken token function abnormal branch. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, UpdateHapToken002, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + HapPolicyParams policy = g_infoManagerTestPolicyPrams; + policy.apl = APL_SYSTEM_BASIC; + int ret = AccessTokenInfoManager::GetInstance().UpdateHapToken( + tokenIdEx.tokenIdExStruct.tokenID, std::string(""), DEFAULT_API_VERSION, policy); + ASSERT_EQ(RET_FAILED, ret); + + ret = AccessTokenInfoManager::GetInstance().UpdateHapToken( + tokenIdEx.tokenIdExStruct.tokenID, std::string("updateAppId"), DEFAULT_API_VERSION, policy); + ASSERT_EQ(RET_FAILED, ret); +} +#ifdef TOKEN_SYNC_ENABLE +/** + * @tc.name: GetHapTokenSync001 + * @tc.desc: Verify the GetHapTokenSync token function and abnormal branch. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, GetHapTokenSync001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int result; + result = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( + g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, result); + GTEST_LOG_(INFO) << "add a hap token"; + + HapTokenInfoForSync hapSync; + result = AccessTokenInfoManager::GetInstance().GetHapTokenSync(tokenIdEx.tokenIdExStruct.tokenID, hapSync); + ASSERT_EQ(result, RET_SUCCESS); + + result = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, result); + GTEST_LOG_(INFO) << "remove the token info"; + + result = AccessTokenInfoManager::GetInstance().GetHapTokenSync(tokenIdEx.tokenIdExStruct.tokenID, hapSync); + ASSERT_EQ(result, RET_FAILED); +} + +/** + * @tc.name: GetHapTokenInfoFromRemote001 + * @tc.desc: Verify the GetHapTokenInfoFromRemote token function . + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, GetHapTokenInfoFromRemote001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( + g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + HapTokenInfoForSync hapSync; + ret = AccessTokenInfoManager::GetInstance().GetHapTokenInfoFromRemote(tokenIdEx.tokenIdExStruct.tokenID, hapSync); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: RemoteHapTest001001 + * @tc.desc: Verify the RemoteHap token function . + * @tc.type: FUNC + * @tc.require: issueI5RJBB + */ +HWTEST_F(AccessTokenInfoManagerTest, RemoteHapTest001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int32_t ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( + g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + std::string deviceId = "device_1"; + std::string deviceId2 = "device_2"; + AccessTokenID mapID = + AccessTokenInfoManager::GetInstance().AllocLocalTokenID(deviceId, tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(mapID == 0, true); + HapTokenInfoForSync hapSync; + ret = AccessTokenInfoManager::GetInstance().GetHapTokenInfoFromRemote(tokenIdEx.tokenIdExStruct.tokenID, hapSync); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenInfoManager::GetInstance().SetRemoteHapTokenInfo(deviceId, hapSync); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenInfoManager::GetInstance().DeleteRemoteDeviceTokens(deviceId); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenInfoManager::GetInstance().DeleteRemoteDeviceTokens(deviceId2); + ASSERT_EQ(RET_FAILED, ret); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: DeleteRemoteToken001 + * @tc.desc: Verify the DeleteRemoteToken normal and abnormal branch . + * @tc.type: FUNC + * @tc.require: issueI5RJBB + */ +HWTEST_F(AccessTokenInfoManagerTest, DeleteRemoteToken001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int32_t ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( + g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + std::string deviceId = "device_1"; + std::string deviceId2 = "device_2"; + AccessTokenID mapId = + AccessTokenInfoManager::GetInstance().AllocLocalTokenID(deviceId, tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(mapId == 0, true); + HapTokenInfoForSync hapSync; + ret = AccessTokenInfoManager::GetInstance().GetHapTokenInfoFromRemote(tokenIdEx.tokenIdExStruct.tokenID, hapSync); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenInfoManager::GetInstance().SetRemoteHapTokenInfo(deviceId, hapSync); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenInfoManager::GetInstance().DeleteRemoteToken(deviceId, tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenInfoManager::GetInstance().DeleteRemoteToken(deviceId2, tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_FAILED, ret); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: GetUdidByNodeId001 + * @tc.desc: Verify the GetUdidByNodeId abnormal branch. + * @tc.type: FUNC + * @tc.require: issue5RJBB + */ +HWTEST_F(AccessTokenInfoManagerTest, GetUdidByNodeId001, TestSize.Level1) +{ + std::string nodeId = "test"; + std::string result = AccessTokenInfoManager::GetInstance().GetUdidByNodeId(nodeId); + ASSERT_EQ(result.empty(), true); +} +#endif #ifdef SUPPORT_SANDBOX_APP static void PrepareJsonData1() { @@ -703,4 +948,50 @@ HWTEST_F(AccessTokenInfoManagerTest, DlpPermissionConfig006, TestSize.Level1) ASSERT_EQ(RET_SUCCESS, ret); GTEST_LOG_(INFO) << "remove the token info"; } -#endif \ No newline at end of file +#endif + +/** + * @tc.name: Dump001 + * @tc.desc: Dump tokeninfo. + * @tc.type: FUNC + * @tc.require: issueI4V02P + */ +HWTEST_F(AccessTokenInfoManagerTest, Dump001, TestSize.Level1) +{ + int fd = -1; + std::vector args; + + // fd is 0 + ASSERT_NE(RET_SUCCESS, atManagerService_->Dump(fd, args)); + + fd = 1; // 1: std output + + // hidumper + ASSERT_EQ(RET_SUCCESS, atManagerService_->Dump(fd, args)); + + // hidumper -h + args.emplace_back(Str8ToStr16("-h")); + ASSERT_EQ(RET_SUCCESS, atManagerService_->Dump(fd, args)); + + args.clear(); + // hidumper -a + args.emplace_back(Str8ToStr16("-a")); + ASSERT_EQ(RET_SUCCESS, atManagerService_->Dump(fd, args)); + + args.clear(); + // hidumper -t + args.emplace_back(Str8ToStr16("-t")); + ASSERT_NE(RET_SUCCESS, atManagerService_->Dump(fd, args)); + + args.clear(); + // hidumper -t + args.emplace_back(Str8ToStr16("-t")); + args.emplace_back(Str8ToStr16("-1")); // illegal tokenId + ASSERT_NE(RET_SUCCESS, atManagerService_->Dump(fd, args)); + + args.clear(); + // hidumper -t + args.emplace_back(Str8ToStr16("-t")); + args.emplace_back(Str8ToStr16("123")); // invalid tokenId + ASSERT_EQ(RET_SUCCESS, atManagerService_->Dump(fd, args)); +} \ No newline at end of file diff --git a/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h index 03cbc7d1ca1a4d911f9b9e199085d3161cbf3e1c..9358b78c2c4564761a657aac08a8da428897ff99 100644 --- a/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h +++ b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h @@ -17,6 +17,7 @@ #define ACCESSTOKEN_INFO_MANAGER_TEST_H #include +#include "accesstoken_manager_service.h" namespace OHOS { namespace Security { @@ -30,6 +31,8 @@ public: void SetUp(); void TearDown(); + + std::shared_ptr atManagerService_; }; } // namespace AccessToken } // namespace Security diff --git a/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.cpp b/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.cpp index 3ff81802ec61b3a8adf4a5fec6045356698c11d2..17a680a82853afb998b7a26086957d1d80dd0111 100644 --- a/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.cpp +++ b/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.cpp @@ -311,6 +311,91 @@ HWTEST_F(NativeTokenReceptorTest, ProcessNativeTokenInfos001, TestSize.Level1) ASSERT_EQ(ret, RET_SUCCESS); } +/** + * @tc.name: CheckNativeDCap001 + * @tc.desc: Verify CheckNativeDCap normal and abnormal branch + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, CheckNativeDCap001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test CheckNativeDCap001!"); + + // test tokenInfo = nullptr + std::vector> tokenInfos; + tokenInfos.emplace_back(nullptr); + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + + // test process one + NativeTokenInfo info = {.apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test0", + .tokenID = 0x28100000, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"}}; + + std::vector permStateList = {}; + std::shared_ptr nativeToken = std::make_shared(info, permStateList); + tokenInfos.emplace_back(nativeToken); + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + NativeTokenInfo findInfo; + int ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(info.tokenID, findInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(findInfo.apl, info.apl); + ASSERT_EQ(findInfo.ver, info.ver); + ASSERT_EQ(findInfo.processName, info.processName); + ASSERT_EQ(findInfo.tokenID, info.tokenID); + ASSERT_EQ(findInfo.tokenAttr, info.tokenAttr); + ASSERT_EQ(findInfo.dcap, info.dcap); + + std::string dcap = "AT_CAP"; + ASSERT_EQ(AccessTokenInfoManager::GetInstance().CheckNativeDCap(findInfo.tokenID, dcap), RET_SUCCESS); + std::string ndcap = "AT"; + ASSERT_EQ(AccessTokenInfoManager::GetInstance().CheckNativeDCap(findInfo.tokenID, ndcap), RET_FAILED); + AccessTokenID testId = 1; + ASSERT_EQ(AccessTokenInfoManager::GetInstance().CheckNativeDCap(testId, dcap), RET_FAILED); + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(info.tokenID); + ASSERT_EQ(ret, RET_SUCCESS); +} + +#ifdef TOKEN_SYNC_ENABLE +/** + * @tc.name: GetAllNativeTokenInfo001 + * @tc.desc: Verify GetAllNativeTokenInfo normal and abnormal branch + * @tc.type: FUNC + * @tc.require: Issue I5RJBB + */ +HWTEST_F(NativeTokenReceptorTest, GetAllNativeTokenInfo001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetAllNativeTokenInfo001!"); + + // test nativetokenInfo = nullptr + std::vector nativeVec; + std::vector> tokenInfos; + AccessTokenInfoManager::GetInstance().GetAllNativeTokenInfo(nativeVec); + ASSERT_EQ(nativeVec.empty(), false); + + // test process one + NativeTokenInfo info = {.apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test0", + .tokenID = 0x28100000, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"}}; + + std::vector permStateList = {}; + std::shared_ptr nativeToken = std::make_shared(info, permStateList); + tokenInfos.emplace_back(nativeToken); + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + AccessTokenInfoManager::GetInstance().GetAllNativeTokenInfo(nativeVec); + ASSERT_EQ(!nativeVec.empty(), true); + AccessTokenID resultTokenId = AccessTokenInfoManager::GetInstance().GetNativeTokenId("native_token_test0"); + ASSERT_EQ(resultTokenId, info.tokenID); + + int32_t ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(info.tokenID); + ASSERT_EQ(ret, RET_SUCCESS); +} +#endif /** * @tc.name: ProcessNativeTokenInfos002 * @tc.desc: test add two native tokens. diff --git a/services/accesstokenmanager/test/unittest/cpp/src/permission_grant_event_test.cpp b/services/accesstokenmanager/test/unittest/cpp/src/permission_grant_event_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd8fa4482511b4fca40fb114b8208dbf300b7368 --- /dev/null +++ b/services/accesstokenmanager/test/unittest/cpp/src/permission_grant_event_test.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_grant_event_test.h" + +#define private public +#include "permission_grant_event.h" +#undef private + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionGrantEventTest"}; +} + +void PermissionGrantEventTest::SetUpTestCase() +{} + +void PermissionGrantEventTest::TearDownTestCase() +{} + +void PermissionGrantEventTest::SetUp() +{} + +void PermissionGrantEventTest::TearDown() +{} + +/** + * @tc.name: NotifyPermGrantStoreResult001 + * @tc.desc: test notify permssion grant event success + * @tc.type: FUNC + * @tc.require:issueI5OOPG + */ +HWTEST_F(PermissionGrantEventTest, NotifyPermGrantStoreResult001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "NotifyPermGrantStoreResult001!"); + AccessTokenID tokenID = 0x100000; + std::string permissionName = "testpremission"; + uint64_t time; + + PermissionGrantEvent eventHandler; + eventHandler.AddEvent(tokenID, permissionName, time); + + // larger than grant timestamp + eventHandler.NotifyPermGrantStoreResult(true, time + 1); + + ASSERT_EQ(eventHandler.permGrantEventList_.size(), 0); +} + +/** + * @tc.name: NotifyPermGrantStoreResult002 + * @tc.desc: test notify permssion grant event failed + * @tc.type: FUNC + * @tc.require:issueI5OOPG + */ +HWTEST_F(PermissionGrantEventTest, NotifyPermGrantStoreResult002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "NotifyPermGrantStoreResult002!"); + AccessTokenID tokenID = 0x100000; + std::string permissionName = "testpremission"; + uint64_t time; + + PermissionGrantEvent eventHandler; + eventHandler.AddEvent(tokenID, permissionName, time); + + // larger than grant timestamp + eventHandler.NotifyPermGrantStoreResult(false, time + 1); + + ASSERT_EQ(eventHandler.permGrantEventList_.size(), 0); +} + +/** + * @tc.name: NotifyPermGrantStoreResult003 + * @tc.desc: test notify permssion grant event success, but timestamp is less than add timestamp + * @tc.type: FUNC + * @tc.require:issueI5OOPG + */ +HWTEST_F(PermissionGrantEventTest, NotifyPermGrantStoreResult003, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "NotifyPermGrantStoreResult003!"); + AccessTokenID tokenID = 0x100000; + std::string permissionName = "testpremission"; + uint64_t time; + + PermissionGrantEvent eventHandler; + eventHandler.AddEvent(tokenID, permissionName, time); + + // less than grant timestamp + eventHandler.NotifyPermGrantStoreResult(true, time - 1); + + ASSERT_EQ(eventHandler.permGrantEventList_.size(), 1); +} diff --git a/services/accesstokenmanager/test/unittest/cpp/src/permission_grant_event_test.h b/services/accesstokenmanager/test/unittest/cpp/src/permission_grant_event_test.h new file mode 100644 index 0000000000000000000000000000000000000000..8b5b199e8dae1d577cb8bc15abca4e74ee5f8487 --- /dev/null +++ b/services/accesstokenmanager/test/unittest/cpp/src/permission_grant_event_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_GRANT_EVENT_TEST_H +#define PERMISSION_GRANT_EVENT_TEST_H + +#include +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionGrantEventTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_GRANT_EVENT_TEST_H \ No newline at end of file diff --git a/services/common/database/test/BUILD.gn b/services/common/database/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7125ad43a8d8ecfaa1c3d468e72c4e2a4fa7b9b2 --- /dev/null +++ b/services/common/database/test/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/test.gni") + +ohos_unittest("libdatabase_values_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//third_party/googletest/include", + "//base/security/access_token/services/common/database/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/database", + ] + + sources = [ "unittest/src/generic_values_test.cpp" ] + + configs = [ "//base/security/access_token/config:coverage_flags" ] + + deps = [ + "//base/security/access_token/services/accesstokenmanager:accesstoken_manager_service", + "//base/security/access_token/services/common/database:accesstoken_database_cxx", + "//third_party/sqlite:sqlite", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libdatabase_values_test" ] +} diff --git a/services/common/database/test/unittest/src/generic_values_test.cpp b/services/common/database/test/unittest/src/generic_values_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..777a23721649d833c3d1059bb68e61d2c2fb3822 --- /dev/null +++ b/services/common/database/test/unittest/src/generic_values_test.cpp @@ -0,0 +1,175 @@ +/* + * 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 "sqlite_storage.h" +#include "generic_values.h" +#include "variant_value.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr int32_t GET_INT64_TRUE_VALUE = -1; +static constexpr int32_t ROLLBACK_TRANSACTION_RESULT_ABNORMAL = -1; +static constexpr int32_t EXECUTESQL_RESULT_ABNORMAL = -1; +static const int32_t DEFAULT_VALUE = -1; +} // namespace +class DatabaseTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DatabaseTest::SetUpTestCase(void) +{} +void DatabaseTest::TearDownTestCase(void) +{} +void DatabaseTest::SetUp(void) +{} +void DatabaseTest::TearDown(void) +{} + +/** + * @tc.name: PutInt64001 + * @tc.desc: Verify the GenericValues put and get int64 value function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, PutInt64001, TestSize.Level1) +{ + GenericValues outGenericValues; + std::string key = "databasetest"; + int64_t data = 1; + outGenericValues.Put(key, data); + int64_t outdata = outGenericValues.GetInt64(key); + EXPECT_EQ(outdata, data); + outGenericValues.Remove(key); + outdata = outGenericValues.GetInt64(key); + EXPECT_EQ(GET_INT64_TRUE_VALUE, outdata); +} + +/** + * @tc.name: RollbackTransaction001 + * @tc.desc: RollbackTransaction001 Abnormal branch res != SQLITE_OK + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, RollbackTransaction001, TestSize.Level1) +{ + int32_t result = SqliteStorage::GetInstance().RollbackTransaction(); + EXPECT_EQ(result, ROLLBACK_TRANSACTION_RESULT_ABNORMAL); +} + +/** + * @tc.name: RollbackTransaction002 + * @tc.desc: RollbackTransaction002 Abnormal branch db_ = nullptr + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, RollbackTransaction002, TestSize.Level1) +{ + SqliteStorage::GetInstance().Close(); + EXPECT_EQ(SqliteStorage::GetInstance().RollbackTransaction(), ROLLBACK_TRANSACTION_RESULT_ABNORMAL); +} + +/** + * @tc.name: ExecuteSql001 + * @tc.desc: ExecuteSql001 Abnormal branch res != SQLITE_OK + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, ExecuteSql001, TestSize.Level1) +{ + std::string testSql = "test"; + EXPECT_EQ(SqliteStorage::GetInstance().ExecuteSql(testSql), EXECUTESQL_RESULT_ABNORMAL); +} + +/** + * @tc.name: ExecuteSql002 + * @tc.desc: ExecuteSql002 Abnormal branch db_ = nullptr + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, ExecuteSql002, TestSize.Level1) +{ + std::string testSql = "test"; + SqliteStorage::GetInstance().Close(); + EXPECT_EQ(SqliteStorage::GetInstance().ExecuteSql(testSql), EXECUTESQL_RESULT_ABNORMAL); +} + +/** + * @tc.name: SpitError001 + * @tc.desc: SpitError001 Abnormal branch db_ = nullptr + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, SpitError001, TestSize.Level1) +{ + SqliteStorage::GetInstance().Close(); + std::string result = SqliteStorage::GetInstance().SpitError().c_str(); + EXPECT_EQ(result.empty(), true); +} + +/** + * @tc.name: SpitError002 + * @tc.desc: SpitError002 use SpitError + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, SpitError002, TestSize.Level1) +{ + SqliteStorage::GetInstance().Open(); + std::string result = SqliteStorage::GetInstance().SpitError().c_str(); + EXPECT_EQ(result.length() > 0, true); +} + +/** + * @tc.name: VariantValue64001 + * @tc.desc: VariantValue64001 use VariantValue + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, VariantValue64001, TestSize.Level1) +{ + int64_t testValue = 1; + VariantValue Test(testValue); + EXPECT_EQ(Test.GetInt64(), testValue); +} + +/** + * @tc.name: VariantValue64002 + * @tc.desc: VariantValue64002 getint and getint64 Abnormal branch + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DatabaseTest, VariantValue64002, TestSize.Level1) +{ + int32_t ntestValue = 1; + VariantValue Ntest(ntestValue); + EXPECT_EQ(DEFAULT_VALUE, Ntest.GetInt64()); + int64_t testValue = 1; + VariantValue Test(testValue); + EXPECT_EQ(DEFAULT_VALUE, Test.GetInt()); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/privacymanager/BUILD.gn b/services/privacymanager/BUILD.gn index 86ffd4d0a45ea77b6837eb8f1dc30feb49653802..4f5321129ba37fa0653758e427019d5145762c17 100644 --- a/services/privacymanager/BUILD.gn +++ b/services/privacymanager/BUILD.gn @@ -47,6 +47,8 @@ if (is_standard_system && ability_base_enable == true) { "//base/security/access_token/interfaces/innerkits/accesstoken/include", "//base/security/access_token/interfaces/innerkits/privacy/include", "//base/security/access_token/services/common/database/include", + "//foundation/multimedia/audio_framework/interfaces/inner_api/native/audiomanager/include", + "//foundation/ability/ability_runtime/interfaces/kits/native/ability/ability_runtime", "//third_party/json/include", "//third_party/sqlite/include/", ] @@ -79,16 +81,22 @@ if (is_standard_system && ability_base_enable == true) { "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "//base/security/access_token/services/common/database:accesstoken_database_cxx", "//base/security/access_token/services/privacymanager:privacy.rc", + "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager:ability_manager", + "//third_party/libuv:uv", ] external_deps = [ + "ability_base:want", + "ability_runtime:ability_manager", "ability_runtime:app_manager", "c_utils:utils", "hisysevent_native:libhisysevent", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_audio_framework:audio_client", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "window_manager:libwm", ] } } diff --git a/services/privacymanager/include/sensitive/sensitive_resource_manager.h b/services/privacymanager/include/sensitive/sensitive_resource_manager.h index 80f91eb57ec6caf95169690173b7eb38a717e42a..6dc2c8d5a7b181034f118da850c3fbe5c745b8f8 100644 --- a/services/privacymanager/include/sensitive/sensitive_resource_manager.h +++ b/services/privacymanager/include/sensitive/sensitive_resource_manager.h @@ -21,6 +21,7 @@ #include #include "app_mgr_proxy.h" #include "application_status_change_callback.h" +#include "safe_map.h" namespace OHOS { namespace Security { @@ -31,6 +32,11 @@ enum AppStatus { APP_FOREGROUND, APP_BACKGROUND, }; +enum ResourceType { + INVALID = -1, + CAMERA = 0, + MICROPHONE = 1, +}; using DialogCallback = std::function; class SensitiveResourceManager final { @@ -38,8 +44,11 @@ public: static SensitiveResourceManager& GetInstance(); SensitiveResourceManager(); virtual ~SensitiveResourceManager(); + void Init(); bool GetAppStatus(const std::string& pkgName, int32_t& status); + bool GetGlobalSwitch(const ResourceType type); + void SetGlobalSwitch(const ResourceType type, bool switchStatus); // register and unregister app status change callback bool RegisterAppStatusChangeCallback(uint32_t tokenId, OnAppStatusChangeCallback callback); @@ -52,6 +61,7 @@ private: private: std::mutex appStatusMutex_; std::vector> appStateCallbacks_; + SafeMap switchStatusMap_; std::mutex mutex_; sptr appMgrProxy_; }; diff --git a/services/privacymanager/include/service/privacy_manager_service.h b/services/privacymanager/include/service/privacy_manager_service.h index 8461b8e0e09ef8bb91854ca23958811baf3930fd..6eebcff0e2fc8d7a0bb5404c7e5b33cc181079f3 100644 --- a/services/privacymanager/include/service/privacy_manager_service.h +++ b/services/privacymanager/include/service/privacy_manager_service.h @@ -49,10 +49,10 @@ public: std::vector& permList, const sptr& callback) override; int32_t UnRegisterPermActiveStatusCallback(const sptr& callback) override; bool IsAllowedUsingPermission(AccessTokenID tokenId, const std::string& permissionName) override; - int32_t Dump(int fd, const std::vector& args) override; - int32_t ResponseDumpCommand(int fd, const std::vector& args); + int32_t Dump(int32_t fd, const std::vector& args) override; private: bool Initialize() const; + int32_t ResponseDumpCommand(int32_t fd, const std::vector& args); ServiceRunningState state_; }; diff --git a/services/privacymanager/src/active/active_status_callback_manager.cpp b/services/privacymanager/src/active/active_status_callback_manager.cpp index 39bea09f66d7b9c6aac9767c23e6a3d1ebd9828b..6dc2f0daff2beff2c539ad1ab6b1566801aab5cf 100644 --- a/services/privacymanager/src/active/active_status_callback_manager.cpp +++ b/services/privacymanager/src/active/active_status_callback_manager.cpp @@ -104,12 +104,8 @@ bool ActiveStatusCallbackManager::NeedCalled(const std::vector& per if (permList.empty()) { return true; } - for (const auto& perm : permList) { - if (perm == permName) { - return true; - } - } - return false; + return std::any_of(permList.begin(), permList.end(), + [permName](const std::string& perm) { return perm == permName; }); } void ActiveStatusCallbackManager::ExecuteCallbackAsync( diff --git a/services/privacymanager/src/record/permission_record_manager.cpp b/services/privacymanager/src/record/permission_record_manager.cpp index b032f301af655cf3aad14373725805e0c59e0b01..67aa001f268f25cac71c99555d547c4f75f069c5 100644 --- a/services/privacymanager/src/record/permission_record_manager.cpp +++ b/services/privacymanager/src/record/permission_record_manager.cpp @@ -15,6 +15,7 @@ #include "permission_record_manager.h" +#include #include #include @@ -326,14 +327,14 @@ int32_t PermissionRecordManager::DeletePermissionRecord(int32_t days) bool PermissionRecordManager::HasStarted(const PermissionRecord& record) { Utils::UniqueWriteGuard lk(this->startRecordListRWLock_); - for (const auto& rec : startRecordList_) { - if ((rec.opCode == record.opCode) && (rec.tokenId == record.tokenId)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId(%{public}d), opCode(%{public}d) has been started.", - record.tokenId, record.opCode); - return true; - } + bool hasStarted = std::any_of(startRecordList_.begin(), startRecordList_.end(), + [record](const auto& rec) { return (rec.opCode == record.opCode) && (rec.tokenId == record.tokenId); }); + if (hasStarted) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId(%{public}d), opCode(%{public}d) has been started.", + record.tokenId, record.opCode); } - return false; + + return hasStarted; } void PermissionRecordManager::FindRecordsToUpdateAndExecuted( @@ -489,7 +490,6 @@ int32_t PermissionRecordManager::StopUsingPermission(AccessTokenID tokenId, cons CallbackExecute(tokenId, permissionName, PERM_INACTIVE); } - // when StopUsingPermission and there is no permission with tokenId in cache, need to UnRegisterAppStatusChangeCallback if (!IsTokenIdExist(tokenId) && !SensitiveResourceManager::GetInstance().UnRegisterAppStatusChangeCallback( tokenId, AppStatusListener)) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}d unregiste app status change callback failed.", tokenId); @@ -504,10 +504,11 @@ void PermissionRecordManager::PermListToString(const std::vector& p std::string permStr; permStr = accumulate(permList.begin(), permList.end(), std::string(" ")); - ACCESSTOKEN_LOG_INFO(LABEL, "permStr =%{public}s",permStr.c_str()); + ACCESSTOKEN_LOG_INFO(LABEL, "permStr =%{public}s", permStr.c_str()); } -int32_t PermissionRecordManager::PermissionListFilter(const std::vector& listSrc, std::vector& listRes) +int32_t PermissionRecordManager::PermissionListFilter( + const std::vector& listSrc, std::vector& listRes) { PermissionDef permissionDef; std::set permSet; diff --git a/services/privacymanager/src/record/permission_used_record_cache.cpp b/services/privacymanager/src/record/permission_used_record_cache.cpp index 0908327e9de07bb7670586265010520001836c7e..c3cd74e29ee5812892b5853b7e4ce843fa7c3bba 100644 --- a/services/privacymanager/src/record/permission_used_record_cache.cpp +++ b/services/privacymanager/src/record/permission_used_record_cache.cpp @@ -175,8 +175,9 @@ int32_t PermissionUsedRecordCache::RemoveRecords(const AccessTokenID tokenId) std::shared_ptr curFindDeletePos; std::shared_ptr persistPendingBufferHead; std::shared_ptr persistPendingBufferEnd = nullptr; - int32_t countPersistPendingNode = 0; + { + int32_t countPersistPendingNode = 0; Utils::UniqueWriteGuard lock1(this->cacheLock1_); curFindDeletePos = recordBufferHead_->next; persistPendingBufferHead = recordBufferHead_; diff --git a/services/privacymanager/src/sensitive/sensitive_resource_manager.cpp b/services/privacymanager/src/sensitive/sensitive_resource_manager.cpp index b53b061ab72628d779ca72517dfccaa3bfdbb233..46aea1b19e89b383d530198392cec4ab563da245 100644 --- a/services/privacymanager/src/sensitive/sensitive_resource_manager.cpp +++ b/services/privacymanager/src/sensitive/sensitive_resource_manager.cpp @@ -15,10 +15,13 @@ #include "sensitive_resource_manager.h" #include +#include "ability_manager_client.h" #include "accesstoken_log.h" #include "active_change_response_info.h" #include "iservice_registry.h" #include "system_ability_definition.h" +#include "window_manager.h" +#include "audio_system_manager.h" namespace OHOS { namespace Security { @@ -44,6 +47,12 @@ SensitiveResourceManager::~SensitiveResourceManager() { } +void SensitiveResourceManager::Init() +{ + switchStatusMap_[ResourceType::CAMERA] = true; + switchStatusMap_[ResourceType::MICROPHONE] = AudioStandard::AudioSystemManager::GetInstance()->IsMicrophoneMute(); +} + bool SensitiveResourceManager::InitProxy() { std::lock_guard lock(mutex_); @@ -93,17 +102,34 @@ bool SensitiveResourceManager::GetAppStatus(const std::string& pkgName, int32_t& std::vector foreGroundAppList; appMgrProxy->GetForegroundApplications(foreGroundAppList); - for (const auto& foreGroundApp : foreGroundAppList) { - if (foreGroundApp.bundleName == pkgName) { + status = PERM_ACTIVE_IN_BACKGROUND; + if (std::any_of(foreGroundAppList.begin(), foreGroundAppList.end(), + [pkgName](const auto& foreGroundApp) { return foreGroundApp.bundleName == pkgName; })) { status = PERM_ACTIVE_IN_FOREGROUND; - return true; - } } - - status = PERM_ACTIVE_IN_BACKGROUND; return true; } +bool SensitiveResourceManager::GetGlobalSwitch(const ResourceType type) +{ + bool status = true; + if (!switchStatusMap_.Find(type, status)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Invalid ResourceType."); + return true; + } + return status; +} + +void SensitiveResourceManager::SetGlobalSwitch(const ResourceType type, bool switchStatus) +{ + bool status = true; + if (!switchStatusMap_.Find(type, status)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Invalid ResourceType."); + return; + } + switchStatusMap_[type] = switchStatus; +} + bool SensitiveResourceManager::RegisterAppStatusChangeCallback(uint32_t tokenId, OnAppStatusChangeCallback callback) { if (callback == nullptr) { diff --git a/services/privacymanager/src/service/privacy_manager_service.cpp b/services/privacymanager/src/service/privacy_manager_service.cpp index fedbf036e449f6f31e71b64608ac8927bd405556..1ff35ddc00cdd1d70018b5548748b463e8b9332f 100644 --- a/services/privacymanager/src/service/privacy_manager_service.cpp +++ b/services/privacymanager/src/service/privacy_manager_service.cpp @@ -30,7 +30,7 @@ namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PrivacyManagerService" }; -constexpr int PERMISSION_USAGE_RECORDS_MAXNUM = 100; +constexpr int PERMISSION_USAGE_RECORDS_MAX_NUM = 100; } const bool REGISTER_RESULT = @@ -116,38 +116,36 @@ int32_t PrivacyManagerService::RegisterPermActiveStatusCallback( return PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback(permList, callback); } -int32_t PrivacyManagerService::ResponseDumpCommand(int fd, const std::vector& args) +int32_t PrivacyManagerService::ResponseDumpCommand(int32_t fd, const std::vector& args) { - if (args.size() < 2) { // 2 :need two args 0:command 1:tokenID + if (args.size() < 2) { // 2 :need two args 0:command 1:tokenId return ERR_INVALID_VALUE; } - long long tokenID = atoll(static_cast(Str16ToStr8(args.at(1)).c_str())); + long long tokenId = atoll(static_cast(Str16ToStr8(args.at(1)).c_str())); PermissionUsedRequest request; - if (tokenID <= 0) { + if (tokenId <= 0) { return ERR_INVALID_VALUE; } - request.tokenId = static_cast(tokenID); + request.tokenId = static_cast(tokenId); request.flag = FLAG_PERMISSION_USAGE_SUMMARY; PermissionUsedResult result; if (PermissionRecordManager::GetInstance().GetPermissionUsedRecords(request, result) != 0) { return ERR_INVALID_VALUE; } std::string infos; - int RecordsNum = 0; - for (int index = result.bundleRecords[0].permissionRecords.size() - 1; index >= 0; index--) { - if (RecordsNum > PERMISSION_USAGE_RECORDS_MAXNUM) { + if (result.bundleRecords.empty() || result.bundleRecords[0].permissionRecords.empty()) { + dprintf(fd, "No Record \n"); + return ERR_OK; + } + int32_t RecordsNum = 0; + for (int32_t index = result.bundleRecords[0].permissionRecords.size() - 1; index >= 0; index--) { + if (RecordsNum > PERMISSION_USAGE_RECORDS_MAX_NUM) { break; } infos.append(R"( "permissionRecord": [)"); infos.append("\n"); infos.append(R"( "bundleName": )" + result.bundleRecords[0].bundleName + ",\n"); - if (result.bundleRecords[0].isRemote) { - std::string status = "true"; - infos.append(R"( "isRemote": )" + status + ",\n"); - } else { - std::string status = "false"; - infos.append(R"( "isRemote": )" + status + ",\n"); - } + infos.append(R"( "isRemote": )" + std::to_string(result.bundleRecords[0].isRemote) + ",\n"); infos.append(R"( "permissionName": ")" + result.bundleRecords[0].permissionRecords[index].permissionName + R"(")" + ",\n"); time_t lastAccessTime = static_cast(result.bundleRecords[0].permissionRecords[index].lastAccessTime); @@ -165,24 +163,27 @@ int32_t PrivacyManagerService::ResponseDumpCommand(int fd, const std::vector& args) +int32_t PrivacyManagerService::Dump(int32_t fd, const std::vector& args) { if (fd < 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "Dump fd invalid value"); return ERR_INVALID_VALUE; } - int ReturnValue = ERR_OK; + int32_t ret = ERR_OK; dprintf(fd, "Privacy Dump:\n"); - dprintf(fd, "please use hidumper -s said -a '-h' command help\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, " -t : according to specific token id dump permission used records\n"); } else if (arg0.compare("-t") == 0) { - ReturnValue = PrivacyManagerService::ResponseDumpCommand(fd, args); + ret = PrivacyManagerService::ResponseDumpCommand(fd, args); } - return ReturnValue; + + if (ret != ERR_OK) { + dprintf(fd, "please use hidumper -s said -a '-h' command help\n"); + } + return ret; } int32_t PrivacyManagerService::UnRegisterPermActiveStatusCallback(const sptr& callback) diff --git a/services/privacymanager/test/unittest/BUILD.gn b/services/privacymanager/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d7178178abb7c3bd4cc35da2f0e91c75e646955c --- /dev/null +++ b/services/privacymanager/test/unittest/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("//base/security/access_token/access_token.gni") +import("//build/test.gni") + +if (is_standard_system && ability_base_enable == true) { + ohos_unittest("libprivacy_manager_service_standard_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/frameworks/privacy/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + "//base/security/access_token/services/privacymanager/include/service", + "//third_party/googletest/include", + "//commonlibrary/c_utils/base/include", + ] + + sources = [ "privacy_manager_service_test.cpp" ] + + configs = [ "//base/security/access_token/config:coverage_flags" ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/services/privacymanager:privacy_manager_service", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "safwk:system_ability_fwk", + ] + } +} + +group("unittest") { + testonly = true + deps = [ ":libprivacy_manager_service_standard_test" ] +} diff --git a/services/privacymanager/test/unittest/privacy_manager_service_test.cpp b/services/privacymanager/test/unittest/privacy_manager_service_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..885562c1c623469b7fd2dcceb51918d410e80cae --- /dev/null +++ b/services/privacymanager/test/unittest/privacy_manager_service_test.cpp @@ -0,0 +1,142 @@ +/* + * 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 "privacy_manager_service_test.h" +#include "accesstoken_kit.h" +#include "string_ex.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::AccessToken; + +namespace { +constexpr int32_t PERMISSION_USAGE_RECORDS_MAX_NUM = 10; +static PermissionStateFull g_testState = { + .permissionName = "ohos.permission.CAMERA", + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; + +static HapPolicyParams g_PolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain.A", + .permList = {}, + .permStateList = {g_testState} +}; + +static HapInfoParams g_InfoParms = { + .userID = 1, + .bundleName = "ohos.privacy_test.bundleA", + .instIndex = 0, + .appIDDesc = "privacy_test.bundleA" +}; + +} +void PrivacyManagerServiceTest::SetUpTestCase() +{ +} + +void PrivacyManagerServiceTest::TearDownTestCase() +{ +} + +void PrivacyManagerServiceTest::SetUp() +{ + privacyManagerService_ = DelayedSingleton::GetInstance(); + EXPECT_NE(nullptr, privacyManagerService_); + AccessTokenKit::AllocHapToken(g_InfoParms, g_PolicyPrams); +} + +void PrivacyManagerServiceTest::TearDown() +{ + privacyManagerService_ = nullptr; + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms.userID, + g_InfoParms.bundleName, + g_InfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenId); +} + +/** + * @tc.name: Dump001 + * @tc.desc: Dump record info. + * @tc.type: FUNC + * @tc.require: issueI4V02P + */ +HWTEST_F(PrivacyManagerServiceTest, Dump001, TestSize.Level1) +{ + int32_t fd = -1; + std::vector args; + + // fd is 0 + ASSERT_NE(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); + + fd = 1; // 1: std output + + // hidumper + ASSERT_EQ(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); + + // hidumper -h + args.emplace_back(Str8ToStr16("-h")); + ASSERT_EQ(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); + + args.clear(); + // hidumper -t + args.emplace_back(Str8ToStr16("-t")); + ASSERT_NE(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); + + args.clear(); + // hidumper -t + args.emplace_back(Str8ToStr16("-t")); + args.emplace_back(Str8ToStr16("-1")); // illegal tokenId // illegal tokenId + ASSERT_NE(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); + + args.clear(); + // hidumper -t + args.emplace_back(Str8ToStr16("-t")); + args.emplace_back(Str8ToStr16("123")); // 123: invalid tokenId + ASSERT_EQ(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); +} + +/** + * @tc.name: Dump002 + * @tc.desc: Dump record info. + * @tc.type: FUNC + * @tc.require: issueI4V02P + */ +HWTEST_F(PrivacyManagerServiceTest, Dump002, TestSize.Level1) +{ + int32_t fd = 1; // 1: std output + std::vector args; + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms.userID, + g_InfoParms.bundleName, + g_InfoParms.instIndex); + args.emplace_back(Str8ToStr16("-t")); + std::string tokenIdStr = std::to_string(tokenId); + args.emplace_back(Str8ToStr16(tokenIdStr)); + + ASSERT_EQ(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); + + std::string permission = "ohos.permission.CAMERA"; + for (int32_t i = 0; i < PERMISSION_USAGE_RECORDS_MAX_NUM; i++) { + privacyManagerService_->AddPermissionUsedRecord(tokenId, permission, 1, 0); + } + + ASSERT_EQ(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); + + privacyManagerService_->AddPermissionUsedRecord(tokenId, permission, 1, 0); + ASSERT_EQ(RET_SUCCESS, privacyManagerService_->Dump(fd, args)); +} diff --git a/services/privacymanager/test/unittest/privacy_manager_service_test.h b/services/privacymanager/test/unittest/privacy_manager_service_test.h new file mode 100644 index 0000000000000000000000000000000000000000..6f8c016413d5399ff8eb7897621853d02bb78c31 --- /dev/null +++ b/services/privacymanager/test/unittest/privacy_manager_service_test.h @@ -0,0 +1,39 @@ +/* + * 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 PRIVACY_MANAGER_SERVICE_TEST_H +#define PRIVACY_MANAGER_SERVICE_TEST_H + +#include +#include "privacy_manager_service.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PrivacyManagerServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + std::shared_ptr privacyManagerService_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PRIVACY_MANAGER_SERVICE_TEST_H diff --git a/services/tokensyncmanager/include/service/token_sync_manager_stub.h b/services/tokensyncmanager/include/service/token_sync_manager_stub.h index f16fd8dd75dab71eb574b3e398940996b1364e5f..ed587de81780c9fcac8a82beb0c8c92747c9bd6f 100644 --- a/services/tokensyncmanager/include/service/token_sync_manager_stub.h +++ b/services/tokensyncmanager/include/service/token_sync_manager_stub.h @@ -34,6 +34,9 @@ private: void GetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); void DeleteRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); void UpdateRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + + bool IsNativeProcessCalling() const; + bool IsRootCalling() const; }; } // namespace AccessToken } // namespace Security diff --git a/services/tokensyncmanager/src/device/device_info_repository.cpp b/services/tokensyncmanager/src/device/device_info_repository.cpp index e3c652cf4f49f3b52e35694298d4111aab71689b..678d92d91637a1d8edf3f36a7a2a6701b3bdc804 100644 --- a/services/tokensyncmanager/src/device/device_info_repository.cpp +++ b/services/tokensyncmanager/src/device/device_info_repository.cpp @@ -35,7 +35,7 @@ std::vector DeviceInfoRepository::ListDeviceInfo() itEnd = deviceInfoMap_.end(); while (it != itEnd) { deviceInfo.push_back(it->second); - it++; + ++it; } return deviceInfo; } diff --git a/services/tokensyncmanager/src/remote/remote_command_executor.cpp b/services/tokensyncmanager/src/remote/remote_command_executor.cpp index 7aa6658043cdd9887a2dcbb2d968f5b7120a9a63..f0d090a73ba33067e8231e4b0397e739105ced9a 100644 --- a/services/tokensyncmanager/src/remote/remote_command_executor.cpp +++ b/services/tokensyncmanager/src/remote/remote_command_executor.cpp @@ -117,14 +117,13 @@ int RemoteCommandExecutor::AddCommand(const std::shared_ptr& std::unique_lock lock(mutex_); // make sure do not have the same command in the command buffer - for (const auto& bufferedCommand : commands_) { - if (bufferedCommand->remoteProtocol_.uniqueId == uniqueId) { + if (std::any_of(commands_.begin(), commands_.end(), + [uniqueId](const auto& buffCommand) {return buffCommand->remoteProtocol_.uniqueId == uniqueId; })) { ACCESSTOKEN_LOG_WARN(LABEL, "targetNodeId %{public}s, add uniqueId %{public}s, already exist in the buffer, skip", targetNodeId_.c_str(), uniqueId.c_str()); return Constant::SUCCESS; - } } commands_.push_back(ptrCommand); diff --git a/services/tokensyncmanager/src/remote/remote_command_manager.cpp b/services/tokensyncmanager/src/remote/remote_command_manager.cpp index c9d41f27f3707ec4d9bbe2541bab3015838bdfa0..447448bde9029d6de810a741dc34ccda7e9793f7 100644 --- a/services/tokensyncmanager/src/remote/remote_command_manager.cpp +++ b/services/tokensyncmanager/src/remote/remote_command_manager.cpp @@ -56,7 +56,6 @@ int RemoteCommandManager::AddCommand(const std::string &udid, const std::shared_ ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid, or null command"); return Constant::FAILURE; } - std::string uniqueId = command->remoteProtocol_.uniqueId; ACCESSTOKEN_LOG_INFO(LABEL, "add uniqueId"); std::shared_ptr executor = GetOrCreateRemoteCommandExecutor(udid); diff --git a/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp b/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp index 85ca0d399374195c7c6281a960d0a9e91a7f9001..fa1d7230e0741d308edf437df1616f57998d9d21 100644 --- a/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp +++ b/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp @@ -26,6 +26,7 @@ namespace Security { namespace AccessToken { namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerStub"}; +static const int32_t ROOT_UID = 0; } int32_t TokenSyncManagerStub::OnRemoteRequest( @@ -53,15 +54,29 @@ int32_t TokenSyncManagerStub::OnRemoteRequest( return NO_ERROR; } -void TokenSyncManagerStub::GetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +bool TokenSyncManagerStub::IsNativeProcessCalling() const { AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); int type = (reinterpret_cast(&tokenCaller))->type; - if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "Calling type: %{public}d", type); + return type == TOKEN_NATIVE; +} + +bool TokenSyncManagerStub::IsRootCalling() const +{ + int callingUid = IPCSkeleton::GetCallingUid(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "Calling uid: %{public}d", callingUid); + return callingUid == ROOT_UID; +} + +void TokenSyncManagerStub::GetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsRootCalling() && !IsNativeProcessCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; } + std::string deviceID = data.ReadString(); AccessTokenID tokenID = data.ReadUint32(); @@ -72,14 +87,11 @@ void TokenSyncManagerStub::GetRemoteHapTokenInfoInner(MessageParcel& data, Messa void TokenSyncManagerStub::DeleteRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - int type = (reinterpret_cast(&tokenCaller))->type; - if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { + if (!IsRootCalling() && !IsNativeProcessCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; } - std::string deviceID = data.ReadString(); AccessTokenID tokenID = data.ReadUint32(); int result = this->DeleteRemoteHapTokenInfo(tokenID); reply.WriteInt32(result); @@ -87,13 +99,12 @@ void TokenSyncManagerStub::DeleteRemoteHapTokenInfoInner(MessageParcel& data, Me void TokenSyncManagerStub::UpdateRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - int type = (reinterpret_cast(&tokenCaller))->type; - if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { + if (!IsRootCalling() && !IsNativeProcessCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; } + sptr tokenInfoParcelPtr = data.ReadParcelable(); int result = RET_FAILED; if (tokenInfoParcelPtr != nullptr) { diff --git a/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp b/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp index 94647249557ac360bb7caea0e1a59cc775039ebd..6ac2e75a8cbadda71a964921b71fc2fd1b69d684 100644 --- a/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp +++ b/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp @@ -52,13 +52,13 @@ int32_t GetNodeKeyInfo(const char *pkgName, const char *networkId, NodeDeviceInf if (key == NodeDeviceInfoKey::NODE_KEY_UDID) { std::string temp = networkId; temp += ":udid-001"; - strncpy_s((char *) info, infoLen, temp.c_str(), temp.length()); + strncpy_s(reinterpret_cast(info), infoLen, temp.c_str(), temp.length()); infoLen = temp.length(); } if (key == NodeDeviceInfoKey::NODE_KEY_UUID) { std::string temp = networkId; temp += ":uuid-001"; - strncpy_s((char *) info, infoLen, temp.c_str(), temp.length()); + strncpy_s(reinterpret_cast(info), infoLen, temp.c_str(), temp.length()); } ACCESSTOKEN_LOG_DEBUG(LABEL, "success, count: %{public}d, id: %{public}s", regCount_, info); return Constant::SUCCESS; diff --git a/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp b/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp index 6cb349e4d20511c78b870693b0c13eafc6cf6602..7826a7fc0f612066ff7de573214500178030bf62 100644 --- a/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp +++ b/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp @@ -104,7 +104,7 @@ int SendBytes(int sessionId, const void *data, unsigned int len) if (sessionId == Constant::INVALID_SESSION) { return Constant::FAILURE; } - DecompressMock((unsigned char *) data, len); + DecompressMock(reinterpret_cast(data), len); g_sendMessFlag = true; return Constant::SUCCESS; } diff --git a/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn b/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn index 9252861a63927f9713e3c454cf970d59e5631982..0fae85acec039b32225e2c48d5dfddfdbcc59cc3 100644 --- a/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn +++ b/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn @@ -67,12 +67,14 @@ ohos_unittest("libtoken_sync_service_sdk_test") { "//foundation/communication/dsoftbus/interfaces/kits/common", "//foundation/communication/dsoftbus/interfaces/kits/bus_center", "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include", + "//base/security/access_token/interfaces/innerkits/token_setproc/include", ] deps = [ "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", "//base/security/access_token/frameworks/common:accesstoken_common_cxx", "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp:devicemanagersdk", "//third_party/zlib:libz", ] diff --git a/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp b/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp index 3517a2721d6ae47e051803ce0f480aa41f2233f7..79d4b33a27cf019136a40aead714ee80f856c822 100644 --- a/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp +++ b/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp @@ -32,6 +32,7 @@ #include "device_info.h" #include "soft_bus_device_connection_listener.h" #include "soft_bus_session_listener.h" +#include "token_setproc.h" #include "device_info_manager.h" #define private public @@ -63,8 +64,19 @@ TokenSyncServiceTest::TokenSyncServiceTest() } TokenSyncServiceTest::~TokenSyncServiceTest() {} + +void NativeTokenGet() +{ + uint64_t tokenId; + tokenId = AccessTokenKit::GetNativeTokenId("token_sync_service"); + ASSERT_NE(tokenId, 0); + SetSelfTokenID(tokenId); +} + void TokenSyncServiceTest::SetUpTestCase() -{} +{ + NativeTokenGet(); +} void TokenSyncServiceTest::TearDownTestCase() {} void TokenSyncServiceTest::SetUp() @@ -228,7 +240,7 @@ HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo002, TestSize.Level1) int count = 0; while (!GetSendMessFlagMock() && count < 10) { sleep(1); - count ++; + count++; } free(recvBuffer); @@ -645,7 +657,7 @@ HWTEST_F(TokenSyncServiceTest, SyncNativeTokens005, TestSize.Level1) int count = 0; while (!GetSendMessFlagMock() && count < 10) { sleep(1); - count ++; + count++; } free(recvBuffer); diff --git a/test/fuzztest/access_token/BUILD.gn b/test/fuzztest/access_token/BUILD.gn index e37d93e7fd00f66c53dffb8f732c8a25e0625d94..69dee3310fe31a1f5c212738a3bae3d5f595e3a8 100644 --- a/test/fuzztest/access_token/BUILD.gn +++ b/test/fuzztest/access_token/BUILD.gn @@ -25,7 +25,13 @@ group("fuzztest") { "deleteremotetoken_fuzzer:DeleteRemoteTokenFuzzTest", "deletetoken_fuzzer:DeleteTokenFuzzTest", "getdefpermission_fuzzer:GetDefPermissionFuzzTest", + "getdefpermissions_fuzzer:GetDefPermissionsFuzzTest", + "gethaptokenid_fuzzer:GetHapTokenIDFuzzTest", + "gethaptokeninfo_fuzzer:GetHapTokenInfoFuzzTest", + "getnativetokeninfo_fuzzer:GetNativeTokenInfoFuzzTest", "getpermissionflags_fuzzer:GetPermissionFlagsFuzzTest", + "gettokentype_fuzzer:GetTokenTypeFuzzTest", + "gettokentypeflag_fuzzer:GetTokenTypeFlagFuzzTest", "grantpermission_fuzzer:GrantPermissionFuzzTest", "revokeusergrantedpermission_fuzzer:RevokeUserGrantedPermissionFuzzTest", "setremotehaptokeninfo_fuzzer:SetRemoteHapTokenInfoFuzzTest", diff --git a/test/fuzztest/access_token/getdefpermissions_fuzzer/BUILD.gn b/test/fuzztest/access_token/getdefpermissions_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c6ee63b5b1d2102c507dc8429260b04503472fc2 --- /dev/null +++ b/test/fuzztest/access_token/getdefpermissions_fuzzer/BUILD.gn @@ -0,0 +1,42 @@ +# 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") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GetDefPermissionsFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/getdefpermissions_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "getdefpermissions_fuzzer.cpp" ] + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + configs = [ "//base/security/access_token/config:coverage_flags" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/test/fuzztest/access_token/getdefpermissions_fuzzer/corpus/init b/test/fuzztest/access_token/getdefpermissions_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/access_token/getdefpermissions_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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/access_token/getdefpermissions_fuzzer/getdefpermissions_fuzzer.cpp b/test/fuzztest/access_token/getdefpermissions_fuzzer/getdefpermissions_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc3dbd70691f8ad4ed86c93d598400bff1c233a1 --- /dev/null +++ b/test/fuzztest/access_token/getdefpermissions_fuzzer/getdefpermissions_fuzzer.cpp @@ -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. + */ + +#include "getdefpermissions_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool GetDefPermissionsFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + std::vector permDefList; + result = AccessTokenKit::GetDefPermissions(TOKENID, permDefList); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::GetDefPermissionsFuzzTest(data, size); + return 0; +} + diff --git a/test/fuzztest/access_token/getdefpermissions_fuzzer/getdefpermissions_fuzzer.h b/test/fuzztest/access_token/getdefpermissions_fuzzer/getdefpermissions_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a4909408e621429f94c89ff19714fa9ae9d2f994 --- /dev/null +++ b/test/fuzztest/access_token/getdefpermissions_fuzzer/getdefpermissions_fuzzer.h @@ -0,0 +1,28 @@ +/* + * 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 TEST_FUZZTEST_GETDEFPERMISSIONS_FUZZER_H +#define TEST_FUZZTEST_GETDEFPERMISSIONS_FUZZER_H + +#include +#include +#include +#include +#include +#include + +#define FUZZ_PROJECT_NAME "getdefpermissions_fuzzer" + +#endif // TEST_FUZZTEST_GETDEFPERMISSIONS_FUZZER_H diff --git a/test/fuzztest/access_token/getdefpermissions_fuzzer/project.xml b/test/fuzztest/access_token/getdefpermissions_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/access_token/getdefpermissions_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/access_token/gethaptokenid_fuzzer/BUILD.gn b/test/fuzztest/access_token/gethaptokenid_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1940694afdfd2f7b80477936430f7db952eac6cb --- /dev/null +++ b/test/fuzztest/access_token/gethaptokenid_fuzzer/BUILD.gn @@ -0,0 +1,39 @@ +# 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") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GetHapTokenIDFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/gethaptokenid_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "gethaptokenid_fuzzer.cpp" ] + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/test/fuzztest/access_token/gethaptokenid_fuzzer/corpus/init b/test/fuzztest/access_token/gethaptokenid_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..c49c21aa8683c4d54af710059267afe15db14f96 --- /dev/null +++ b/test/fuzztest/access_token/gethaptokenid_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/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.cpp b/test/fuzztest/access_token/gethaptokenid_fuzzer/gethaptokenid_fuzzer.cpp similarity index 36% rename from services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.cpp rename to test/fuzztest/access_token/gethaptokenid_fuzzer/gethaptokenid_fuzzer.cpp index c139fe2ab0b812c572b4d82ed44d9f84a68c0956..de19c977837bfed0d2c8e8001610588872eb7d9e 100644 --- a/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.cpp +++ b/test/fuzztest/access_token/gethaptokenid_fuzzer/gethaptokenid_fuzzer.cpp @@ -13,43 +13,38 @@ * limitations under the License. */ -#include "add_permission_used_record_test.h" +#include "gethaptokenid_fuzzer.h" -using namespace testing::ext; -using namespace OHOS::Security::AccessToken; - -void AddPermissionUsedRecordTest::SetUpTestCase() -{} +#include +#include +#include "accesstoken_kit.h" -void AddPermissionUsedRecordTest::TearDownTestCase() -{ -} +using namespace std; +using namespace OHOS::Security::AccessToken; -void AddPermissionUsedRecordTest::SetUp() -{ +namespace OHOS { + bool GetHapTokenIDFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size >= 0) { + int userID = static_cast(size); + std::string testName(reinterpret_cast(data), size); + int instIndex = static_cast(size); + result = AccessTokenKit::GetHapTokenID(userID, testName, instIndex); + + } + return result; + } } -void AddPermissionUsedRecordTest::TearDown() +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + /* Run your code on data */ + OHOS::GetHapTokenIDFuzzTest(data, size); + return 0; } -/** - * @tc.name: AddPermissionUsedRecord_001 - * @tc.desc: cannot AddPermissionUsedRecord with invalid tokenID and permission. - * @tc.type: FUNC - * @tc.require:AR000GK6TD===== - */ -HWTEST_F(AddPermissionUsedRecordTest, AddPermissionUsedRecord_001, TestSize.Level1) -{ - int32_t successCount = 1; - int32_t fasilCount = 0; - std::string permission = "ohon.permission.READ_CONTACTS"; - AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_InfoParmsA.userID, - g_InfoParmsA.bundleName, - g_InfoParmsA.instIndex); - int32_t ret = PrivacyKit::AddPermissionUsedRecord(0, permission, successCount, fasilCount); - ASSERT_EQ(RET_FAILED, ret); - - ret = PrivacyKit::AddPermissionUsedRecord(tokenID, "", successCount, fasilCount); - ASSERT_EQ(RET_FAILED, ret); -} diff --git a/test/fuzztest/access_token/gethaptokenid_fuzzer/gethaptokenid_fuzzer.h b/test/fuzztest/access_token/gethaptokenid_fuzzer/gethaptokenid_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..eb0e784cf8ae339fd23268ed76af4b324ba69de7 --- /dev/null +++ b/test/fuzztest/access_token/gethaptokenid_fuzzer/gethaptokenid_fuzzer.h @@ -0,0 +1,28 @@ +/* + * 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 TEST_FUZZTEST_GETHAPTOKENID_FUZZER_H +#define TEST_FUZZTEST_GETHAPTOKENID_FUZZER_H + +#include +#include +#include +#include +#include +#include + +#define FUZZ_PROJECT_NAME "gethaptokenid_fuzzer" + +#endif // TEST_FUZZTEST_GETHAPTOKENID_FUZZER_H diff --git a/test/fuzztest/access_token/gethaptokenid_fuzzer/project.xml b/test/fuzztest/access_token/gethaptokenid_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/access_token/gethaptokenid_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/access_token/gethaptokeninfo_fuzzer/BUILD.gn b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..05ee27bc4d0e1c21f0e9fd35d85f846b78db083f --- /dev/null +++ b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GetHapTokenInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/gethaptokeninfo_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "gethaptokeninfo_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + configs = [ "//base/security/access_token/config:coverage_flags" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/test/fuzztest/access_token/gethaptokeninfo_fuzzer/corpus/init b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..c49c21aa8683c4d54af710059267afe15db14f96 --- /dev/null +++ b/test/fuzztest/access_token/gethaptokeninfo_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/access_token/gethaptokeninfo_fuzzer/gethaptokeninfo_fuzzer.cpp b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/gethaptokeninfo_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1bb724453afa8c3c75483b19daff6221dc060dc6 --- /dev/null +++ b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/gethaptokeninfo_fuzzer.cpp @@ -0,0 +1,61 @@ +/* + * 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 "gethaptokeninfo_fuzzer.h" + +#include +#include +#include "accesstoken_kit.h" +#include "hap_token_info.h" + +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool GetHapTokenInfoFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + int num = static_cast(size); + char ver = static_cast(size); + AccessTokenID TOKENID = static_cast(size); + std::string testName(reinterpret_cast(data), size); + HapTokenInfo HapTokenInfotest = { + .ver = ver, + .userID = num, + .bundleName = testName, + .instIndex = num, + .dlpType = num, + .appID = testName, + .deviceID = testName, + .tokenID = TOKENID, + .tokenAttr = TOKENID, + }; + result = AccessTokenKit::GetHapTokenInfo(TOKENID, HapTokenInfotest); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::GetHapTokenInfoFuzzTest(data, size); + return 0; +} + diff --git a/test/fuzztest/access_token/gethaptokeninfo_fuzzer/gethaptokeninfo_fuzzer.h b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/gethaptokeninfo_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..6a7bef7d7ee2f0a07262f9df37be5b35568ce847 --- /dev/null +++ b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/gethaptokeninfo_fuzzer.h @@ -0,0 +1,28 @@ +/* + * 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 TEST_FUZZTEST_GETHAPTOKENINFO_FUZZER_H +#define TEST_FUZZTEST_GETHAPTOKENINFO_FUZZER_H + +#include +#include +#include +#include +#include +#include + +#define FUZZ_PROJECT_NAME "gethaptokeninfo_fuzzer" + +#endif // TEST_FUZZTEST_GETHAPTOKENINFO_FUZZER_H diff --git a/test/fuzztest/access_token/gethaptokeninfo_fuzzer/project.xml b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/access_token/gethaptokeninfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/access_token/getnativetokeninfo_fuzzer/BUILD.gn b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e0fd5387938d1abe311486cf275bd6dbbc73341c --- /dev/null +++ b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/BUILD.gn @@ -0,0 +1,42 @@ +# 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") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GetNativeTokenInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/getnativetokeninfo_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "getnativetokeninfo_fuzzer.cpp" ] + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + configs = [ "//base/security/access_token/config:coverage_flags" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/test/fuzztest/access_token/getnativetokeninfo_fuzzer/corpus/init b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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/access_token/getnativetokeninfo_fuzzer/getnativetokeninfo_fuzzer.cpp b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/getnativetokeninfo_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4dd6305e13793020aa0f91b490089941650474d8 --- /dev/null +++ b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/getnativetokeninfo_fuzzer.cpp @@ -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. + */ + +#include "getnativetokeninfo_fuzzer.h" + +#include +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool GetNativeTokenInfoFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + std::string testName(reinterpret_cast(data), size); + NativeTokenInfo NativeTokenInfotest; + result = AccessTokenKit::GetNativeTokenInfo(TOKENID, NativeTokenInfotest); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::GetNativeTokenInfoFuzzTest(data, size); + return 0; +} + diff --git a/test/fuzztest/access_token/getnativetokeninfo_fuzzer/getnativetokeninfo_fuzzer.h b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/getnativetokeninfo_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..cdf7d6f0cbe872c8e0ab4d5496870250c54a5e5c --- /dev/null +++ b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/getnativetokeninfo_fuzzer.h @@ -0,0 +1,28 @@ +/* + * 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 TEST_FUZZTEST_GETNATIVETOKENINFO_FUZZER_H +#define TEST_FUZZTEST_GETNATIVETOKENINFO_FUZZER_H + +#include +#include +#include +#include +#include +#include + +#define FUZZ_PROJECT_NAME "getnativetokeninfo_fuzzer" + +#endif // TEST_FUZZTEST_GETNATIVETOKENINFO_FUZZER_H diff --git a/test/fuzztest/access_token/getnativetokeninfo_fuzzer/project.xml b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/access_token/getnativetokeninfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/access_token/gettokentype_fuzzer/BUILD.gn b/test/fuzztest/access_token/gettokentype_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d448f999b563f4920cf755bdfab597db44edb8d6 --- /dev/null +++ b/test/fuzztest/access_token/gettokentype_fuzzer/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GetTokenTypeFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/gettokentype_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "gettokentype_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + configs = [ "//base/security/access_token/config:coverage_flags" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/test/fuzztest/access_token/gettokentype_fuzzer/corpus/init b/test/fuzztest/access_token/gettokentype_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..c49c21aa8683c4d54af710059267afe15db14f96 --- /dev/null +++ b/test/fuzztest/access_token/gettokentype_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/access_token/gettokentype_fuzzer/gettokentype_fuzzer.cpp b/test/fuzztest/access_token/gettokentype_fuzzer/gettokentype_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dffc609e95577bb26e26d2a3157dfd447d57aff1 --- /dev/null +++ b/test/fuzztest/access_token/gettokentype_fuzzer/gettokentype_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 "gettokentype_fuzzer.h" + +#include +#include +#include "accesstoken_kit.h" + +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool GetTokenTypeFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + ATokenTypeEnum ATokenType; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + ATokenType = AccessTokenKit::GetTokenType(TOKENID); + result = true; + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::GetTokenTypeFuzzTest(data, size); + return 0; +} + diff --git a/test/fuzztest/access_token/gettokentype_fuzzer/gettokentype_fuzzer.h b/test/fuzztest/access_token/gettokentype_fuzzer/gettokentype_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..e6faf332068d102ed230e4b50c22d6baead5cbae --- /dev/null +++ b/test/fuzztest/access_token/gettokentype_fuzzer/gettokentype_fuzzer.h @@ -0,0 +1,28 @@ +/* + * 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 TEST_FUZZTEST_GETTOKENTYPE_FUZZER_H +#define TEST_FUZZTEST_GETTOKENTYPE_FUZZER_H + +#include +#include +#include +#include +#include +#include + +#define FUZZ_PROJECT_NAME "gettokentype_fuzzer" + +#endif // TEST_FUZZTEST_GETTOKENTYPE_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/access_token/gettokentype_fuzzer/project.xml b/test/fuzztest/access_token/gettokentype_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/access_token/gettokentype_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/access_token/gettokentypeflag_fuzzer/BUILD.gn b/test/fuzztest/access_token/gettokentypeflag_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..193768d5d98dad1cd12603df9f680e3261cc9ac0 --- /dev/null +++ b/test/fuzztest/access_token/gettokentypeflag_fuzzer/BUILD.gn @@ -0,0 +1,39 @@ +# 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") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GetTokenTypeFlagFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/gettokentypeflag_fuzzer" + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "gettokentypeflag_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + configs = [ "//base/security/access_token/config:coverage_flags" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/test/fuzztest/access_token/gettokentypeflag_fuzzer/corpus/init b/test/fuzztest/access_token/gettokentypeflag_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..c49c21aa8683c4d54af710059267afe15db14f96 --- /dev/null +++ b/test/fuzztest/access_token/gettokentypeflag_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/access_token/gettokentypeflag_fuzzer/gettokentypeflag_fuzzer.cpp b/test/fuzztest/access_token/gettokentypeflag_fuzzer/gettokentypeflag_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce7732073416d8972c82dc70c250e8454b96fdc0 --- /dev/null +++ b/test/fuzztest/access_token/gettokentypeflag_fuzzer/gettokentypeflag_fuzzer.cpp @@ -0,0 +1,46 @@ +/* + * 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 "gettokentypeflag_fuzzer.h" + +#include +#include +#include "accesstoken_kit.h" + +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool GetTokenTypeFlagFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::GetTokenTypeFlag(TOKENID); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::GetTokenTypeFlagFuzzTest(data, size); + return 0; +} + diff --git a/test/fuzztest/access_token/gettokentypeflag_fuzzer/gettokentypeflag_fuzzer.h b/test/fuzztest/access_token/gettokentypeflag_fuzzer/gettokentypeflag_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..af9797a3f53f9bb518436fcd165768874a5ff0a5 --- /dev/null +++ b/test/fuzztest/access_token/gettokentypeflag_fuzzer/gettokentypeflag_fuzzer.h @@ -0,0 +1,28 @@ +/* + * 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 TEST_FUZZTEST_GETTOKENTYPEFLAG_FUZZER_H +#define TEST_FUZZTEST_GETTOKENTYPEFLAG_FUZZER_H + +#include +#include +#include +#include +#include +#include + +#define FUZZ_PROJECT_NAME "gettokentypeflag_fuzzer" + +#endif // TEST_FUZZTEST_GETTOKENTYPEFLAG_FUZZER_H diff --git a/test/fuzztest/access_token/gettokentypeflag_fuzzer/project.xml b/test/fuzztest/access_token/gettokentypeflag_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/access_token/gettokentypeflag_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/tools/accesstoken/src/atm_command.cpp b/tools/accesstoken/src/atm_command.cpp index eedb40e98ed417f4ea55cbd43ecff9dd9cac6423..ac069054181ca64cb5552666d47e84f76e3c7b23 100644 --- a/tools/accesstoken/src/atm_command.cpp +++ b/tools/accesstoken/src/atm_command.cpp @@ -88,40 +88,39 @@ ErrCode AtmCommand::RunAsHelpCommand() ErrCode AtmCommand::RunAsDumpCommand() { - ErrCode result = ERR_OK; + ErrCode results = ERR_OK; OptType type = DEFAULT; uint32_t tokenId = 0; std::string permissionName = ""; - int option = -1; int counter = 0; while (true) { counter++; - option = getopt_long(argc_, argv_, SHORT_OPTIONS_DUMP.c_str(), LONG_OPTIONS_DUMP, nullptr); + int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_DUMP.c_str(), LONG_OPTIONS_DUMP, nullptr); if (optind < 0 || optind > argc_) { return ERR_INVALID_VALUE; } if (option == -1) { if (counter == 1) { - result = RunAsCommandError(); + results = RunAsCommandError(); } break; } if (option == '?') { - result = RunAsCommandMissingOptionArgument(); + results = RunAsCommandMissingOptionArgument(); break; } - result = RunAsCommandExistentOptionArgument(option, type, tokenId, permissionName); + results = RunAsCommandExistentOptionArgument(option, type, tokenId, permissionName); } - if (result != ERR_OK) { + if (results != ERR_OK) { resultReceiver_.append(HELP_MSG_DUMP + "\n"); } else { - result = RunCommandByOperationType(type, tokenId, permissionName); + results = RunCommandByOperationType(type, tokenId, permissionName); } - return result; + return results; } ErrCode AtmCommand::RunAsPermCommand() @@ -130,11 +129,10 @@ ErrCode AtmCommand::RunAsPermCommand() OptType type = DEFAULT; uint32_t tokenId = 0; std::string permissionName = ""; - int option = -1; int counter = 0; while (true) { counter++; - option = getopt_long(argc_, argv_, SHORT_OPTIONS_PERM.c_str(), LONG_OPTIONS_PERM, nullptr); + int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_PERM.c_str(), LONG_OPTIONS_PERM, nullptr); if (optind < 0 || optind > argc_) { return ERR_INVALID_VALUE; }