From dbe1c4e5c608f22ba17e6e8a380f1008b01e1880 Mon Sep 17 00:00:00 2001 From: LHY6968 Date: Sat, 21 Jun 2025 19:24:07 +0800 Subject: [PATCH 1/3] forbide bio authentication caused by screenlock strong auth Signed-off-by: LHY6968 Change-Id: Ieec05457bc58fdea986a081e27d5cdbc4ce86a8e --- bundle.json | 5 +- .../common/dfx/inc/hisysevent_adapter.h | 6 + .../common/dfx/src/hisysevent_adapter.cpp | 12 ++ hisysevent.yaml | 7 +- interfaces/inner_api/iam_common_defines.h | 2 + sa_profile/default/useriam.cfg | 3 +- sa_profile/dynamic_load/useriam.cfg | 3 +- services/context/inc/context_pool.h | 1 + services/context/src/context_pool_impl.cpp | 19 ++ services/core/BUILD.gn | 27 +++ services/core/inc/os_accounts_manager.h | 36 ++++ services/core/inc/resource_node_pool.h | 2 + services/core/inc/risk_event_manager.h | 59 ++++++ .../core/inc/screenlock_status_listener.h | 67 ++++++ .../core/inc/strong_auth_status_manager.h | 37 ++++ .../core/src/os_accounts_manager_impl.cpp | 164 +++++++++++++++ .../core/src/os_accounts_manager_mock.cpp | 51 +++++ services/core/src/resource_node_pool_impl.cpp | 23 ++ services/core/src/risk_event_manager.cpp | 191 +++++++++++++++++ .../core/src/screenlock_status_listener.cpp | 126 +++++++++++ .../src/strong_auth_status_manager_impl.cpp | 197 ++++++++++++++++++ .../src/strong_auth_status_manager_mock.cpp | 61 ++++++ services/ipc/src/co_auth_service.cpp | 2 + services/ipc/src/service_init_manager.cpp | 7 + services/ipc/src/template_cache_manager.cpp | 164 +-------------- test/fuzztest/common_fuzzer/BUILD.gn | 27 +++ .../services/servicecore_fuzzer/BUILD.gn | 7 + .../inc/risk_event_manager_fuzzer.h | 28 +++ .../src/risk_event_manager_fuzzer.cpp | 154 ++++++++++++++ .../src/service_core_fuzzer.cpp | 2 + test/unittest/services/BUILD.gn | 39 +++- .../services/inc/os_accounts_manager_test.h | 37 ++++ .../services/inc/risk_event_manager_test.h | 37 ++++ .../inc/screenlock_status_listener_test.h | 36 ++++ .../inc/strong_auth_status_manager_test.h | 37 ++++ .../services/src/context_pool_test.cpp | 6 + .../services/src/os_accounts_manager_test.cpp | 62 ++++++ .../services/src/resource_node_pool_test.cpp | 24 +++ .../services/src/risk_event_manager_test.cpp | 114 ++++++++++ .../src/screenlock_status_listener_test.cpp | 78 +++++++ .../src/strong_auth_status_manager_test.cpp | 71 +++++++ .../src/template_cache_manager_test.cpp | 70 ------- 42 files changed, 1862 insertions(+), 239 deletions(-) create mode 100644 services/core/inc/os_accounts_manager.h create mode 100644 services/core/inc/risk_event_manager.h create mode 100644 services/core/inc/screenlock_status_listener.h create mode 100644 services/core/inc/strong_auth_status_manager.h create mode 100644 services/core/src/os_accounts_manager_impl.cpp create mode 100644 services/core/src/os_accounts_manager_mock.cpp create mode 100644 services/core/src/risk_event_manager.cpp create mode 100644 services/core/src/screenlock_status_listener.cpp create mode 100644 services/core/src/strong_auth_status_manager_impl.cpp create mode 100644 services/core/src/strong_auth_status_manager_mock.cpp create mode 100644 test/fuzztest/services/servicecore_fuzzer/inc/risk_event_manager_fuzzer.h create mode 100644 test/fuzztest/services/servicecore_fuzzer/src/risk_event_manager_fuzzer.cpp create mode 100644 test/unittest/services/inc/os_accounts_manager_test.h create mode 100644 test/unittest/services/inc/risk_event_manager_test.h create mode 100644 test/unittest/services/inc/screenlock_status_listener_test.h create mode 100644 test/unittest/services/inc/strong_auth_status_manager_test.h create mode 100644 test/unittest/services/src/os_accounts_manager_test.cpp create mode 100644 test/unittest/services/src/risk_event_manager_test.cpp create mode 100644 test/unittest/services/src/screenlock_status_listener_test.cpp create mode 100644 test/unittest/services/src/strong_auth_status_manager_test.cpp diff --git a/bundle.json b/bundle.json index b58251681..191738c20 100644 --- a/bundle.json +++ b/bundle.json @@ -57,7 +57,10 @@ "ets_frontend", "hiappevent", "jsoncpp", - "screenlock_mgr" + "screenlock_mgr", + "ffrt", + "preferences", + "eventhandler" ] }, "build": { diff --git a/frameworks/native/common/dfx/inc/hisysevent_adapter.h b/frameworks/native/common/dfx/inc/hisysevent_adapter.h index 6472834e4..34d8a9728 100644 --- a/frameworks/native/common/dfx/inc/hisysevent_adapter.h +++ b/frameworks/native/common/dfx/inc/hisysevent_adapter.h @@ -114,6 +114,11 @@ struct IsCredentialEnrolledMismatchTrace { bool updatedStatus = false; }; +struct ScreenLockStrongAuthTrace { + int32_t userId = 0; + int32_t strongAuthReason = 0; +}; + void ReportSystemFault(const std::string &timeString, const std::string &moduleName); void ReportSecurityTemplateChange(const TemplateChangeTrace &info); void ReportBehaviorCredManager(const UserCredManagerTrace &info); @@ -125,6 +130,7 @@ void ReportRemoteConnectOpen(const RemoteConnectOpenTrace &info); void ReportConnectFaultTrace(const RemoteConnectFaultTrace &info); void ReportSaLoadDriverFailure(const SaLoadDriverFailureTrace &info); void ReportIsCredentialEnrolledMismatch(const IsCredentialEnrolledMismatchTrace &info); +void ReportScreenLockStrongAuth(const ScreenLockStrongAuthTrace &info); } // namespace UserAuth } // namespace UserIam } // namespace OHOS diff --git a/frameworks/native/common/dfx/src/hisysevent_adapter.cpp b/frameworks/native/common/dfx/src/hisysevent_adapter.cpp index 099bbc3ac..aaae643c1 100644 --- a/frameworks/native/common/dfx/src/hisysevent_adapter.cpp +++ b/frameworks/native/common/dfx/src/hisysevent_adapter.cpp @@ -62,6 +62,7 @@ constexpr char STR_IS_BACKGROUND_APPLICATION[] = "IS_BACKGROUND_APPLICATION"; constexpr char STR_ERROR_CODE[] = "ERROR_CODE"; constexpr char STR_PREVIOUS_STATUS[] = "PREVIOUS_STATUS"; constexpr char STR_UPDATED_STATUS[] = "UPDATED_STATUS"; +constexpr char STRONG_AUTH_REASON[] = "STRONG_AUTH_REASON"; static std::string MaskForStringId(const std::string &id) { @@ -243,6 +244,17 @@ void ReportIsCredentialEnrolledMismatch(const IsCredentialEnrolledMismatchTrace IAM_LOGE("hisysevent write failed! ret %{public}d", ret); } } + +void ReportScreenLockStrongAuth(const ScreenLockStrongAuthTrace &info) +{ + int32_t ret = HiSysEventWrite(HiSysEvent::Domain::USERIAM_FWK, "SCREENLOCK_STRONG_AUTH", + HiSysEvent::EventType::SECURITY, + STR_USER_ID, info.userId, + STRONG_AUTH_REASON, info.strongAuthReason); + if (ret != 0) { + IAM_LOGE("hisysevent write failed! ret %{public}d", ret); + } +} } // namespace UserAuth } // namespace UserIam } // namespace OHOS \ No newline at end of file diff --git a/hisysevent.yaml b/hisysevent.yaml index 8c70b2c03..771c8c73b 100644 --- a/hisysevent.yaml +++ b/hisysevent.yaml @@ -105,4 +105,9 @@ IS_CREDENTIAL_ENROLLED_MISMATCH: __BASE: {type: STATISTIC, level: CRITICAL, tag: UserAuth, desc: credential judgement system param mismatches actual credential} AUTH_TYPE: {type: INT32, desc: auth type} PREVIOUS_STATUS: {type: BOOL, desc: system param value before update} - UPDATED_STATUS: {type: BOOL, desc: system param value updated} \ No newline at end of file + UPDATED_STATUS: {type: BOOL, desc: system param value updated} + +SCREENLOCK_STRONG_AUTH: + __BASE: {type: SECURITY, level: CRITICAL, tag: UserAuth, desc: screen lock triggers strong authentication} + USER_ID: {type: INT32, desc: user id} + STRONG_AUTH_REASON: {type: INT32, desc: reason for screenlock activates strong authentication} \ No newline at end of file diff --git a/interfaces/inner_api/iam_common_defines.h b/interfaces/inner_api/iam_common_defines.h index 22023c093..bdf3ce177 100644 --- a/interfaces/inner_api/iam_common_defines.h +++ b/interfaces/inner_api/iam_common_defines.h @@ -161,6 +161,8 @@ enum PropertyMode : uint32_t { PROPERTY_MODE_SET_CACHED_TEMPLATES = 7, /** The property mode is notify collector ready. */ PROPERTY_MODE_NOTIFY_COLLECTOR_READY = 8, + /** The property mode is risk event. */ + PROPERTY_MODE_RISK_EVENT = 9, }; /** diff --git a/sa_profile/default/useriam.cfg b/sa_profile/default/useriam.cfg index 656242062..b2514d47c 100644 --- a/sa_profile/default/useriam.cfg +++ b/sa_profile/default/useriam.cfg @@ -30,7 +30,8 @@ "ohos.permission.PERMISSION_USED_STATS", "ohos.permission.MANAGE_USER_IDM", "ohos.permission.USE_USER_IDM", - "ohos.permission.MANAGE_CAMERA_CONFIG" + "ohos.permission.MANAGE_CAMERA_CONFIG", + "ohos.permission.ACCESS_SCREEN_LOCK" ], "permission_acls" : [ "ohos.permission.ACCESS_AUTH_RESPOOL", diff --git a/sa_profile/dynamic_load/useriam.cfg b/sa_profile/dynamic_load/useriam.cfg index 320a56fc0..504d5e315 100644 --- a/sa_profile/dynamic_load/useriam.cfg +++ b/sa_profile/dynamic_load/useriam.cfg @@ -73,7 +73,8 @@ "ohos.permission.RUNNING_STATE_OBSERVER", "ohos.permission.DISTRIBUTED_DATASYNC", "ohos.permission.MANAGE_USER_IDM", - "ohos.permission.USE_USER_IDM" + "ohos.permission.USE_USER_IDM", + "ohos.permission.ACCESS_SCREEN_LOCK" ], "permission_acls" : [ "ohos.permission.ACCESS_AUTH_RESPOOL", diff --git a/services/context/inc/context_pool.h b/services/context/inc/context_pool.h index a5a27936e..1c06c82cd 100644 --- a/services/context/inc/context_pool.h +++ b/services/context/inc/context_pool.h @@ -40,6 +40,7 @@ public: virtual std::shared_ptr SelectScheduleNodeByScheduleId(uint64_t scheduleId) = 0; virtual bool RegisterContextPoolListener(const std::shared_ptr &listener) = 0; virtual bool DeregisterContextPoolListener(const std::shared_ptr &listener) = 0; + virtual void StartSubscribeOsAccountSaStatus() = 0; }; } // namespace UserAuth } // namespace UserIam diff --git a/services/context/src/context_pool_impl.cpp b/services/context/src/context_pool_impl.cpp index 9528ff175..b5e8343d4 100644 --- a/services/context/src/context_pool_impl.cpp +++ b/services/context/src/context_pool_impl.cpp @@ -21,6 +21,9 @@ #include #include +#include "system_ability_definition.h" +#include "system_ability_listener.h" + #include "iam_logger.h" #include "iam_para2str.h" #include "iam_check.h" @@ -58,12 +61,14 @@ public: std::shared_ptr SelectScheduleNodeByScheduleId(uint64_t scheduleId) override; bool RegisterContextPoolListener(const std::shared_ptr &listener) override; bool DeregisterContextPoolListener(const std::shared_ptr &listener) override; + void StartSubscribeOsAccountSaStatus() override; private: void CheckPreemptContext(const std::shared_ptr &context); mutable std::recursive_mutex poolMutex_; std::unordered_map> contextMap_; std::set> listenerSet_; + sptr accountSaStatusListener_ {nullptr}; }; void ContextPoolImpl::CheckPreemptContext(const std::shared_ptr &context) @@ -207,6 +212,20 @@ bool ContextPoolImpl::DeregisterContextPoolListener(const std::shared_ptr lock(poolMutex_); + if (accountSaStatusListener_ != nullptr) { + return; + } + accountSaStatusListener_ = SystemAbilityListener::Subscribe( + "OsAccountService", SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN, + []() {}, + []() { ContextPool::Instance().CancelAll(); }); + IF_FALSE_LOGE_AND_RETURN(accountSaStatusListener_ != nullptr); +} + ContextPool &ContextPool::Instance() { return ContextPoolImpl::GetInstance(); diff --git a/services/core/BUILD.gn b/services/core/BUILD.gn index e34604bd7..60888b650 100644 --- a/services/core/BUILD.gn +++ b/services/core/BUILD.gn @@ -70,10 +70,12 @@ ohos_source_set("userauth_service_core") { "src/resource_node_impl.cpp", "src/resource_node_pool_impl.cpp", "src/resource_node_utils.cpp", + "src/risk_event_manager.cpp", "src/schedule_node_builder.cpp", "src/schedule_node_helper.cpp", "src/schedule_node_impl.cpp", "src/schedule_resource_node_listener.cpp", + "src/screenlock_status_listener.cpp", "src/secure_user_info_impl.cpp", "src/system_param_manager.cpp", "src/update_pin_param_impl.cpp", @@ -106,9 +108,34 @@ ohos_source_set("userauth_service_core") { "samgr:samgr_proxy", ] + defines = [] + if (screenlock_client_enable) { + external_deps += [ + "eventhandler:libeventhandler", + "ffrt:libffrt", + "preferences:native_preferences", + "screenlock_mgr:screenlock_client", + "window_manager:libdm_lite", + ] + sources += [ + "src/strong_auth_status_manager_impl.cpp", + ] + } else { + sources += [ + "src/strong_auth_status_manager_mock.cpp", + ] + } + if (has_os_account_part) { cflags_cc = [ "-DHAS_OS_ACCOUNT_PART" ] external_deps += [ "os_account:os_account_innerkits" ] + sources += [ + "src/os_accounts_manager_impl.cpp", + ] + } else { + sources += [ + "src/os_accounts_manager_mock.cpp", + ] } if (has_notification_common_event_service) { diff --git a/services/core/inc/os_accounts_manager.h b/services/core/inc/os_accounts_manager.h new file mode 100644 index 000000000..132b8eeda --- /dev/null +++ b/services/core/inc/os_accounts_manager.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OS_ACCOUNTS_MANAGER_H +#define OS_ACCOUNTS_MANAGER_H + +#include +#include + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class OsAccountsManager { +public: + static OsAccountsManager &Instance(); + + virtual void StartSubscribe() = 0; + virtual void OnOsAccountSaAdd() = 0; + virtual void OnOsAccountSaRemove() = 0; +}; +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // OS_ACCOUNTS_MANAGER_H \ No newline at end of file diff --git a/services/core/inc/resource_node_pool.h b/services/core/inc/resource_node_pool.h index 2567d1188..ca545bd08 100644 --- a/services/core/inc/resource_node_pool.h +++ b/services/core/inc/resource_node_pool.h @@ -44,6 +44,8 @@ public: virtual void Enumerate(std::function &)> action) const = 0; virtual bool RegisterResourceNodePoolListener(const std::shared_ptr &listener) = 0; virtual bool DeregisterResourceNodePoolListener(const std::shared_ptr &listener) = 0; + virtual void GetResourceNodeByTypeAndRole(AuthType authType, + ExecutorRole role, std::vector> &authTypeNodes) = 0; }; } // namespace UserAuth } // namespace UserIam diff --git a/services/core/inc/risk_event_manager.h b/services/core/inc/risk_event_manager.h new file mode 100644 index 000000000..94226e86b --- /dev/null +++ b/services/core/inc/risk_event_manager.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RISK_EVENT_MANAGER_H +#define RISK_EVENT_MANAGER_H + +#include + +#include "attributes.h" +#include "iam_common_defines.h" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class RiskEventManager { +public: + static RiskEventManager &GetInstance(); + + void HandleStrongAuthEvent(int32_t userId); + void SyncRiskEvents(); + void OnScreenLock(); + +#ifndef IAM_TEST_ENABLE +private: +#endif + enum EventType : uint32_t { + UNKNOWN = 0, + SCREENLOCK_STRONG_AUTH = 1 + }; + + RiskEventManager() = default; + ~RiskEventManager() = default; + + void SetRiskEventPropertyForAuthType(int32_t userId, const AuthType authType, + EventType event); + ResultCode GetTemplateIdList(int32_t userId, const AuthType authType, + std::vector &templateIds); + ResultCode GetStrongAuthExtraInfo(int32_t userId, const AuthType authType, + std::vector &extraInfo); + bool IsScreenLockStrongAuth(int32_t userId); + ResultCode SetAttributes(int32_t userId, const AuthType authType, + EventType event, Attributes &attributes); +}; +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // RISK_EVENT_MANAGER_H \ No newline at end of file diff --git a/services/core/inc/screenlock_status_listener.h b/services/core/inc/screenlock_status_listener.h new file mode 100644 index 000000000..01e9a4321 --- /dev/null +++ b/services/core/inc/screenlock_status_listener.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SCREENLOCK_STATUS_LISTENER_H +#define SCREENLOCK_STATUS_LISTENER_H + +#include "common_event_manager.h" +#include "common_event_subscriber.h" +#include "common_event_support.h" +#include "system_ability_definition.h" + +#include "iam_check.h" +#include "iam_common_defines.h" +#include "iam_logger.h" +#include "iam_ptr.h" +#include "system_ability_listener.h" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +using CommonEventSubscriber = OHOS::EventFwk::CommonEventSubscriber; +using CommonEventData = OHOS::EventFwk::CommonEventData; +using CommonEventSubscribeInfo = OHOS::EventFwk::CommonEventSubscribeInfo; + +class ScreenlockStatusListener : public CommonEventSubscriber { +public: + explicit ScreenlockStatusListener(const CommonEventSubscribeInfo &subscriberInfo) + : CommonEventSubscriber(subscriberInfo) {} + ~ScreenlockStatusListener() = default; + + void OnReceiveEvent(const CommonEventData &data) override; +}; + +class ScreenlockStatusListenerManager { +public: + static ScreenlockStatusListenerManager &GetInstance(); + + ResultCode RegisterCommonEventListener(); + +private: + ScreenlockStatusListenerManager() = default; + ~ScreenlockStatusListenerManager() = default; + + void RegisterScreenLockedCallback(); + void UnRegisterScreenLockedCallback(); + void SyncScreenlockStatus(); + + std::shared_ptr subscriber_ {nullptr}; + sptr commonEventSaStatusListener_ {nullptr}; + std::recursive_mutex mutex_; +}; +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // SCREENLOCK_STATUS_LISTENER_H \ No newline at end of file diff --git a/services/core/inc/strong_auth_status_manager.h b/services/core/inc/strong_auth_status_manager.h new file mode 100644 index 000000000..ceb4bd1dd --- /dev/null +++ b/services/core/inc/strong_auth_status_manager.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STRONG_AUTH_STATUS_MANAGER_H +#define STRONG_AUTH_STATUS_MANAGER_H + +#include "iam_common_defines.h" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class StrongAuthStatusManager { +public: + static StrongAuthStatusManager &Instance(); + + virtual void RegisterStrongAuthListener() = 0; + virtual void UnRegisterStrongAuthListener() = 0; + virtual void StartSubscribe() = 0; + virtual bool IsScreenLockStrongAuth(int32_t userId) = 0; + virtual void SyncStrongAuthStatusForAllAccounts() = 0; +}; +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // STRONG_AUTH_STATUS_MANAGER_H \ No newline at end of file diff --git a/services/core/src/os_accounts_manager_impl.cpp b/services/core/src/os_accounts_manager_impl.cpp new file mode 100644 index 000000000..38c03955f --- /dev/null +++ b/services/core/src/os_accounts_manager_impl.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "os_accounts_manager.h" + +#include + +#include "iservice_registry.h" +#include "os_account_manager.h" +#include "system_ability_definition.h" +#include "system_ability_status_change_stub.h" + +#include "context_pool.h" +#include "iam_check.h" +#include "iam_common_defines.h" +#include "iam_logger.h" +#include "iam_ptr.h" +#include "ipc_common.h" +#include "resource_node_pool.h" +#include "resource_node_utils.h" +#include "system_ability_listener.h" +#include "template_cache_manager.h" +#include "thread_handler.h" +#include "user_idm_database.h" + +#define LOG_TAG "USER_AUTH_SA" +namespace OHOS { +namespace UserIam { +namespace UserAuth { +namespace { +using OsAccountSubscriber = AccountSA::OsAccountSubscriber; +using OsAccountSubscribeInfo = AccountSA::OsAccountSubscribeInfo; +using OS_ACCOUNT_SUBSCRIBE_TYPE = AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE; +void HandleAccountsChanged(const int &id) +{ + auto threadHandler = ThreadHandler::GetSingleThreadInstance(); + + if (threadHandler == nullptr) { + IAM_LOGE("threadHandler is nullptr"); + return; + } + + threadHandler->PostTask([id]() { + TemplateCacheManager::GetInstance().ProcessUserIdChange(id); + }); +} + +void SyncOsAccountIdStatus() +{ + IAM_LOGI("start"); + std::optional userIdOpt = INVALID_USER_ID; + int32_t ret = IpcCommon::GetActiveUserId(userIdOpt); + if (ret != SUCCESS || userIdOpt.has_value()) { + IAM_LOGE("get current user id fail"); + return; + } + int32_t userId = userIdOpt.value(); + if (userId == INVALID_USER_ID) { + IAM_LOGE("invalid user id"); + return; + } + HandleAccountsChanged(userId); +} +} + +class UserIamOsAccountSubscriber : public OsAccountSubscriber, public NoCopyable { +public: + explicit UserIamOsAccountSubscriber(const OsAccountSubscribeInfo &subscribeInfo); + ~UserIamOsAccountSubscriber() = default; + + void OnAccountsChanged(const int &id) override; +}; + +class OsAccountsManagerImpl final : public OsAccountsManager, public Singleton { +public: + void StartSubscribe() override; + void OnOsAccountSaAdd() override; + void OnOsAccountSaRemove() override; + +private: + sptr accountSaStatusListener_ {nullptr}; + std::shared_ptr subscriber_ {nullptr}; + std::recursive_mutex mutex_; +}; + +UserIamOsAccountSubscriber::UserIamOsAccountSubscriber(const OsAccountSubscribeInfo &subscribeInfo) + : OsAccountSubscriber(subscribeInfo) +{ +} + +void UserIamOsAccountSubscriber::OnAccountsChanged(const int &id) +{ + IAM_LOGI("OnAccountsChanged %{public}d", id); + HandleAccountsChanged(id); +} + +void OsAccountsManagerImpl::StartSubscribe() +{ + IAM_LOGI("start"); + std::lock_guard lock(mutex_); + if (accountSaStatusListener_ != nullptr) { + return; + } + accountSaStatusListener_ = SystemAbilityListener::Subscribe( + "OsAccountService", SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN, + []() { OsAccountsManager::Instance().OnOsAccountSaAdd(); }, + []() { OsAccountsManager::Instance().OnOsAccountSaRemove(); }); + IF_FALSE_LOGE_AND_RETURN(accountSaStatusListener_ != nullptr); +} + +void OsAccountsManagerImpl::OnOsAccountSaAdd() +{ + IAM_LOGI("start"); + if (subscriber_ != nullptr) { + return; + } + OsAccountSubscribeInfo subscribeInfo; + subscribeInfo.SetOsAccountSubscribeType(OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVATED); + auto subscriber = Common::MakeShared(subscribeInfo); + IF_FALSE_LOGE_AND_RETURN(subscriber != nullptr); + + ErrCode errCode = AccountSA::OsAccountManager::SubscribeOsAccount(subscriber); + if (errCode != ERR_OK) { + IAM_LOGE("subscribe fail, errCode = %{public}d", errCode); + return; + } + subscriber_ = subscriber; + SyncOsAccountIdStatus(); +} + +void OsAccountsManagerImpl::OnOsAccountSaRemove() +{ + IAM_LOGI("start"); + if (subscriber_ == nullptr) { + return; + } + + ErrCode errCode = AccountSA::OsAccountManager::UnsubscribeOsAccount(subscriber_); + if (errCode != ERR_OK) { + IAM_LOGE("unsubscribe fail, errCode = %{public}d", errCode); + return; + } + subscriber_ = nullptr; +} + +OsAccountsManager &OsAccountsManager::Instance() +{ + return OsAccountsManagerImpl::GetInstance(); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/services/core/src/os_accounts_manager_mock.cpp b/services/core/src/os_accounts_manager_mock.cpp new file mode 100644 index 000000000..06c390041 --- /dev/null +++ b/services/core/src/os_accounts_manager_mock.cpp @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "os_accounts_manager.h" + +#include + +#include "system_ability_listener.h" + +#define LOG_TAG "USER_AUTH_SA" +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class OsAccountsManagerImpl final : public OsAccountsManager, public Singleton { +public: + void StartSubscribe() override; + void OnOsAccountSaAdd() override; + void OnOsAccountSaRemove() override; +}; + +void OsAccountsManagerImpl::StartSubscribe() +{ +} + +void OsAccountsManagerImpl::OnOsAccountSaAdd() +{ +} + +void OsAccountsManagerImpl::OnOsAccountSaRemove() +{ +} + +OsAccountsManager &OsAccountsManager::Instance() +{ + return OsAccountsManagerImpl::GetInstance(); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/services/core/src/resource_node_pool_impl.cpp b/services/core/src/resource_node_pool_impl.cpp index be815ad5a..4dbb9a91e 100644 --- a/services/core/src/resource_node_pool_impl.cpp +++ b/services/core/src/resource_node_pool_impl.cpp @@ -39,6 +39,8 @@ public: void Enumerate(std::function &)> action) const override; bool RegisterResourceNodePoolListener(const std::shared_ptr &listener) override; bool DeregisterResourceNodePoolListener(const std::shared_ptr &listener) override; + void GetResourceNodeByTypeAndRole(AuthType authType, + ExecutorRole role, std::vector> &authTypeNodes) override; private: struct ResourceNodeParam { @@ -186,6 +188,27 @@ bool ResourceNodePoolImpl::DeregisterResourceNodePoolListener(const std::shared_ return listenerSet_.erase(listener) == 1; } +void ResourceNodePoolImpl::GetResourceNodeByTypeAndRole(AuthType authType, + ExecutorRole role, std::vector> &authTypeNodes) +{ + IAM_LOGI("start"); + authTypeNodes.clear(); + ResourceNodePool::Instance().Enumerate( + [&authTypeNodes, role, authType](const std::weak_ptr &weakNode) { + auto node = weakNode.lock(); + if (node == nullptr) { + return; + } + if (node->GetAuthType() != authType) { + return; + } + if (node->GetExecutorRole() != role) { + return; + } + authTypeNodes.push_back(node); + }); +} + ResourceNodePool &ResourceNodePool::Instance() { return ResourceNodePoolImpl::GetInstance(); diff --git a/services/core/src/risk_event_manager.cpp b/services/core/src/risk_event_manager.cpp new file mode 100644 index 000000000..627e3e27a --- /dev/null +++ b/services/core/src/risk_event_manager.cpp @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "risk_event_manager.h" + +#include "system_ability_definition.h" +#include "system_ability.h" + +#include "context_appstate_observer.h" +#include "ipc_common.h" +#include "strong_auth_status_manager.h" +#include "system_ability_listener.h" +#include "resource_node_pool.h" +#include "user_idm_database.h" + +#define LOG_TAG "USER_AUTH_SA" +namespace OHOS { +namespace UserIam { +namespace UserAuth { +RiskEventManager &RiskEventManager::GetInstance() +{ + static RiskEventManager instance; + return instance; +} + +void RiskEventManager::SetRiskEventPropertyForAuthType(int32_t userId, + const AuthType authType, EventType event) +{ + IAM_LOGI("start"); + Attributes attributes; + int32_t getAttrRet = SetAttributes(userId, authType, event, attributes); + if (getAttrRet != SUCCESS) { + IAM_LOGE("get attributes fail"); + return; + } + + std::vector> authTypeNodes; + ResourceNodePool::Instance().GetResourceNodeByTypeAndRole(authType, ALL_IN_ONE, authTypeNodes); + if (authTypeNodes.size() == 0) { + IAM_LOGE("authTypeNodes is empty"); + return; + } + + for (auto &authTypeNode : authTypeNodes) { + auto resourceNode = authTypeNode.lock(); + if (resourceNode != nullptr) { + int32_t result = resourceNode->SetProperty(attributes); + IAM_LOGI("set authType %{public}d property finish, ret:%{public}d", authType, result); + } else { + IAM_LOGE("resourceNode already expired"); + } + } +} + +ResultCode RiskEventManager::SetAttributes(int32_t userId, const AuthType authType, + EventType event, Attributes &attributes) +{ + IAM_LOGI("start"); + bool setModeRet = attributes.SetUint32Value(Attributes::ATTR_PROPERTY_MODE, + PropertyMode::PROPERTY_MODE_RISK_EVENT); + if (!setModeRet) { + IAM_LOGE("set property mode fail"); + return GENERAL_ERROR; + } + + std::vector extraInfo; + if (event != EventType::SCREENLOCK_STRONG_AUTH) { + IAM_LOGE("unknown event type"); + return GENERAL_ERROR; + } + + int32_t getExtraInfoRet = GetStrongAuthExtraInfo(userId, authType, extraInfo); + if (getExtraInfoRet != SUCCESS) { + IAM_LOGE("getExtraInfoRet fail"); + return GENERAL_ERROR; + } + bool setExtraInfoRet = attributes.SetUint8ArrayValue(Attributes::ATTR_EXTRA_INFO, extraInfo); + if (!setExtraInfoRet) { + IAM_LOGE("set extra info fail"); + return GENERAL_ERROR; + } + return SUCCESS; +} + +ResultCode RiskEventManager::GetTemplateIdList(int32_t userId, const AuthType authType, + std::vector &templateIds) +{ + IAM_LOGI("start"); + std::vector> credentialInfos; + int32_t getCredInfoRet = UserIdmDatabase::Instance().GetCredentialInfo(userId, authType, + credentialInfos); + if (getCredInfoRet == NOT_ENROLLED) { + IAM_LOGE("userId:%{public}d, authType:%{public}d not enrolled", userId, authType); + return NOT_ENROLLED; + } + + if (getCredInfoRet != SUCCESS) { + IAM_LOGE("get credential fail, ret:%{public}d, userId:%{public}d, authType:%{public}d", + getCredInfoRet, userId, authType); + return GENERAL_ERROR; + } + for (auto &info : credentialInfos) { + if (info == nullptr) { + IAM_LOGE("info is null"); + continue; + } + templateIds.push_back(info->GetTemplateId()); + } + return SUCCESS; +} + +ResultCode RiskEventManager::GetStrongAuthExtraInfo(int32_t userId, const AuthType authType, + std::vector &extraInfo) +{ + IAM_LOGI("start"); + std::vector templateIds; + ResultCode getTemplateIdsRet = GetTemplateIdList(userId, authType, templateIds); + if (getTemplateIdsRet != SUCCESS) { + IAM_LOGE("get template id list fail"); + return GENERAL_ERROR; + } + Attributes extraInfoAttr; + bool setTemplateIdListRet = extraInfoAttr.SetUint64ArrayValue(Attributes::ATTR_TEMPLATE_ID_LIST, + templateIds); + if (!setTemplateIdListRet) { + IAM_LOGE("set template id list fail"); + return GENERAL_ERROR; + } + + bool setAuthTypeRet = extraInfoAttr.SetInt32Value(Attributes::ATTR_AUTH_TYPE, authType); + if (!setAuthTypeRet) { + IAM_LOGE("set auth type fail"); + return GENERAL_ERROR; + } + extraInfo = extraInfoAttr.Serialize(); + return SUCCESS; +} + +void RiskEventManager::HandleStrongAuthEvent(int32_t userId) +{ + IAM_LOGI("handle strong auth event for userId:%{public}d", userId); + bool screenLockState = ContextAppStateObserverManager::GetInstance().IsScreenLocked(); + if (!screenLockState) { + IAM_LOGI("screen is not locked"); + return; + } + SetRiskEventPropertyForAuthType(userId, AuthType::FACE, EventType::SCREENLOCK_STRONG_AUTH); + SetRiskEventPropertyForAuthType(userId, AuthType::FINGERPRINT, EventType::SCREENLOCK_STRONG_AUTH); +} + +void RiskEventManager::SyncRiskEvents() +{ + IAM_LOGI("start"); + std::vector userIdList; + IpcCommon::GetAllUserId(userIdList); + for (int32_t &userId : userIdList) { + bool isScreenLockStrongAuth = StrongAuthStatusManager::Instance().IsScreenLockStrongAuth(userId); + if (isScreenLockStrongAuth) { + IAM_LOGI("screenlock in strong auth status for userId:%{public}d", userId); + HandleStrongAuthEvent(userId); + } + } +} + +void RiskEventManager::OnScreenLock() +{ + IAM_LOGI("start"); + auto handler = ThreadHandler::GetSingleThreadInstance(); + if (handler == nullptr) { + IAM_LOGE("GetSingleThreadInstance fail"); + return; + } + handler->PostTask([]() { + RiskEventManager::GetInstance().SyncRiskEvents(); + }); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/services/core/src/screenlock_status_listener.cpp b/services/core/src/screenlock_status_listener.cpp new file mode 100644 index 000000000..628697244 --- /dev/null +++ b/services/core/src/screenlock_status_listener.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "screenlock_status_listener.h" + +#include "common_event_subscribe_info.h" +#include "matching_skills.h" +#include "singleton.h" +#include "want.h" + +#include "context_appstate_observer.h" +#include "credential_info_interface.h" +#include "risk_event_manager.h" +#include "user_idm_database.h" + +#define LOG_TAG "USER_AUTH_SA" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +ScreenlockStatusListenerManager &ScreenlockStatusListenerManager::GetInstance() +{ + static ScreenlockStatusListenerManager instance; + return instance; +} + +ResultCode ScreenlockStatusListenerManager::RegisterCommonEventListener() +{ + IAM_LOGI("start"); + std::lock_guard lock(mutex_); + if (commonEventSaStatusListener_ != nullptr) { + IAM_LOGI("commonEventSaStatusListener_ is not nullptr"); + return SUCCESS; + } + commonEventSaStatusListener_ = SystemAbilityListener::Subscribe( + "common_event_service", COMMON_EVENT_SERVICE_ID, + []() { ScreenlockStatusListenerManager::GetInstance().RegisterScreenLockedCallback(); }, + []() { ScreenlockStatusListenerManager::GetInstance().UnRegisterScreenLockedCallback(); }); + if (commonEventSaStatusListener_ == nullptr) { + IAM_LOGE("commonEventSaStatusListener_ is nullptr"); + return GENERAL_ERROR; + } + + IAM_LOGI("success"); + return SUCCESS; +} + +void ScreenlockStatusListenerManager::RegisterScreenLockedCallback() +{ + IAM_LOGI("start"); + std::lock_guard lock(mutex_); + if (subscriber_ != nullptr) { + IAM_LOGI("ScreenlockStatusListener already subscribed"); + return; + } + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED); + + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + auto subscriber = Common::MakeShared(subscribeInfo); + if (!EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber)) { + IAM_LOGE("SubscribeCommonEvent fail"); + return; + } + subscriber_ = subscriber; + SyncScreenlockStatus(); + IAM_LOGI("success"); +} + +void ScreenlockStatusListenerManager::UnRegisterScreenLockedCallback() +{ + IAM_LOGI("start"); + std::lock_guard lock(mutex_); + if (subscriber_ == nullptr) { + IAM_LOGI("ScreenlockStatusListener already unsubscribed"); + return; + } + + if (!EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_)) { + IAM_LOGE("UnSubscribeCommonEvent failed"); + } + subscriber_ = nullptr; + IAM_LOGI("success"); +} + +void ScreenlockStatusListenerManager::SyncScreenlockStatus() +{ + IAM_LOGI("start"); + bool screenLockState = ContextAppStateObserverManager::GetInstance().IsScreenLocked(); + if (!screenLockState) { + IAM_LOGI("screen is not locked"); + return; + } + RiskEventManager::GetInstance().OnScreenLock(); + IAM_LOGI("success"); +} + +void ScreenlockStatusListener::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) +{ + std::string action = data.GetWant().GetAction(); + int32_t userId = data.GetWant().GetIntParam("userId", INVALID_USER_ID); + IAM_LOGI("OnReceiveEvent %{public}s, userId = %{public}d", action.c_str(), userId); + if (userId == INVALID_USER_ID) { + IAM_LOGE("Event userId invalid"); + return; + } + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { + IAM_LOGI("receive screen locked event"); + RiskEventManager::GetInstance().OnScreenLock(); + }; +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/services/core/src/strong_auth_status_manager_impl.cpp b/services/core/src/strong_auth_status_manager_impl.cpp new file mode 100644 index 000000000..d1e396b69 --- /dev/null +++ b/services/core/src/strong_auth_status_manager_impl.cpp @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "strong_auth_status_manager.h" + +#include + +#include "screenlock_common.h" +#include "screenlock_inner_listener.h" +#include "screenlock_manager.h" +#include "screenlock_system_ability.h" +#include "system_ability_definition.h" +#include "system_ability.h" + +#include "context_appstate_observer.h" +#include "hisysevent_adapter.h" +#include "ipc_common.h" +#include "resource_node_pool.h" +#include "risk_event_manager.h" +#include "screenlock_status_listener.h" +#include "system_ability_listener.h" +#include "user_auth_service.h" + +#define LOG_TAG "USER_AUTH_SA" +namespace OHOS { +namespace UserIam { +namespace UserAuth { +using StrongAuthListener = ScreenLock::StrongAuthListener; +using ScreenLockManager = ScreenLock::ScreenLockManager; +using StrongAuthReasonFlags = ScreenLock::StrongAuthReasonFlags; + +class UserIamStrongAuthListener : public StrongAuthListener { +public: + using StrongAuthListener::StrongAuthListener; + ~UserIamStrongAuthListener() override = default; + + void OnStrongAuthChanged(int32_t userId, int32_t strongAuthStatus) override; +}; + +class StrongAuthStatusManagerImpl final : public StrongAuthStatusManager, public Singleton { +public: + void RegisterStrongAuthListener() override; + void UnRegisterStrongAuthListener() override; + void StartSubscribe() override; + bool IsScreenLockStrongAuth(int32_t userId) override; + void SyncStrongAuthStatusForAllAccounts() override; + +private: + std::recursive_mutex mutex_; + sptr screenLockSaStatusListener_ {nullptr}; + sptr strongAuthListener_ {nullptr}; +}; + +void UserIamStrongAuthListener::OnStrongAuthChanged(int32_t userId, int32_t strongAuthStatus) +{ + IAM_LOGI("strong auth state changed to %{public}d for userId %{public}d", strongAuthStatus, userId); + if (strongAuthStatus != static_cast(StrongAuthReasonFlags::AFTER_BOOT) && + strongAuthStatus != static_cast(StrongAuthReasonFlags::NONE)) { + ScreenLockStrongAuthTrace screenLockStrongAuthTraceInfo = {}; + screenLockStrongAuthTraceInfo.userId = userId; + screenLockStrongAuthTraceInfo.strongAuthReason = strongAuthStatus; + UserIam::UserAuth::ReportScreenLockStrongAuth(screenLockStrongAuthTraceInfo); + } + auto handler = ThreadHandler::GetSingleThreadInstance(); + if (handler == nullptr) { + IAM_LOGE("GetSingleThreadInstance fail"); + return; + } + + handler->PostTask([userId]() { + int32_t reasonFlag = static_cast(StrongAuthReasonFlags::NONE); + ScreenLockManager::GetInstance()->GetStrongAuth(userId, reasonFlag); + if (reasonFlag == static_cast(StrongAuthReasonFlags::NONE)) { + IAM_LOGE("screenlock not in strong auth status"); + return; + } + RiskEventManager::GetInstance().HandleStrongAuthEvent(userId); + }); +} + +void StrongAuthStatusManagerImpl::RegisterStrongAuthListener() +{ + IAM_LOGI("start"); + std::lock_guard lock(mutex_); + if (strongAuthListener_ != nullptr) { + IAM_LOGI("strongAuthListener_ is not nullptr"); + } + + const int32_t ALL_USER_ID = -1; + strongAuthListener_ = + sptr(new (std::nothrow) UserIamStrongAuthListener(ALL_USER_ID)); + if (strongAuthListener_ == nullptr) { + IAM_LOGE("strongAuthListener_ is nullptr"); + } + + ScreenLockManager::GetInstance()->RegisterStrongAuthListener(strongAuthListener_); + if (strongAuthListener_ == nullptr) { + IAM_LOGE("RegisterStrongAuthListener fail"); + } + SyncStrongAuthStatusForAllAccounts(); +} + +void StrongAuthStatusManagerImpl::UnRegisterStrongAuthListener() +{ + IAM_LOGI("start"); + std::lock_guard lock(mutex_); + if (strongAuthListener_ == nullptr) { + IAM_LOGI("strongAuthListener_ is nullptr"); + return; + } + + int32_t ret = ScreenLockManager::GetInstance()->UnRegisterStrongAuthListener(strongAuthListener_); + if (ret != SUCCESS) { + IAM_LOGE("UnRegisterStrongAuthListener fail"); + } + + strongAuthListener_ = nullptr; +} + +void StrongAuthStatusManagerImpl::SyncStrongAuthStatusForAllAccounts() +{ + IAM_LOGI("start"); + std::lock_guard lock(mutex_); + std::vector userIdList; + IpcCommon::GetAllUserId(userIdList); + int32_t reasonFlag = static_cast(StrongAuthReasonFlags::NONE); + for (int32_t &userId : userIdList) { + auto screenLockManager = ScreenLockManager::GetInstance(); + if (screenLockManager == nullptr) { + IAM_LOGE("screenLockManger is nullptr"); + return; + } + screenLockManager->GetStrongAuth(userId, reasonFlag); + + if (strongAuthListener_ == nullptr) { + IAM_LOGE("strongAuthListener_ is nullptr"); + return; + } + strongAuthListener_->OnStrongAuthChanged(userId, reasonFlag); + reasonFlag = static_cast(StrongAuthReasonFlags::NONE); + } +} + +void StrongAuthStatusManagerImpl::StartSubscribe() +{ + IAM_LOGI("start"); + std::lock_guard lock(mutex_); + if (screenLockSaStatusListener_ != nullptr) { + return; + } + screenLockSaStatusListener_ = SystemAbilityListener::Subscribe( + "ScreenLockService", SCREENLOCK_SERVICE_ID, + []() + { + StrongAuthStatusManager::Instance().RegisterStrongAuthListener(); + ScreenlockStatusListenerManager::GetInstance().RegisterCommonEventListener(); + }, + []() { StrongAuthStatusManager::Instance().UnRegisterStrongAuthListener(); }); + IF_FALSE_LOGE_AND_RETURN(screenLockSaStatusListener_ != nullptr); +} + +bool StrongAuthStatusManagerImpl::IsScreenLockStrongAuth(int32_t userId) +{ + int32_t reasonFlag = static_cast(StrongAuthReasonFlags::NONE); + auto screenLockManager = ScreenLockManager::GetInstance(); + if (screenLockManager == nullptr) { + IAM_LOGE("screenLockManager is nullptr"); + return false; + } + screenLockManager->GetStrongAuth(userId, reasonFlag); + IAM_LOGI("get strong auth ret: %{public}d for userId: %{public}d", reasonFlag, userId); + if (reasonFlag == static_cast(StrongAuthReasonFlags::NONE)) { + IAM_LOGE("screenlock not in strong auth status"); + return false; + } + return true; +} + +StrongAuthStatusManager &StrongAuthStatusManager::Instance() +{ + return StrongAuthStatusManagerImpl::GetInstance(); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/services/core/src/strong_auth_status_manager_mock.cpp b/services/core/src/strong_auth_status_manager_mock.cpp new file mode 100644 index 000000000..e357bc0d2 --- /dev/null +++ b/services/core/src/strong_auth_status_manager_mock.cpp @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "strong_auth_status_manager.h" + +#include + +#define LOG_TAG "USER_AUTH_SA" +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class StrongAuthStatusManagerImpl final : public StrongAuthStatusManager, public Singleton { +public: + void RegisterStrongAuthListener() override; + void UnRegisterStrongAuthListener() override; + void StartSubscribe() override; + bool IsScreenLockStrongAuth(int32_t userId) override; + void SyncStrongAuthStatusForAllAccounts() override; +}; + +void StrongAuthStatusManagerImpl::RegisterStrongAuthListener() +{ +} + +void StrongAuthStatusManagerImpl::UnRegisterStrongAuthListener() +{ +} + +void StrongAuthStatusManagerImpl::StartSubscribe() +{ +} + +bool StrongAuthStatusManagerImpl::IsScreenLockStrongAuth(int32_t userId) +{ + (void)userId; + return false; +} + +void StrongAuthStatusManagerImpl::SyncStrongAuthStatusForAllAccounts() +{ +} + +StrongAuthStatusManager &StrongAuthStatusManager::Instance() +{ + return StrongAuthStatusManagerImpl::GetInstance(); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/services/ipc/src/co_auth_service.cpp b/services/ipc/src/co_auth_service.cpp index 9e45203e9..508d90cf6 100644 --- a/services/ipc/src/co_auth_service.cpp +++ b/services/ipc/src/co_auth_service.cpp @@ -38,6 +38,7 @@ #include "parameter.h" #include "relative_timer.h" #include "remote_connect_manager.h" +#include "risk_event_manager.h" #include "service_init_manager.h" #include "system_param_manager.h" #include "template_cache_manager.h" @@ -179,6 +180,7 @@ int32_t CoAuthService::ProcExecutorRegisterSuccess(std::shared_ptr callback); IAM_LOGI("update template cache after register success"); TemplateCacheManager::GetInstance().UpdateTemplateCache(resourceNode->GetAuthType()); + RiskEventManager::GetInstance().SyncRiskEvents(); }); return SUCCESS; diff --git a/services/ipc/src/service_init_manager.cpp b/services/ipc/src/service_init_manager.cpp index 2cd418580..f13463e8b 100644 --- a/services/ipc/src/service_init_manager.cpp +++ b/services/ipc/src/service_init_manager.cpp @@ -19,10 +19,13 @@ #include "iam_logger.h" #include "co_auth_service.h" +#include "context_pool.h" #include "driver_state_manager.h" #include "load_mode_handler.h" +#include "os_accounts_manager.h" #include "remote_auth_service.h" #include "soft_bus_manager.h" +#include "strong_auth_status_manager.h" #include "system_param_manager.h" #define IAM_LOG_TAG "USER_AUTH_SA" @@ -110,6 +113,10 @@ void ServiceInitManager::CheckAllServiceStart() IF_FALSE_LOGE_AND_RETURN(coAuthService != nullptr); coAuthService->RegisterAccessTokenListener(); + OsAccountsManager::Instance().StartSubscribe(); + ContextPool::Instance().StartSubscribeOsAccountSaStatus(); + StrongAuthStatusManager::Instance().StartSubscribe(); + DriverStateManager::GetInstance().StartSubscribe(); IAM_LOGI("all service start, init global instance end"); diff --git a/services/ipc/src/template_cache_manager.cpp b/services/ipc/src/template_cache_manager.cpp index 2bc364679..b655b641d 100644 --- a/services/ipc/src/template_cache_manager.cpp +++ b/services/ipc/src/template_cache_manager.cpp @@ -35,171 +35,9 @@ namespace OHOS { namespace UserIam { namespace UserAuth { -namespace { -int32_t GetCurrentUserId() -{ - std::vector ids; - ErrCode queryRet = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids); - if (queryRet != ERR_OK || ids.empty()) { - IAM_LOGE("failed to query active account id ret %{public}d count %{public}zu", - queryRet, ids.size()); - return INVALID_USER_ID; - } - return ids.front(); -} -} -using OsAccountSubscriber = AccountSA::OsAccountSubscriber; -using OsAccountSubscribeInfo = AccountSA::OsAccountSubscribeInfo; -using OS_ACCOUNT_SUBSCRIBE_TYPE = AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE; - -class ServiceStatusListener : public OHOS::SystemAbilityStatusChangeStub, public NoCopyable { -public: - static sptr GetInstance(); - static void Subscribe(); - - void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; - void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; - -private: - ServiceStatusListener() {}; - ~ServiceStatusListener() override {}; -}; - -class OsAccountIdSubscriber : public OsAccountSubscriber, public NoCopyable { -public: - explicit OsAccountIdSubscriber(const OsAccountSubscribeInfo &subscribeInfo); - ~OsAccountIdSubscriber() = default; - - static std::shared_ptr GetInstance(); - static void Subscribe(); - static void Unsubscribe(); - void OnAccountsChanged(const int& id) override; - -private: - std::shared_ptr threadHandler_; -}; - -void ServiceStatusListener::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) -{ - if (systemAbilityId != SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { - return; - } - - IAM_LOGI("os account service added"); - OsAccountIdSubscriber::Subscribe(); - IAM_LOGI("os account service add process finish"); -} - -void ServiceStatusListener::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) -{ - if (systemAbilityId != SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { - return; - } - - IAM_LOGI("os account service removed"); - OsAccountIdSubscriber::Unsubscribe(); - ContextPool::Instance().CancelAll(); - IAM_LOGI("os account service remove process finish"); -} - -sptr ServiceStatusListener::GetInstance() -{ - static sptr listener(new (std::nothrow) ServiceStatusListener()); - if (listener == nullptr) { - IAM_LOGE("ServiceStatusListener is null"); - } - return listener; -} - -void ServiceStatusListener::Subscribe() -{ - auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (sam == nullptr) { - IAM_LOGE("failed to get SA manager"); - return; - } - - auto instance = GetInstance(); - IF_FALSE_LOGE_AND_RETURN(instance != NULL); - - int32_t ret = sam->SubscribeSystemAbility(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN, instance); - if (ret != ERR_OK) { - IAM_LOGE("failed to subscribe os account service status"); - return; - } - - IAM_LOGI("subscribe os account SA service status success"); -} - -OsAccountIdSubscriber::OsAccountIdSubscriber(const OsAccountSubscribeInfo &subscribeInfo) - : OsAccountSubscriber(subscribeInfo), - threadHandler_(ThreadHandler::GetSingleThreadInstance()) -{} - -void OsAccountIdSubscriber::Subscribe() -{ - IAM_LOGI("start"); - auto instance = GetInstance(); - IF_FALSE_LOGE_AND_RETURN(instance != NULL); - - ErrCode errCode = AccountSA::OsAccountManager::SubscribeOsAccount(instance); - if (errCode != ERR_OK) { - IAM_LOGE("subscribe fail, errCode = %{public}d", errCode); - return; - } - - int32_t userId = GetCurrentUserId(); - if (userId == INVALID_USER_ID) { - IAM_LOGE("GetCurrentUserId fail"); - return; - } - TemplateCacheManager::GetInstance().ProcessUserIdChange(userId); - IAM_LOGI("subscribe success"); -} - -void OsAccountIdSubscriber::Unsubscribe() -{ - auto instance = GetInstance(); - IF_FALSE_LOGE_AND_RETURN(instance != NULL); - - ErrCode errCode = AccountSA::OsAccountManager::UnsubscribeOsAccount(instance); - if (errCode != ERR_OK) { - IAM_LOGE("unsubscribe fail, errCode = %{public}d", errCode); - return; - } - IAM_LOGI("unsubscribe success"); -} - -void OsAccountIdSubscriber::OnAccountsChanged(const int& id) -{ - IAM_LOGI("OnAccountsChanged %{public}d", id); - if (threadHandler_ == nullptr) { - IAM_LOGE("threadHandler_ not set"); - return; - } - - threadHandler_->PostTask([id]() { - IAM_LOGI("task process begin"); - TemplateCacheManager::GetInstance().ProcessUserIdChange(id); - IAM_LOGI("task process end"); - }); -} - -std::shared_ptr OsAccountIdSubscriber::GetInstance() -{ - OsAccountSubscribeInfo subscribeInfo; - subscribeInfo.SetOsAccountSubscribeType(OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVATED); - - static auto subscriber = Common::MakeShared(subscribeInfo); - if (subscriber == nullptr) { - IAM_LOGE("OsAccountIdSubscriber is null"); - } - return subscriber; -} - TemplateCacheManager::TemplateCacheManager() { - ServiceStatusListener::Subscribe(); + IAM_LOGI("init"); } TemplateCacheManager &TemplateCacheManager::GetInstance() diff --git a/test/fuzztest/common_fuzzer/BUILD.gn b/test/fuzztest/common_fuzzer/BUILD.gn index 6e6e0ad2e..f3150e061 100644 --- a/test/fuzztest/common_fuzzer/BUILD.gn +++ b/test/fuzztest/common_fuzzer/BUILD.gn @@ -135,10 +135,12 @@ ohos_source_set("userauth_service_core_fuzzer") { "../../../services/core/src/resource_node_impl.cpp", "../../../services/core/src/resource_node_pool_impl.cpp", "../../../services/core/src/resource_node_utils.cpp", + "../../../services/core/src/risk_event_manager.cpp", "../../../services/core/src/schedule_node_builder.cpp", "../../../services/core/src/schedule_node_helper.cpp", "../../../services/core/src/schedule_node_impl.cpp", "../../../services/core/src/schedule_resource_node_listener.cpp", + "../../../services/core/src/screenlock_status_listener.cpp", "../../../services/core/src/secure_user_info_impl.cpp", "../../../services/core/src/update_pin_param_impl.cpp", "../../../services/core/src/user_idm_database_impl.cpp", @@ -178,9 +180,34 @@ ohos_source_set("userauth_service_core_fuzzer") { "samgr:samgr_proxy", ] + defines = [] + if (screenlock_client_enable) { + external_deps += [ + "eventhandler:libeventhandler", + "ffrt:libffrt", + "preferences:native_preferences", + "screenlock_mgr:screenlock_client", + "window_manager:libdm_lite", + ] + sources += [ + "../../../services/core/src/strong_auth_status_manager_impl.cpp", + ] + } else { + sources += [ + "../../../services/core/src/strong_auth_status_manager_mock.cpp", + ] + } + if (has_os_account_part) { cflags_cc = [ "-DHAS_OS_ACCOUNT_PART" ] external_deps += [ "os_account:os_account_innerkits" ] + sources += [ + "../../../services/core/src/os_accounts_manager_impl.cpp", + ] + } else { + sources += [ + "../../../services/core/src/os_accounts_manager_mock.cpp", + ] } public_configs = [ "../../../services/core:userauth_service_core_config" ] diff --git a/test/fuzztest/services/servicecore_fuzzer/BUILD.gn b/test/fuzztest/services/servicecore_fuzzer/BUILD.gn index ebe462eb4..b01534493 100644 --- a/test/fuzztest/services/servicecore_fuzzer/BUILD.gn +++ b/test/fuzztest/services/servicecore_fuzzer/BUILD.gn @@ -24,6 +24,7 @@ ohos_fuzztest("ServiceCoreFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-DIAM_TEST_ENABLE", "-Dprivate=public", "-Dprotected=public", ] @@ -35,6 +36,7 @@ ohos_fuzztest("ServiceCoreFuzzTest") { "../../../../services/base/inc", "../../../../services/core/inc", "../../../../services/core/src", + "../../../../services/context/inc", "../../../../common/utils", "../../../../common/logs", ] @@ -42,6 +44,7 @@ ohos_fuzztest("ServiceCoreFuzzTest") { sources = [ "src/resource_node_fuzzer.cpp", "src/resource_node_pool_fuzzer.cpp", + "src/risk_event_manager_fuzzer.cpp", "src/schedule_node_fuzzer.cpp", "src/service_core_fuzzer.cpp", ] @@ -56,10 +59,14 @@ ohos_fuzztest("ServiceCoreFuzzTest") { remove_configs = [ "//build/config/compiler:no_exceptions" ] external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", "c_utils:utils", "hdf_core:libhdi", "hilog:libhilog", "ipc:ipc_core", + "samgr:samgr_proxy", ] subsystem_name = "useriam" diff --git a/test/fuzztest/services/servicecore_fuzzer/inc/risk_event_manager_fuzzer.h b/test/fuzztest/services/servicecore_fuzzer/inc/risk_event_manager_fuzzer.h new file mode 100644 index 000000000..8b6b28178 --- /dev/null +++ b/test/fuzztest/services/servicecore_fuzzer/inc/risk_event_manager_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 RISK_EVENT_MANAGER_FUZZ_TEST_H +#define RISK_EVENT_MANAGER_FUZZ_TEST_H + +#include "parcel.h" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +void RiskEventManagerFuzzTest(Parcel &parcel); +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // RISK_EVENT_MANAGER_FUZZ_TEST_H diff --git a/test/fuzztest/services/servicecore_fuzzer/src/risk_event_manager_fuzzer.cpp b/test/fuzztest/services/servicecore_fuzzer/src/risk_event_manager_fuzzer.cpp new file mode 100644 index 000000000..d40bbb2bf --- /dev/null +++ b/test/fuzztest/services/servicecore_fuzzer/src/risk_event_manager_fuzzer.cpp @@ -0,0 +1,154 @@ +/* + * 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 "risk_event_manager_fuzzer.h" + +#include "os_accounts_manager.h" +#include "iam_fuzz_test.h" +#include "iam_logger.h" +#include "iam_ptr.h" +#include "risk_event_manager.h" +#include "screenlock_status_listener.h" +#include "strong_auth_status_manager.h" + +#define LOG_TAG "USER_AUTH_SA" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +namespace { +void FuzzRiskEventManagerMain(Parcel &parcel) +{ + IAM_LOGI("begin"); + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + Attributes attributes; + std::vector extraInfo; + RiskEventManager::GetInstance().SetRiskEventPropertyForAuthType(mainUserId, + AuthType::FACE, RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH); + RiskEventManager::GetInstance().SetRiskEventPropertyForAuthType(inValidUserId, + AuthType::FACE, RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH); + RiskEventManager::GetInstance().SetRiskEventPropertyForAuthType(mainUserId, + AuthType::PIN, RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH); + RiskEventManager::GetInstance().SetAttributes(mainUserId, AuthType::FACE, + RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH, attributes); + RiskEventManager::GetInstance().SetAttributes(inValidUserId, AuthType::FACE, + RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH, attributes); + RiskEventManager::GetInstance().SetAttributes(mainUserId, AuthType::FACE, + RiskEventManager::EventType::UNKNOWN, attributes); + RiskEventManager::GetInstance().GetStrongAuthExtraInfo(mainUserId, + AuthType::FACE, extraInfo); + IAM_LOGI("end"); +} + +void FuzzGetTemplateIdList(Parcel &parcel) +{ + IAM_LOGI("begin"); + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + std::vector templateIds; + RiskEventManager::GetInstance().GetTemplateIdList(mainUserId, AuthType::FACE, + templateIds); + RiskEventManager::GetInstance().GetTemplateIdList(inValidUserId, AuthType::FACE, + templateIds); + RiskEventManager::GetInstance().GetTemplateIdList(mainUserId, AuthType::PIN, + templateIds); + RiskEventManager::GetInstance().GetTemplateIdList(inValidUserId, AuthType::PIN, + templateIds); + IAM_LOGI("end"); +} + +void FuzzHandleStrongAuthEvent(Parcel &parcel) +{ + IAM_LOGI("begin"); + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + std::vector userIdList; + RiskEventManager::GetInstance().HandleStrongAuthEvent(mainUserId); + RiskEventManager::GetInstance().HandleStrongAuthEvent(inValidUserId); + RiskEventManager::GetInstance().SyncRiskEvents(); + RiskEventManager::GetInstance().OnScreenLock(); + IAM_LOGI("end"); +} + +void FuzzScreenlockStatusListener(Parcel &parcel) +{ + IAM_LOGI("begin"); + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED); + + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + auto subscriber = std::make_shared(subscribeInfo); + EventFwk::Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED); + EventFwk::CommonEventData data(want); + subscriber->OnReceiveEvent(data); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED); + EventFwk::CommonEventData data1(want); + subscriber->OnReceiveEvent(data1); + IAM_LOGI("end"); +} + +void FuzzStrongAuthStatusManager(Parcel &parcel) +{ + IAM_LOGI("begin"); + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + StrongAuthStatusManager::Instance().RegisterStrongAuthListener(); + StrongAuthStatusManager::Instance().RegisterStrongAuthListener(); + StrongAuthStatusManager::Instance().SyncStrongAuthStatusForAllAccounts(); + StrongAuthStatusManager::Instance().UnRegisterStrongAuthListener(); + StrongAuthStatusManager::Instance().UnRegisterStrongAuthListener(); + StrongAuthStatusManager::Instance().StartSubscribe(); + StrongAuthStatusManager::Instance().StartSubscribe(); + StrongAuthStatusManager::Instance().IsScreenLockStrongAuth(mainUserId); + StrongAuthStatusManager::Instance().IsScreenLockStrongAuth(inValidUserId); + IAM_LOGI("end"); +} + +void FuzzOsAccountsManager(Parcel &parcel) +{ + IAM_LOGI("begin"); + OsAccountsManager::Instance().StartSubscribe(); + OsAccountsManager::Instance().StartSubscribe(); + OsAccountsManager::Instance().OnOsAccountSaAdd(); + OsAccountsManager::Instance().OnOsAccountSaAdd(); + OsAccountsManager::Instance().OnOsAccountSaRemove(); + OsAccountsManager::Instance().OnOsAccountSaRemove(); + IAM_LOGI("end"); +} + +using RiskEventManagerFuzzFunc = decltype(FuzzRiskEventManagerMain); +RiskEventManagerFuzzFunc *g_RiskEventManagerFuzzFuncs[] = { + FuzzRiskEventManagerMain, + FuzzGetTemplateIdList, + FuzzHandleStrongAuthEvent, + FuzzScreenlockStatusListener, + FuzzStrongAuthStatusManager, + FuzzOsAccountsManager, +}; +} // namespace + +void RiskEventManagerFuzzTest(Parcel &parcel) +{ + uint32_t index = parcel.ReadUint32() % (sizeof(g_RiskEventManagerFuzzFuncs) / sizeof(RiskEventManagerFuzzFunc *)); + auto fuzzFunc = g_RiskEventManagerFuzzFuncs[index]; + fuzzFunc(parcel); + return; +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS diff --git a/test/fuzztest/services/servicecore_fuzzer/src/service_core_fuzzer.cpp b/test/fuzztest/services/servicecore_fuzzer/src/service_core_fuzzer.cpp index 94a9cecb9..c5f154390 100644 --- a/test/fuzztest/services/servicecore_fuzzer/src/service_core_fuzzer.cpp +++ b/test/fuzztest/services/servicecore_fuzzer/src/service_core_fuzzer.cpp @@ -17,6 +17,7 @@ #include "resource_node_fuzzer.h" #include "resource_node_pool_fuzzer.h" +#include "risk_event_manager_fuzzer.h" #include "schedule_node_fuzzer.h" namespace { @@ -25,6 +26,7 @@ FuzzEntryFunc *g_FuzzFuncList[] = { OHOS::UserIam::UserAuth::ScheduleNodeFuzzTest, OHOS::UserIam::UserAuth::ResourceNodePoolFuzzTest, OHOS::UserIam::UserAuth::ResourceNodeFuzzTest, + OHOS::UserIam::UserAuth::RiskEventManagerFuzzTest, }; } // namespace diff --git a/test/unittest/services/BUILD.gn b/test/unittest/services/BUILD.gn index f77114ce9..8c58c8805 100644 --- a/test/unittest/services/BUILD.gn +++ b/test/unittest/services/BUILD.gn @@ -15,6 +15,13 @@ import("//build/ohos.gni") import("//build/test.gni") import("../../../user_auth_framework.gni") +if (!defined(global_parts_info) || + defined(global_parts_info.account_os_account)) { + has_os_account_part = true +} else { + has_os_account_part = false +} + ohos_unittest("iam_services_test") { sanitize = { integer_overflow = true @@ -95,10 +102,12 @@ ohos_unittest("iam_services_test") { "../../../services/core/src/resource_node_impl.cpp", "../../../services/core/src/resource_node_pool_impl.cpp", "../../../services/core/src/resource_node_utils.cpp", + "../../../services/core/src/risk_event_manager.cpp", "../../../services/core/src/schedule_node_builder.cpp", "../../../services/core/src/schedule_node_helper.cpp", "../../../services/core/src/schedule_node_impl.cpp", "../../../services/core/src/schedule_resource_node_listener.cpp", + "../../../services/core/src/screenlock_status_listener.cpp", "../../../services/core/src/secure_user_info_impl.cpp", "../../../services/core/src/system_param_manager.cpp", "../../../services/core/src/update_pin_param_impl.cpp", @@ -148,14 +157,17 @@ ohos_unittest("iam_services_test") { "src/identification_impl_test.cpp", "src/identify_context_test.cpp", "src/ipc_common_test.cpp", + "src/os_accounts_manager_test.cpp", "src/relative_timer_test.cpp", "src/remote_auth_context_test.cpp", "src/remote_auth_invoker_context_test.cpp", "src/resource_node_pool_test.cpp", "src/resource_node_test.cpp", "src/resource_node_utils_test.cpp", + "src/risk_event_manager_test.cpp", "src/schedule_node_helper_test.cpp", "src/schedule_node_test.cpp", + "src/screenlock_status_listener_test.cpp", "src/secure_user_info_test.cpp", "src/simple_auth_context_test.cpp", "src/soft_bus_base_socket_test.cpp", @@ -163,6 +175,7 @@ ohos_unittest("iam_services_test") { "src/soft_bus_manager_test.cpp", "src/soft_bus_server_socket_test.cpp", "src/state_machine_test.cpp", + "src/strong_auth_status_manager_test.cpp", "src/system_ability_listener_test.cpp", "src/system_param_manager_test.cpp", "src/template_cache_manager_test.cpp", @@ -223,8 +236,30 @@ ohos_unittest("iam_services_test") { defines = [] if (screenlock_client_enable) { - external_deps += [ "screenlock_mgr:screenlock_client" ] - defines += [ "SCREENLOCK_CLIENT_ENABLE" ] + external_deps += [ + "eventhandler:libeventhandler", + "ffrt:libffrt", + "preferences:native_preferences", + "screenlock_mgr:screenlock_client" + ] + sources += [ + "../../../services/core/src/strong_auth_status_manager_impl.cpp", + ] + } else { + sources += [ + "../../../services/core/src/strong_auth_status_manager_mock.cpp", + ] + } + + if (has_os_account_part) { + cflags_cc = [ "-DHAS_OS_ACCOUNT_PART" ] + sources += [ + "../../../services/core/src/os_accounts_manager_impl.cpp", + ] + } else { + sources += [ + "../../../services/core/src/os_accounts_manager_mock.cpp", + ] } configs = [ diff --git a/test/unittest/services/inc/os_accounts_manager_test.h b/test/unittest/services/inc/os_accounts_manager_test.h new file mode 100644 index 000000000..3a57c7746 --- /dev/null +++ b/test/unittest/services/inc/os_accounts_manager_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OS_ACCOUNTS_MANAGER_TEST_H +#define OS_ACCOUNTS_MANAGER_TEST_H + +#include +#include + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class OsAccountsManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // OS_ACCOUNTS_MANAGER_TEST_H \ No newline at end of file diff --git a/test/unittest/services/inc/risk_event_manager_test.h b/test/unittest/services/inc/risk_event_manager_test.h new file mode 100644 index 000000000..79c5b600c --- /dev/null +++ b/test/unittest/services/inc/risk_event_manager_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef RISK_EVENT_MANAGER_TEST_H +#define RISK_EVENT_MANAGER_TEST_H + +#include +#include + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class RiskEventManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // RISK_EVENT_MANAGER_TEST_H \ No newline at end of file diff --git a/test/unittest/services/inc/screenlock_status_listener_test.h b/test/unittest/services/inc/screenlock_status_listener_test.h new file mode 100644 index 000000000..72b29dae3 --- /dev/null +++ b/test/unittest/services/inc/screenlock_status_listener_test.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef SCREENLOCK_STATUS_LISTENER_TEST +#define SCREENLOCK_STATUS_LISTENER_TEST + +#include + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class ScreenlockStatusListenerTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // SCREENLOCK_STATUS_LISTENER_TEST \ No newline at end of file diff --git a/test/unittest/services/inc/strong_auth_status_manager_test.h b/test/unittest/services/inc/strong_auth_status_manager_test.h new file mode 100644 index 000000000..7ef08575c --- /dev/null +++ b/test/unittest/services/inc/strong_auth_status_manager_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef STRONG_AUTH_STATUS_MANAGER_TEST_H +#define STRONG_AUTH_STATUS_MANAGER_TEST_H + +#include +#include + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +class StrongAuthStatusManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS +#endif // STRONG_AUTH_STATUS_MANAGER_TEST_H \ No newline at end of file diff --git a/test/unittest/services/src/context_pool_test.cpp b/test/unittest/services/src/context_pool_test.cpp index ae230fa46..979a1713b 100644 --- a/test/unittest/services/src/context_pool_test.cpp +++ b/test/unittest/services/src/context_pool_test.cpp @@ -265,6 +265,12 @@ HWTEST_F(ContextPoolTest, ContextPoolTestGetNewContextId, TestSize.Level0) EXPECT_TRUE(ContextPool::Instance().Delete(contextId)); } } + +HWTEST_F(ContextPoolTest, StartSubscribeOsAccountSaStatusTest, TestSize.Level0) +{ + EXPECT_NO_THROW(ContextPool::Instance().StartSubscribeOsAccountSaStatus()); + EXPECT_NO_THROW(ContextPool::Instance().StartSubscribeOsAccountSaStatus()); +} } // namespace UserAuth } // namespace UserIam } // namespace OHOS diff --git a/test/unittest/services/src/os_accounts_manager_test.cpp b/test/unittest/services/src/os_accounts_manager_test.cpp new file mode 100644 index 000000000..7d199ddea --- /dev/null +++ b/test/unittest/services/src/os_accounts_manager_test.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "os_accounts_manager_test.h" + +#include "os_accounts_manager.h" + +#include "iam_logger.h" +#include "securec.h" + +#define LOG_TAG "USER_AUTH_SA" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +using namespace testing; +using namespace testing::ext; + +void OsAccountsManagerTest::SetUpTestCase() +{ +} + +void OsAccountsManagerTest::TearDownTestCase() +{ +} + +void OsAccountsManagerTest::SetUp() +{ +} + +void OsAccountsManagerTest::TearDown() +{ +} + +HWTEST_F(OsAccountsManagerTest, OnOsAccountSaAddRemoveTest, TestSize.Level0) +{ + EXPECT_NO_THROW(OsAccountsManager::Instance().OnOsAccountSaAdd()); + EXPECT_NO_THROW(OsAccountsManager::Instance().OnOsAccountSaAdd()); + EXPECT_NO_THROW(OsAccountsManager::Instance().OnOsAccountSaRemove()); + EXPECT_NO_THROW(OsAccountsManager::Instance().OnOsAccountSaRemove()); +} + +HWTEST_F(OsAccountsManagerTest, StartSubscribeTest, TestSize.Level0) +{ + EXPECT_NO_THROW(OsAccountsManager::Instance().StartSubscribe()); + EXPECT_NO_THROW(OsAccountsManager::Instance().StartSubscribe()); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/services/src/resource_node_pool_test.cpp b/test/unittest/services/src/resource_node_pool_test.cpp index c76c327d3..5f951a0ae 100644 --- a/test/unittest/services/src/resource_node_pool_test.cpp +++ b/test/unittest/services/src/resource_node_pool_test.cpp @@ -243,6 +243,30 @@ HWTEST_F(ResourceNodePoolTest, ResourceNodePoolTestEnumerate, TestSize.Level0) pool.DeleteAll(); } + +HWTEST_F(ResourceNodePoolTest, GetResourceNodeByTypeAndRole, TestSize.Level0) +{ + auto &pool = ResourceNodePool::Instance(); + std::vector> pinNodes; + std::vector> faceNodes; + std::vector> fingerPrintNodes; + + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::PIN, ALL_IN_ONE, faceNodes)); + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::FACE, ALL_IN_ONE, faceNodes)); + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::FINGERPRINT, ALL_IN_ONE, fingerPrintNodes)); + + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::PIN, SCHEDULER, faceNodes)); + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::FACE, SCHEDULER, faceNodes)); + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::FINGERPRINT, SCHEDULER, fingerPrintNodes)); + + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::PIN, COLLECTOR, faceNodes)); + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::FACE, COLLECTOR, faceNodes)); + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::FINGERPRINT, COLLECTOR, fingerPrintNodes)); + + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::PIN, VERIFIER, faceNodes)); + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::FACE, VERIFIER, faceNodes)); + EXPECT_NO_THROW(pool.GetResourceNodeByTypeAndRole(AuthType::FINGERPRINT, VERIFIER, fingerPrintNodes)); +} } // namespace UserAuth } // namespace UserIam } // namespace OHOS diff --git a/test/unittest/services/src/risk_event_manager_test.cpp b/test/unittest/services/src/risk_event_manager_test.cpp new file mode 100644 index 000000000..a060a5233 --- /dev/null +++ b/test/unittest/services/src/risk_event_manager_test.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "risk_event_manager_test.h" + +#include "risk_event_manager.h" + +#include "iam_logger.h" +#include "securec.h" + +#define LOG_TAG "USER_AUTH_SA" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +using namespace testing; +using namespace testing::ext; + +void RiskEventManagerTest::SetUpTestCase() +{ +} + +void RiskEventManagerTest::TearDownTestCase() +{ +} + +void RiskEventManagerTest::SetUp() +{ +} + +void RiskEventManagerTest::TearDown() +{ +} + +HWTEST_F(RiskEventManagerTest, SetRiskEventPropertyForAuthTypeTest, TestSize.Level0) +{ + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + EXPECT_NO_THROW(RiskEventManager::GetInstance().SetRiskEventPropertyForAuthType(mainUserId, + AuthType::FACE, RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().SetRiskEventPropertyForAuthType(inValidUserId, + AuthType::FACE, RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().SetRiskEventPropertyForAuthType(mainUserId, + AuthType::PIN, RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH)); +} + +HWTEST_F(RiskEventManagerTest, GetAttributesTest, TestSize.Level0) +{ + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + Attributes attributes; + EXPECT_NO_THROW(RiskEventManager::GetInstance().SetAttributes(mainUserId, AuthType::FACE, + RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH, attributes)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().SetAttributes(inValidUserId, AuthType::FACE, + RiskEventManager::EventType::SCREENLOCK_STRONG_AUTH, attributes)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().SetAttributes(mainUserId, AuthType::FACE, + RiskEventManager::EventType::UNKNOWN, attributes)); +} + +HWTEST_F(RiskEventManagerTest, GetTemplateIdListTest, TestSize.Level0) +{ + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + std::vector templateIds; + EXPECT_NO_THROW(RiskEventManager::GetInstance().GetTemplateIdList(mainUserId, AuthType::FACE, + templateIds)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().GetTemplateIdList(inValidUserId, AuthType::FACE, + templateIds)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().GetTemplateIdList(mainUserId, AuthType::PIN, + templateIds)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().GetTemplateIdList(inValidUserId, AuthType::PIN, + templateIds)); +} + +HWTEST_F(RiskEventManagerTest, GetStrongAuthExtraInfoTest, TestSize.Level0) +{ + std::vector extraInfo; + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + EXPECT_NO_THROW(RiskEventManager::GetInstance().GetStrongAuthExtraInfo(mainUserId, + AuthType::FACE, extraInfo)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().GetStrongAuthExtraInfo(inValidUserId, + AuthType::FACE, extraInfo)); +} + +HWTEST_F(RiskEventManagerTest, HandleStrongAuthEventTest, TestSize.Level0) +{ + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + EXPECT_NO_THROW(RiskEventManager::GetInstance().HandleStrongAuthEvent(mainUserId)); + EXPECT_NO_THROW(RiskEventManager::GetInstance().HandleStrongAuthEvent(inValidUserId)); +} + +HWTEST_F(RiskEventManagerTest, SyncRiskEventsTest, TestSize.Level0) +{ + auto instance = RiskEventManager::GetInstance(); + EXPECT_NO_THROW(instance.SyncRiskEvents()); + EXPECT_NO_THROW(instance.OnScreenLock()); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/services/src/screenlock_status_listener_test.cpp b/test/unittest/services/src/screenlock_status_listener_test.cpp new file mode 100644 index 000000000..8f91aaa94 --- /dev/null +++ b/test/unittest/services/src/screenlock_status_listener_test.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "screenlock_status_listener_test.h" + +#include "screenlock_status_listener.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +using namespace testing; +using namespace testing::ext; + +void ScreenlockStatusListenerTest::SetUpTestCase() +{ +} + +void ScreenlockStatusListenerTest::TearDownTestCase() +{ +} + +void ScreenlockStatusListenerTest::SetUp() +{ +} + +void ScreenlockStatusListenerTest::TearDown() +{ +} + +HWTEST_F(ScreenlockStatusListenerTest, RegisterCommonEventListenerTest, TestSize.Level0) +{ + ResultCode result = ScreenlockStatusListenerManager::GetInstance().RegisterCommonEventListener(); + EXPECT_EQ(result, SUCCESS); + result = ScreenlockStatusListenerManager::GetInstance().RegisterCommonEventListener(); + EXPECT_NO_THROW(ScreenlockStatusListenerManager::GetInstance().RegisterScreenLockedCallback()); + EXPECT_NO_THROW(ScreenlockStatusListenerManager::GetInstance().RegisterScreenLockedCallback()); + EXPECT_NO_THROW(ScreenlockStatusListenerManager::GetInstance().UnRegisterScreenLockedCallback()); + EXPECT_NO_THROW(ScreenlockStatusListenerManager::GetInstance().UnRegisterScreenLockedCallback()); +} + +HWTEST_F(ScreenlockStatusListenerTest, SyncScreenlockStatusTest, TestSize.Level0) +{ + EXPECT_NO_THROW(ScreenlockStatusListenerManager::GetInstance().SyncScreenlockStatus()); +} + +HWTEST_F(ScreenlockStatusListenerTest, ScreenlockStatusListenerTestOnReceiveEvent, TestSize.Level0) +{ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED); + + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + auto subscriber = std::make_shared(subscribeInfo); + EventFwk::Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED); + EventFwk::CommonEventData data(want); + EXPECT_NO_THROW(subscriber->OnReceiveEvent(data)); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED); + EventFwk::CommonEventData data1(want); + EXPECT_NO_THROW(subscriber->OnReceiveEvent(data1)); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/services/src/strong_auth_status_manager_test.cpp b/test/unittest/services/src/strong_auth_status_manager_test.cpp new file mode 100644 index 000000000..2ba8dae02 --- /dev/null +++ b/test/unittest/services/src/strong_auth_status_manager_test.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "strong_auth_status_manager_test.h" + +#include "strong_auth_status_manager.h" + +#include "iam_logger.h" +#include "securec.h" + +#define LOG_TAG "USER_AUTH_SA" + +namespace OHOS { +namespace UserIam { +namespace UserAuth { +using namespace testing; +using namespace testing::ext; + +void StrongAuthStatusManagerTest::SetUpTestCase() +{ +} + +void StrongAuthStatusManagerTest::TearDownTestCase() +{ +} + +void StrongAuthStatusManagerTest::SetUp() +{ +} + +void StrongAuthStatusManagerTest::TearDown() +{ +} + +HWTEST_F(StrongAuthStatusManagerTest, RegisterStrongAuthListenerTest, TestSize.Level0) +{ + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().RegisterStrongAuthListener()); + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().RegisterStrongAuthListener()); + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().SyncStrongAuthStatusForAllAccounts()); + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().UnRegisterStrongAuthListener()); + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().UnRegisterStrongAuthListener()); +} + +HWTEST_F(StrongAuthStatusManagerTest, StartSubscribeTest, TestSize.Level0) +{ + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().StartSubscribe()); + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().StartSubscribe()); +} + +HWTEST_F(StrongAuthStatusManagerTest, IsScreenLockStrongAuthTest, TestSize.Level0) +{ + int32_t mainUserId = 100; + int32_t inValidUserId = -1; + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().IsScreenLockStrongAuth(mainUserId)); + EXPECT_NO_THROW(StrongAuthStatusManager::Instance().IsScreenLockStrongAuth(inValidUserId)); +} +} // namespace UserAuth +} // namespace UserIam +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/services/src/template_cache_manager_test.cpp b/test/unittest/services/src/template_cache_manager_test.cpp index a7166d17e..04a3ed5cc 100644 --- a/test/unittest/services/src/template_cache_manager_test.cpp +++ b/test/unittest/services/src/template_cache_manager_test.cpp @@ -43,34 +43,6 @@ void TemplateCacheManagerTest::TearDown() { } -using OsAccountSubscriber = AccountSA::OsAccountSubscriber; -using OsAccountSubscribeInfo = AccountSA::OsAccountSubscribeInfo; -using OS_ACCOUNT_SUBSCRIBE_TYPE = AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE; - -class ServiceStatusListener : public OHOS::SystemAbilityStatusChangeStub, public NoCopyable { -public: - static sptr GetInstance(); - static void Subscribe(); - - void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; - void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; - -private: - ServiceStatusListener() {}; - ~ServiceStatusListener() override {}; -}; - -class OsAccountIdSubscriber : public OsAccountSubscriber, public NoCopyable { -public: - explicit OsAccountIdSubscriber(const OsAccountSubscribeInfo &subscribeInfo); - ~OsAccountIdSubscriber() = default; - - static std::shared_ptr GetInstance(); - static void Subscribe(); - static void Unsubscribe(); - void OnAccountsChanged(const int& id) override; -}; - HWTEST_F(TemplateCacheManagerTest, TemplateCacheManagerTest_001, TestSize.Level1) { EXPECT_NO_THROW({ @@ -80,48 +52,6 @@ HWTEST_F(TemplateCacheManagerTest, TemplateCacheManagerTest_001, TestSize.Level1 TemplateCacheManager::GetInstance().UpdateTemplateCache(PIN); }); } - -HWTEST_F(TemplateCacheManagerTest, TemplateCacheManagerTestOnAddSystemAbility, TestSize.Level1) -{ - int32_t systemAbilityId = 1; - const std::string deviceId = "123"; - EXPECT_NO_THROW({ - ServiceStatusListener::GetInstance()->OnAddSystemAbility(systemAbilityId, deviceId); - }); -} - -HWTEST_F(TemplateCacheManagerTest, TemplateCacheManagerTestOnRemoveSystemAbility_001, TestSize.Level1) -{ - int32_t systemAbilityId = 1; - const std::string deviceId = "123"; - EXPECT_NO_THROW({ - ServiceStatusListener::GetInstance()->OnRemoveSystemAbility(systemAbilityId, deviceId); - }); -} - -HWTEST_F(TemplateCacheManagerTest, TemplateCacheManagerTestOnRemoveSystemAbility_002, TestSize.Level1) -{ - int32_t systemAbilityId = 200; - const std::string deviceId = "123"; - EXPECT_NO_THROW({ - ServiceStatusListener::GetInstance()->OnAddSystemAbility(systemAbilityId, deviceId); - }); -} - -HWTEST_F(TemplateCacheManagerTest, TemplateCacheManagerTestUnsubscribe, TestSize.Level1) -{ - EXPECT_NO_THROW({ - OsAccountIdSubscriber::GetInstance()->Unsubscribe(); - }); -} - -HWTEST_F(TemplateCacheManagerTest, TemplateCacheManagerTestOnAccountsChanged, TestSize.Level1) -{ - const int id = 1; - EXPECT_NO_THROW({ - OsAccountIdSubscriber::GetInstance()->OnAccountsChanged(id); - }); -} } // namespace UserAuth } // namespace UserIam } // namespace OHOS \ No newline at end of file -- Gitee From a141bcba4d9adf6f7222b4cfda8b20d16a813415 Mon Sep 17 00:00:00 2001 From: LHY6968 Date: Sat, 21 Jun 2025 19:40:32 +0800 Subject: [PATCH 2/3] first fork Signed-off-by: LHY6968 Change-Id: Ia27bf8d7f901abcce283a4bbb90a34704054a3df --- services/context/src/context_pool_impl.cpp | 4 ++-- .../core/src/os_accounts_manager_impl.cpp | 5 ++--- .../src/strong_auth_status_manager_impl.cpp | 8 ++++---- .../src/strong_auth_status_manager_mock.cpp | 3 ++- .../src/risk_event_manager_fuzzer.cpp | 4 ++-- test/unittest/services/BUILD.gn | 19 +------------------ 6 files changed, 13 insertions(+), 30 deletions(-) diff --git a/services/context/src/context_pool_impl.cpp b/services/context/src/context_pool_impl.cpp index b5e8343d4..e3a5eb84e 100644 --- a/services/context/src/context_pool_impl.cpp +++ b/services/context/src/context_pool_impl.cpp @@ -22,11 +22,11 @@ #include #include "system_ability_definition.h" -#include "system_ability_listener.h" +#include "iam_check.h" #include "iam_logger.h" #include "iam_para2str.h" -#include "iam_check.h" +#include "system_ability_listener.h" #define LOG_TAG "USER_AUTH_SA" diff --git a/services/core/src/os_accounts_manager_impl.cpp b/services/core/src/os_accounts_manager_impl.cpp index 38c03955f..c1799a17a 100644 --- a/services/core/src/os_accounts_manager_impl.cpp +++ b/services/core/src/os_accounts_manager_impl.cpp @@ -46,7 +46,6 @@ using OS_ACCOUNT_SUBSCRIBE_TYPE = AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE; void HandleAccountsChanged(const int &id) { auto threadHandler = ThreadHandler::GetSingleThreadInstance(); - if (threadHandler == nullptr) { IAM_LOGE("threadHandler is nullptr"); return; @@ -60,9 +59,9 @@ void HandleAccountsChanged(const int &id) void SyncOsAccountIdStatus() { IAM_LOGI("start"); - std::optional userIdOpt = INVALID_USER_ID; + std::optional userIdOpt; int32_t ret = IpcCommon::GetActiveUserId(userIdOpt); - if (ret != SUCCESS || userIdOpt.has_value()) { + if (ret != SUCCESS || !userIdOpt.has_value()) { IAM_LOGE("get current user id fail"); return; } diff --git a/services/core/src/strong_auth_status_manager_impl.cpp b/services/core/src/strong_auth_status_manager_impl.cpp index d1e396b69..a5a647da4 100644 --- a/services/core/src/strong_auth_status_manager_impl.cpp +++ b/services/core/src/strong_auth_status_manager_impl.cpp @@ -49,7 +49,8 @@ public: void OnStrongAuthChanged(int32_t userId, int32_t strongAuthStatus) override; }; -class StrongAuthStatusManagerImpl final : public StrongAuthStatusManager, public Singleton { +class StrongAuthStatusManagerImpl final + : public StrongAuthStatusManager, public Singleton { public: void RegisterStrongAuthListener() override; void UnRegisterStrongAuthListener() override; @@ -162,9 +163,8 @@ void StrongAuthStatusManagerImpl::StartSubscribe() } screenLockSaStatusListener_ = SystemAbilityListener::Subscribe( "ScreenLockService", SCREENLOCK_SERVICE_ID, - []() - { - StrongAuthStatusManager::Instance().RegisterStrongAuthListener(); + []() { + StrongAuthStatusManager::Instance().RegisterStrongAuthListener(); ScreenlockStatusListenerManager::GetInstance().RegisterCommonEventListener(); }, []() { StrongAuthStatusManager::Instance().UnRegisterStrongAuthListener(); }); diff --git a/services/core/src/strong_auth_status_manager_mock.cpp b/services/core/src/strong_auth_status_manager_mock.cpp index e357bc0d2..44b1dd76f 100644 --- a/services/core/src/strong_auth_status_manager_mock.cpp +++ b/services/core/src/strong_auth_status_manager_mock.cpp @@ -21,7 +21,8 @@ namespace OHOS { namespace UserIam { namespace UserAuth { -class StrongAuthStatusManagerImpl final : public StrongAuthStatusManager, public Singleton { +class StrongAuthStatusManagerImpl final + : public StrongAuthStatusManager, public Singleton { public: void RegisterStrongAuthListener() override; void UnRegisterStrongAuthListener() override; diff --git a/test/fuzztest/services/servicecore_fuzzer/src/risk_event_manager_fuzzer.cpp b/test/fuzztest/services/servicecore_fuzzer/src/risk_event_manager_fuzzer.cpp index d40bbb2bf..d090e5b12 100644 --- a/test/fuzztest/services/servicecore_fuzzer/src/risk_event_manager_fuzzer.cpp +++ b/test/fuzztest/services/servicecore_fuzzer/src/risk_event_manager_fuzzer.cpp @@ -49,7 +49,7 @@ void FuzzRiskEventManagerMain(Parcel &parcel) RiskEventManager::GetInstance().SetAttributes(mainUserId, AuthType::FACE, RiskEventManager::EventType::UNKNOWN, attributes); RiskEventManager::GetInstance().GetStrongAuthExtraInfo(mainUserId, - AuthType::FACE, extraInfo); + AuthType::FACE, extraInfo); IAM_LOGI("end"); } @@ -128,7 +128,7 @@ void FuzzOsAccountsManager(Parcel &parcel) OsAccountsManager::Instance().OnOsAccountSaAdd(); OsAccountsManager::Instance().OnOsAccountSaRemove(); OsAccountsManager::Instance().OnOsAccountSaRemove(); - IAM_LOGI("end"); + IAM_LOGI("end"); } using RiskEventManagerFuzzFunc = decltype(FuzzRiskEventManagerMain); diff --git a/test/unittest/services/BUILD.gn b/test/unittest/services/BUILD.gn index 8c58c8805..144f24f04 100644 --- a/test/unittest/services/BUILD.gn +++ b/test/unittest/services/BUILD.gn @@ -15,13 +15,6 @@ import("//build/ohos.gni") import("//build/test.gni") import("../../../user_auth_framework.gni") -if (!defined(global_parts_info) || - defined(global_parts_info.account_os_account)) { - has_os_account_part = true -} else { - has_os_account_part = false -} - ohos_unittest("iam_services_test") { sanitize = { integer_overflow = true @@ -96,6 +89,7 @@ ohos_unittest("iam_services_test") { "../../../services/core/src/enrollment_impl.cpp", "../../../services/core/src/event_listener_manager.cpp", "../../../services/core/src/identification_impl.cpp", + "../../../services/core/src/os_accounts_manager_impl.cpp", "../../../services/core/src/publish_event_adapter_mock.cpp", "../../../services/core/src/remote_executor_proxy.cpp", "../../../services/core/src/remote_msg_util.cpp", @@ -251,17 +245,6 @@ ohos_unittest("iam_services_test") { ] } - if (has_os_account_part) { - cflags_cc = [ "-DHAS_OS_ACCOUNT_PART" ] - sources += [ - "../../../services/core/src/os_accounts_manager_impl.cpp", - ] - } else { - sources += [ - "../../../services/core/src/os_accounts_manager_mock.cpp", - ] - } - configs = [ "../../../common:iam_log_config", "../../../common:iam_utils_config", -- Gitee From f209965a89d5a589a7b1fde50331835fe850d128 Mon Sep 17 00:00:00 2001 From: LHY6968 Date: Tue, 24 Jun 2025 16:22:59 +0800 Subject: [PATCH 3/3] --amend Signed-off-by: LHY6968 Change-Id: Idfeab7474933d39f60c69df8456d1a1daedfdd50 --- .../core/src/os_accounts_manager_impl.cpp | 2 +- .../core/src/screenlock_status_listener.cpp | 13 +------- .../src/strong_auth_status_manager_impl.cpp | 33 +++++-------------- 3 files changed, 11 insertions(+), 37 deletions(-) diff --git a/services/core/src/os_accounts_manager_impl.cpp b/services/core/src/os_accounts_manager_impl.cpp index c1799a17a..f86247d06 100644 --- a/services/core/src/os_accounts_manager_impl.cpp +++ b/services/core/src/os_accounts_manager_impl.cpp @@ -43,7 +43,7 @@ namespace { using OsAccountSubscriber = AccountSA::OsAccountSubscriber; using OsAccountSubscribeInfo = AccountSA::OsAccountSubscribeInfo; using OS_ACCOUNT_SUBSCRIBE_TYPE = AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE; -void HandleAccountsChanged(const int &id) +void HandleAccountsChanged(const int id) { auto threadHandler = ThreadHandler::GetSingleThreadInstance(); if (threadHandler == nullptr) { diff --git a/services/core/src/screenlock_status_listener.cpp b/services/core/src/screenlock_status_listener.cpp index 628697244..2a77550c0 100644 --- a/services/core/src/screenlock_status_listener.cpp +++ b/services/core/src/screenlock_status_listener.cpp @@ -41,19 +41,14 @@ ResultCode ScreenlockStatusListenerManager::RegisterCommonEventListener() IAM_LOGI("start"); std::lock_guard lock(mutex_); if (commonEventSaStatusListener_ != nullptr) { - IAM_LOGI("commonEventSaStatusListener_ is not nullptr"); return SUCCESS; } commonEventSaStatusListener_ = SystemAbilityListener::Subscribe( "common_event_service", COMMON_EVENT_SERVICE_ID, []() { ScreenlockStatusListenerManager::GetInstance().RegisterScreenLockedCallback(); }, []() { ScreenlockStatusListenerManager::GetInstance().UnRegisterScreenLockedCallback(); }); - if (commonEventSaStatusListener_ == nullptr) { - IAM_LOGE("commonEventSaStatusListener_ is nullptr"); - return GENERAL_ERROR; - } + IF_FALSE_LOGE_AND_RETURN_VAL(commonEventSaStatusListener_ != nullptr, GENERAL_ERROR); - IAM_LOGI("success"); return SUCCESS; } @@ -62,7 +57,6 @@ void ScreenlockStatusListenerManager::RegisterScreenLockedCallback() IAM_LOGI("start"); std::lock_guard lock(mutex_); if (subscriber_ != nullptr) { - IAM_LOGI("ScreenlockStatusListener already subscribed"); return; } EventFwk::MatchingSkills matchingSkills; @@ -76,7 +70,6 @@ void ScreenlockStatusListenerManager::RegisterScreenLockedCallback() } subscriber_ = subscriber; SyncScreenlockStatus(); - IAM_LOGI("success"); } void ScreenlockStatusListenerManager::UnRegisterScreenLockedCallback() @@ -84,7 +77,6 @@ void ScreenlockStatusListenerManager::UnRegisterScreenLockedCallback() IAM_LOGI("start"); std::lock_guard lock(mutex_); if (subscriber_ == nullptr) { - IAM_LOGI("ScreenlockStatusListener already unsubscribed"); return; } @@ -92,7 +84,6 @@ void ScreenlockStatusListenerManager::UnRegisterScreenLockedCallback() IAM_LOGE("UnSubscribeCommonEvent failed"); } subscriber_ = nullptr; - IAM_LOGI("success"); } void ScreenlockStatusListenerManager::SyncScreenlockStatus() @@ -104,7 +95,6 @@ void ScreenlockStatusListenerManager::SyncScreenlockStatus() return; } RiskEventManager::GetInstance().OnScreenLock(); - IAM_LOGI("success"); } void ScreenlockStatusListener::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) @@ -117,7 +107,6 @@ void ScreenlockStatusListener::OnReceiveEvent(const OHOS::EventFwk::CommonEventD return; } if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { - IAM_LOGI("receive screen locked event"); RiskEventManager::GetInstance().OnScreenLock(); }; } diff --git a/services/core/src/strong_auth_status_manager_impl.cpp b/services/core/src/strong_auth_status_manager_impl.cpp index a5a647da4..e398bd38c 100644 --- a/services/core/src/strong_auth_status_manager_impl.cpp +++ b/services/core/src/strong_auth_status_manager_impl.cpp @@ -96,20 +96,16 @@ void StrongAuthStatusManagerImpl::RegisterStrongAuthListener() IAM_LOGI("start"); std::lock_guard lock(mutex_); if (strongAuthListener_ != nullptr) { - IAM_LOGI("strongAuthListener_ is not nullptr"); + return; } const int32_t ALL_USER_ID = -1; strongAuthListener_ = sptr(new (std::nothrow) UserIamStrongAuthListener(ALL_USER_ID)); - if (strongAuthListener_ == nullptr) { - IAM_LOGE("strongAuthListener_ is nullptr"); - } + IF_FALSE_LOGE_AND_RETURN(strongAuthListener_ != nullptr); ScreenLockManager::GetInstance()->RegisterStrongAuthListener(strongAuthListener_); - if (strongAuthListener_ == nullptr) { - IAM_LOGE("RegisterStrongAuthListener fail"); - } + IF_FALSE_LOGE_AND_RETURN(strongAuthListener_ != nullptr); SyncStrongAuthStatusForAllAccounts(); } @@ -118,7 +114,6 @@ void StrongAuthStatusManagerImpl::UnRegisterStrongAuthListener() IAM_LOGI("start"); std::lock_guard lock(mutex_); if (strongAuthListener_ == nullptr) { - IAM_LOGI("strongAuthListener_ is nullptr"); return; } @@ -134,21 +129,15 @@ void StrongAuthStatusManagerImpl::SyncStrongAuthStatusForAllAccounts() { IAM_LOGI("start"); std::lock_guard lock(mutex_); + auto screenLockManager = ScreenLockManager::GetInstance(); + IF_FALSE_LOGE_AND_RETURN(screenLockManager != nullptr); + IF_FALSE_LOGE_AND_RETURN(strongAuthListener_ != nullptr); + std::vector userIdList; IpcCommon::GetAllUserId(userIdList); int32_t reasonFlag = static_cast(StrongAuthReasonFlags::NONE); for (int32_t &userId : userIdList) { - auto screenLockManager = ScreenLockManager::GetInstance(); - if (screenLockManager == nullptr) { - IAM_LOGE("screenLockManger is nullptr"); - return; - } screenLockManager->GetStrongAuth(userId, reasonFlag); - - if (strongAuthListener_ == nullptr) { - IAM_LOGE("strongAuthListener_ is nullptr"); - return; - } strongAuthListener_->OnStrongAuthChanged(userId, reasonFlag); reasonFlag = static_cast(StrongAuthReasonFlags::NONE); } @@ -175,14 +164,10 @@ bool StrongAuthStatusManagerImpl::IsScreenLockStrongAuth(int32_t userId) { int32_t reasonFlag = static_cast(StrongAuthReasonFlags::NONE); auto screenLockManager = ScreenLockManager::GetInstance(); - if (screenLockManager == nullptr) { - IAM_LOGE("screenLockManager is nullptr"); - return false; - } + IF_FALSE_LOGE_AND_RETURN_VAL(screenLockManager != nullptr, false); screenLockManager->GetStrongAuth(userId, reasonFlag); - IAM_LOGI("get strong auth ret: %{public}d for userId: %{public}d", reasonFlag, userId); + if (reasonFlag == static_cast(StrongAuthReasonFlags::NONE)) { - IAM_LOGE("screenlock not in strong auth status"); return false; } return true; -- Gitee