1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16 
17 package com.android.keyguard;
18 
19 import static android.app.StatusBarManager.SESSION_KEYGUARD;
20 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
21 import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
22 import static android.hardware.biometrics.BiometricFaceConstants.FACE_ERROR_LOCKOUT_PERMANENT;
23 import static android.hardware.biometrics.BiometricFingerprintConstants.FINGERPRINT_ERROR_LOCKOUT;
24 import static android.hardware.biometrics.BiometricFingerprintConstants.FINGERPRINT_ERROR_LOCKOUT_PERMANENT;
25 import static android.hardware.biometrics.SensorProperties.STRENGTH_CONVENIENCE;
26 import static android.hardware.biometrics.SensorProperties.STRENGTH_STRONG;
27 import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_UDFPS_OPTICAL;
28 import static android.telephony.SubscriptionManager.DATA_ROAMING_DISABLE;
29 import static android.telephony.SubscriptionManager.NAME_SOURCE_CARRIER_ID;
30 import static android.telephony.SubscriptionManager.PROFILE_CLASS_DEFAULT;
31 import static android.telephony.SubscriptionManager.PROFILE_CLASS_PROVISIONING;
32 
33 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_USER_REQUEST;
34 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN;
35 import static com.android.keyguard.KeyguardUpdateMonitor.BIOMETRIC_STATE_CANCELLING_RESTARTING;
36 import static com.android.keyguard.KeyguardUpdateMonitor.BIOMETRIC_STATE_STOPPED;
37 import static com.android.keyguard.KeyguardUpdateMonitor.DEFAULT_CANCEL_SIGNAL_TIMEOUT;
38 import static com.android.keyguard.KeyguardUpdateMonitor.HAL_POWER_PRESS_TIMEOUT;
39 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_OPENED;
40 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_UNKNOWN;
41 
42 import static com.google.common.truth.Truth.assertThat;
43 
44 import static junit.framework.Assert.assertEquals;
45 
46 import static kotlinx.coroutines.flow.StateFlowKt.MutableStateFlow;
47 
48 import static org.mockito.ArgumentMatchers.any;
49 import static org.mockito.ArgumentMatchers.anyBoolean;
50 import static org.mockito.ArgumentMatchers.anyInt;
51 import static org.mockito.ArgumentMatchers.anyObject;
52 import static org.mockito.ArgumentMatchers.anyString;
53 import static org.mockito.ArgumentMatchers.eq;
54 import static org.mockito.Mockito.atLeastOnce;
55 import static org.mockito.Mockito.clearInvocations;
56 import static org.mockito.Mockito.doNothing;
57 import static org.mockito.Mockito.doReturn;
58 import static org.mockito.Mockito.mock;
59 import static org.mockito.Mockito.never;
60 import static org.mockito.Mockito.spy;
61 import static org.mockito.Mockito.times;
62 import static org.mockito.Mockito.verify;
63 import static org.mockito.Mockito.when;
64 
65 import android.app.Activity;
66 import android.app.ActivityTaskManager;
67 import android.app.IActivityTaskManager;
68 import android.app.admin.DevicePolicyManager;
69 import android.app.trust.IStrongAuthTracker;
70 import android.app.trust.TrustManager;
71 import android.content.BroadcastReceiver;
72 import android.content.ComponentName;
73 import android.content.ContentResolver;
74 import android.content.Context;
75 import android.content.Intent;
76 import android.content.IntentFilter;
77 import android.content.pm.PackageManager;
78 import android.content.pm.ResolveInfo;
79 import android.content.pm.ServiceInfo;
80 import android.database.ContentObserver;
81 import android.hardware.SensorPrivacyManager;
82 import android.hardware.biometrics.BiometricAuthenticator;
83 import android.hardware.biometrics.BiometricConstants;
84 import android.hardware.biometrics.BiometricManager;
85 import android.hardware.biometrics.BiometricSourceType;
86 import android.hardware.biometrics.ComponentInfoInternal;
87 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
88 import android.hardware.fingerprint.FingerprintManager;
89 import android.hardware.fingerprint.FingerprintSensorProperties;
90 import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
91 import android.hardware.fingerprint.IFingerprintAuthenticatorsRegisteredCallback;
92 import android.hardware.usb.UsbManager;
93 import android.hardware.usb.UsbPort;
94 import android.hardware.usb.UsbPortStatus;
95 import android.net.Uri;
96 import android.nfc.NfcAdapter;
97 import android.os.BatteryManager;
98 import android.os.Bundle;
99 import android.os.CancellationSignal;
100 import android.os.Handler;
101 import android.os.PowerManager;
102 import android.os.RemoteException;
103 import android.os.UserHandle;
104 import android.os.UserManager;
105 import android.service.dreams.IDreamManager;
106 import android.service.trust.TrustAgentService;
107 import android.telephony.ServiceState;
108 import android.telephony.SubscriptionInfo;
109 import android.telephony.SubscriptionManager;
110 import android.telephony.TelephonyManager;
111 import android.testing.AndroidTestingRunner;
112 import android.testing.TestableLooper;
113 import android.text.TextUtils;
114 
115 import androidx.test.filters.SmallTest;
116 
117 import com.android.dx.mockito.inline.extended.ExtendedMockito;
118 import com.android.internal.foldables.FoldGracePeriodProvider;
119 import com.android.internal.jank.InteractionJankMonitor;
120 import com.android.internal.logging.InstanceId;
121 import com.android.internal.logging.UiEventLogger;
122 import com.android.internal.telephony.TelephonyIntents;
123 import com.android.internal.util.LatencyTracker;
124 import com.android.internal.widget.ILockSettings;
125 import com.android.internal.widget.LockPatternUtils;
126 import com.android.keyguard.KeyguardUpdateMonitor.BiometricAuthenticated;
127 import com.android.keyguard.logging.KeyguardUpdateMonitorLogger;
128 import com.android.settingslib.fuelgauge.BatteryStatus;
129 import com.android.systemui.SysuiTestCase;
130 import com.android.systemui.biometrics.AuthController;
131 import com.android.systemui.biometrics.FingerprintInteractiveToAuthProvider;
132 import com.android.systemui.broadcast.BroadcastDispatcher;
133 import com.android.systemui.deviceentry.data.repository.FaceWakeUpTriggersConfig;
134 import com.android.systemui.deviceentry.data.repository.FaceWakeUpTriggersConfigImpl;
135 import com.android.systemui.deviceentry.domain.interactor.DeviceEntryFaceAuthInteractor;
136 import com.android.systemui.deviceentry.domain.interactor.FaceAuthenticationListener;
137 import com.android.systemui.deviceentry.shared.model.ErrorFaceAuthenticationStatus;
138 import com.android.systemui.deviceentry.shared.model.FaceDetectionStatus;
139 import com.android.systemui.deviceentry.shared.model.FailedFaceAuthenticationStatus;
140 import com.android.systemui.dump.DumpManager;
141 import com.android.systemui.kosmos.KosmosJavaAdapter;
142 import com.android.systemui.log.SessionTracker;
143 import com.android.systemui.plugins.statusbar.StatusBarStateController;
144 import com.android.systemui.settings.UserTracker;
145 import com.android.systemui.shared.system.TaskStackChangeListener;
146 import com.android.systemui.shared.system.TaskStackChangeListeners;
147 import com.android.systemui.statusbar.StatusBarState;
148 import com.android.systemui.statusbar.phone.KeyguardBypassController;
149 import com.android.systemui.statusbar.policy.DevicePostureController;
150 import com.android.systemui.telephony.TelephonyListenerManager;
151 import com.android.systemui.user.domain.interactor.SelectedUserInteractor;
152 import com.android.systemui.util.settings.GlobalSettings;
153 
154 import org.junit.After;
155 import org.junit.Assert;
156 import org.junit.Before;
157 import org.junit.Test;
158 import org.junit.runner.RunWith;
159 import org.mockito.ArgumentCaptor;
160 import org.mockito.Captor;
161 import org.mockito.InOrder;
162 import org.mockito.Mock;
163 import org.mockito.Mockito;
164 import org.mockito.MockitoAnnotations;
165 import org.mockito.MockitoSession;
166 import org.mockito.internal.util.reflection.FieldSetter;
167 import org.mockito.quality.Strictness;
168 
169 import java.util.ArrayList;
170 import java.util.Arrays;
171 import java.util.List;
172 import java.util.Optional;
173 import java.util.Random;
174 import java.util.concurrent.Executor;
175 import java.util.concurrent.atomic.AtomicBoolean;
176 import java.util.concurrent.atomic.AtomicInteger;
177 
178 @SmallTest
179 @RunWith(AndroidTestingRunner.class)
180 @TestableLooper.RunWithLooper
181 public class KeyguardUpdateMonitorTest extends SysuiTestCase {
182     private static final String PKG_ALLOWING_FP_LISTEN_ON_OCCLUDING_ACTIVITY =
183             "test_app_fp_listen_on_occluding_activity";
184     private static final String TEST_CARRIER = "TEST_CARRIER";
185     private static final String TEST_CARRIER_2 = "TEST_CARRIER_2";
186     private static final int TEST_CARRIER_ID = 1;
187     private static final String TEST_GROUP_UUID = "59b5c870-fc4c-47a4-a99e-9db826b48b24";
188     private static final SubscriptionInfo TEST_SUBSCRIPTION = new SubscriptionInfo(1, "", 0,
189             TEST_CARRIER, TEST_CARRIER, NAME_SOURCE_CARRIER_ID, 0xFFFFFF, "",
190             DATA_ROAMING_DISABLE, null, null, null, null, false, null, "", false, TEST_GROUP_UUID,
191             TEST_CARRIER_ID, 0);
192     private static final SubscriptionInfo TEST_SUBSCRIPTION_2 = new SubscriptionInfo(2, "", 0,
193             TEST_CARRIER, TEST_CARRIER_2, NAME_SOURCE_CARRIER_ID, 0xFFFFFF, "",
194             DATA_ROAMING_DISABLE, null, null, null, null, false, null, "", true, TEST_GROUP_UUID,
195             TEST_CARRIER_ID, 0);
196     private static final SubscriptionInfo TEST_SUBSCRIPTION_PROVISIONING = new SubscriptionInfo(
197             1, "", 0,
198             TEST_CARRIER, TEST_CARRIER, NAME_SOURCE_CARRIER_ID, 0xFFFFFF, "",
199             DATA_ROAMING_DISABLE, null, null, null, null, false, null, "", false, TEST_GROUP_UUID,
200             TEST_CARRIER_ID, PROFILE_CLASS_PROVISIONING);
201     private static final int FINGERPRINT_SENSOR_ID = 1;
202     private KosmosJavaAdapter mKosmos;
203     @Mock
204     private UserTracker mUserTracker;
205     @Mock
206     private DumpManager mDumpManager;
207     @Mock
208     private KeyguardUpdateMonitor.StrongAuthTracker mStrongAuthTracker;
209     @Mock
210     private TrustManager mTrustManager;
211     @Mock
212     private LockPatternUtils mLockPatternUtils;
213     @Mock
214     private ILockSettings mLockSettings;
215     @Mock
216     private FingerprintManager mFingerprintManager;
217     @Mock
218     private BiometricManager mBiometricManager;
219     @Mock
220     private PackageManager mPackageManager;
221     @Mock
222     private UserManager mUserManager;
223     @Mock
224     private DevicePolicyManager mDevicePolicyManager;
225     @Mock
226     private DevicePostureController mDevicePostureController;
227     @Mock
228     private IDreamManager mDreamManager;
229     @Mock
230     private KeyguardBypassController mKeyguardBypassController;
231     @Mock
232     private SubscriptionManager mSubscriptionManager;
233     @Mock
234     private BroadcastDispatcher mBroadcastDispatcher;
235     @Mock
236     private FoldGracePeriodProvider mFoldGracePeriodProvider;
237     @Mock
238     private TelephonyManager mTelephonyManager;
239     @Mock
240     private SensorPrivacyManager mSensorPrivacyManager;
241     @Mock
242     private StatusBarStateController mStatusBarStateController;
243     @Mock
244     private AuthController mAuthController;
245     @Mock
246     private TelephonyListenerManager mTelephonyListenerManager;
247     private InteractionJankMonitor mInteractionJankMonitor;
248     @Mock
249     private LatencyTracker mLatencyTracker;
250     @Captor
251     private ArgumentCaptor<StatusBarStateController.StateListener> mStatusBarStateListenerCaptor;
252     @Mock
253     private KeyguardUpdateMonitorCallback mTestCallback;
254     @Mock
255     private ActiveUnlockConfig mActiveUnlockConfig;
256     @Mock
257     private KeyguardUpdateMonitorLogger mKeyguardUpdateMonitorLogger;
258     @Mock
259     private SessionTracker mSessionTracker;
260     @Mock
261     private UiEventLogger mUiEventLogger;
262     @Mock
263     private GlobalSettings mGlobalSettings;
264     @Mock
265     private FingerprintInteractiveToAuthProvider mInteractiveToAuthProvider;
266     @Mock
267     private UsbPort mUsbPort;
268     @Mock
269     private UsbManager mUsbManager;
270     @Mock
271     private UsbPortStatus mUsbPortStatus;
272     @Mock
273     private TaskStackChangeListeners mTaskStackChangeListeners;
274     @Mock
275     private IActivityTaskManager mActivityTaskManager;
276     @Mock
277     private SelectedUserInteractor mSelectedUserInteractor;
278     @Mock
279     private DeviceEntryFaceAuthInteractor mFaceAuthInteractor;
280     @Captor
281     private ArgumentCaptor<FaceAuthenticationListener> mFaceAuthenticationListener;
282 
283     private List<FingerprintSensorPropertiesInternal> mFingerprintSensorProperties;
284     private final int mCurrentUserId = 100;
285 
286     @Captor
287     private ArgumentCaptor<IBiometricEnabledOnKeyguardCallback>
288             mBiometricEnabledCallbackArgCaptor;
289 
290     // Direct executor
291     private final Executor mBackgroundExecutor = Runnable::run;
292     private final Executor mMainExecutor = Runnable::run;
293     private TestableLooper mTestableLooper;
294     private Handler mHandler;
295     private TestableKeyguardUpdateMonitor mKeyguardUpdateMonitor;
296     private MockitoSession mMockitoSession;
297     private StatusBarStateController.StateListener mStatusBarStateListener;
298     private IBiometricEnabledOnKeyguardCallback mBiometricEnabledOnKeyguardCallback;
299     private FaceWakeUpTriggersConfig mFaceWakeUpTriggersConfig;
300     private IFingerprintAuthenticatorsRegisteredCallback
301             mFingerprintAuthenticatorsRegisteredCallback;
302     private final InstanceId mKeyguardInstanceId = InstanceId.fakeInstanceId(999);
303 
304     @Before
setup()305     public void setup() throws RemoteException {
306         mKosmos = new KosmosJavaAdapter(this);
307         mInteractionJankMonitor = mKosmos.getInteractionJankMonitor();
308         MockitoAnnotations.initMocks(this);
309         when(mSessionTracker.getSessionId(SESSION_KEYGUARD)).thenReturn(mKeyguardInstanceId);
310         when(mFaceAuthInteractor.isAuthenticated()).thenReturn(MutableStateFlow(false));
311         when(mFaceAuthInteractor.isLockedOut()).thenReturn(MutableStateFlow(false));
312         when(mUserManager.isUserUnlocked(anyInt())).thenReturn(true);
313         currentUserIsSystem();
314         when(mStrongAuthTracker.getStub()).thenReturn(mock(IStrongAuthTracker.Stub.class));
315         when(mStrongAuthTracker
316                 .isUnlockingWithBiometricAllowed(anyBoolean() /* isClass3Biometric */))
317                 .thenReturn(true);
318         when(mTelephonyManager.getServiceStateForSubscriber(anyInt()))
319                 .thenReturn(new ServiceState());
320         when(mLockPatternUtils.getLockSettings()).thenReturn(mLockSettings);
321         when(mAuthController.isUdfpsEnrolled(anyInt())).thenReturn(false);
322         when(mDevicePostureController.getDevicePosture()).thenReturn(DEVICE_POSTURE_UNKNOWN);
323 
324         mMockitoSession = ExtendedMockito.mockitoSession()
325                 .spyStatic(SubscriptionManager.class)
326                 .strictness(Strictness.WARN)
327                 .startMocking();
328         ExtendedMockito.doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID)
329                 .when(SubscriptionManager::getDefaultSubscriptionId);
330         when(mSelectedUserInteractor.getSelectedUserId()).thenReturn(mCurrentUserId);
331         when(mSelectedUserInteractor.getSelectedUserId(anyBoolean())).thenReturn(mCurrentUserId);
332 
333         mContext.getOrCreateTestableResources().addOverride(
334                 com.android.systemui.res.R.integer.config_face_auth_supported_posture,
335                 DEVICE_POSTURE_UNKNOWN);
336         mFaceWakeUpTriggersConfig = new FaceWakeUpTriggersConfigImpl(
337                 mContext.getResources(),
338                 mGlobalSettings,
339                 mDumpManager
340         );
341 
342         mContext.getOrCreateTestableResources().addOverride(com.android.systemui.res
343                         .R.array.config_fingerprint_listen_on_occluding_activity_packages,
344                 new String[]{PKG_ALLOWING_FP_LISTEN_ON_OCCLUDING_ACTIVITY});
345 
346         mTestableLooper = TestableLooper.get(this);
347         allowTestableLooperAsMainThread();
348 
349         final ContentResolver contentResolver = mContext.getContentResolver();
350         ExtendedMockito.spyOn(contentResolver);
351         doNothing().when(contentResolver)
352                 .registerContentObserver(any(Uri.class), anyBoolean(), any(ContentObserver.class),
353                         anyInt());
354 
355         mKeyguardUpdateMonitor = new TestableKeyguardUpdateMonitor(mContext);
356         mKeyguardUpdateMonitor.mFoldGracePeriodProvider = mFoldGracePeriodProvider;
357         setupBiometrics(mKeyguardUpdateMonitor);
358         mKeyguardUpdateMonitor.setFaceAuthInteractor(mFaceAuthInteractor);
359         verify(mFaceAuthInteractor).registerListener(mFaceAuthenticationListener.capture());
360     }
361 
setupBiometrics(KeyguardUpdateMonitor keyguardUpdateMonitor)362     private void setupBiometrics(KeyguardUpdateMonitor keyguardUpdateMonitor)
363             throws RemoteException {
364         captureAuthenticatorsRegisteredCallbacks();
365         when(mFaceAuthInteractor.isFaceAuthStrong()).thenReturn(false);
366         setupFingerprintAuth(/* isClass3 */ true);
367 
368         verify(mBiometricManager)
369                 .registerEnabledOnKeyguardCallback(mBiometricEnabledCallbackArgCaptor.capture());
370         mBiometricEnabledOnKeyguardCallback = mBiometricEnabledCallbackArgCaptor.getValue();
371         biometricsEnabledForCurrentUser();
372 
373         mHandler = spy(keyguardUpdateMonitor.getHandler());
374         try {
375             FieldSetter.setField(keyguardUpdateMonitor,
376                     KeyguardUpdateMonitor.class.getDeclaredField("mHandler"), mHandler);
377         } catch (NoSuchFieldException e) {
378 
379         }
380         verify(mStatusBarStateController).addCallback(mStatusBarStateListenerCaptor.capture());
381         mStatusBarStateListener = mStatusBarStateListenerCaptor.getValue();
382         mKeyguardUpdateMonitor.registerCallback(mTestCallback);
383 
384         mTestableLooper.processAllMessages();
385         when(mAuthController.areAllFingerprintAuthenticatorsRegistered()).thenReturn(true);
386     }
387 
captureAuthenticatorsRegisteredCallbacks()388     private void captureAuthenticatorsRegisteredCallbacks() throws RemoteException {
389         ArgumentCaptor<IFingerprintAuthenticatorsRegisteredCallback> fingerprintCaptor =
390                 ArgumentCaptor.forClass(IFingerprintAuthenticatorsRegisteredCallback.class);
391         verify(mFingerprintManager).addAuthenticatorsRegisteredCallback(
392                 fingerprintCaptor.capture());
393         mFingerprintAuthenticatorsRegisteredCallback = fingerprintCaptor.getValue();
394         mFingerprintAuthenticatorsRegisteredCallback
395                 .onAllAuthenticatorsRegistered(mFingerprintSensorProperties);
396     }
397 
setupFingerprintAuth(boolean isClass3)398     private void setupFingerprintAuth(boolean isClass3) throws RemoteException {
399         when(mAuthController.isFingerprintEnrolled(anyInt())).thenReturn(true);
400         when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
401         when(mFingerprintManager.hasEnrolledTemplates(anyInt())).thenReturn(true);
402         mFingerprintSensorProperties = List.of(
403                 createFingerprintSensorPropertiesInternal(TYPE_UDFPS_OPTICAL, isClass3));
404         when(mFingerprintManager.getSensorPropertiesInternal()).thenReturn(
405                 mFingerprintSensorProperties);
406         mFingerprintAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(
407                 mFingerprintSensorProperties);
408         assertEquals(isClass3, mKeyguardUpdateMonitor.isFingerprintClass3());
409     }
410 
createFingerprintSensorPropertiesInternal( @ingerprintSensorProperties.SensorType int sensorType, boolean isClass3)411     private FingerprintSensorPropertiesInternal createFingerprintSensorPropertiesInternal(
412             @FingerprintSensorProperties.SensorType int sensorType,
413             boolean isClass3) {
414         final List<ComponentInfoInternal> componentInfo =
415                 List.of(new ComponentInfoInternal("fingerprintSensor" /* componentId */,
416                         "vendor/model/revision" /* hardwareVersion */,
417                         "1.01" /* firmwareVersion */,
418                         "00000001" /* serialNumber */, "" /* softwareVersion */));
419         return new FingerprintSensorPropertiesInternal(
420                 FINGERPRINT_SENSOR_ID,
421                 isClass3 ? STRENGTH_STRONG : STRENGTH_CONVENIENCE,
422                 1 /* maxEnrollmentsPerUser */,
423                 componentInfo,
424                 sensorType,
425                 true /* resetLockoutRequiresHardwareAuthToken */);
426     }
427 
428     @After
tearDown()429     public void tearDown() {
430         if (mMockitoSession != null) {
431             mMockitoSession.finishMocking();
432         }
433         cleanupKeyguardUpdateMonitor();
434     }
435 
436     @Test
testInitialBatteryLevelRequested()437     public void testInitialBatteryLevelRequested() {
438         mTestableLooper.processAllMessages();
439 
440         assertThat(mKeyguardUpdateMonitor.mBatteryStatus).isNotNull();
441     }
442 
443     @Test
testReceiversRegistered()444     public void testReceiversRegistered() {
445         verify(mBroadcastDispatcher, atLeastOnce()).registerReceiverWithHandler(
446                 eq(mKeyguardUpdateMonitor.mBroadcastReceiver),
447                 any(IntentFilter.class), any(Handler.class));
448         verify(mBroadcastDispatcher, atLeastOnce()).registerReceiverWithHandler(
449                 eq(mKeyguardUpdateMonitor.mBroadcastAllReceiver),
450                 any(IntentFilter.class), any(Handler.class), eq(UserHandle.ALL));
451     }
452 
453     @Test
testSimStateInitialized()454     public void testSimStateInitialized() {
455         cleanupKeyguardUpdateMonitor();
456         final int subId = 3;
457         final int state = TelephonyManager.SIM_STATE_ABSENT;
458 
459         when(mTelephonyManager.getActiveModemCount()).thenReturn(1);
460         when(mTelephonyManager.getSimState(anyInt())).thenReturn(state);
461         when(mSubscriptionManager.getSubscriptionIds(anyInt())).thenReturn(new int[]{subId});
462 
463         KeyguardUpdateMonitor testKUM = new TestableKeyguardUpdateMonitor(mContext);
464 
465         mTestableLooper.processAllMessages();
466 
467         assertThat(testKUM.getSimState(subId)).isEqualTo(state);
468     }
469 
470     @Test
testIgnoresSimStateCallback_rebroadcast()471     public void testIgnoresSimStateCallback_rebroadcast() {
472         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
473 
474         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(), intent);
475         mTestableLooper.processAllMessages();
476         Assert.assertTrue("onSimStateChanged not called",
477                 mKeyguardUpdateMonitor.hasSimStateJustChanged());
478 
479         intent.putExtra(Intent.EXTRA_REBROADCAST_ON_UNLOCK, true);
480         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(), intent);
481         mTestableLooper.processAllMessages();
482         Assert.assertFalse("onSimStateChanged should have been skipped",
483                 mKeyguardUpdateMonitor.hasSimStateJustChanged());
484     }
485 
486     @Test
testTelephonyCapable_BootInitState()487     public void testTelephonyCapable_BootInitState() {
488         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
489     }
490 
491     @Test
testTelephonyCapable_SimState_Absent()492     public void testTelephonyCapable_SimState_Absent() {
493         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
494         intent.putExtra(Intent.EXTRA_SIM_STATE,
495                 Intent.SIM_STATE_ABSENT);
496         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
497                 putPhoneInfo(intent, null, false));
498         mTestableLooper.processAllMessages();
499         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
500     }
501 
502     @Test
testTelephonyCapable_SimState_CardIOError()503     public void testTelephonyCapable_SimState_CardIOError() {
504         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
505         intent.putExtra(Intent.EXTRA_SIM_STATE,
506                 Intent.SIM_STATE_CARD_IO_ERROR);
507         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
508                 putPhoneInfo(intent, null, false));
509         mTestableLooper.processAllMessages();
510         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
511     }
512 
513     @Test
testTelephonyCapable_SimInvalid_ServiceState_InService()514     public void testTelephonyCapable_SimInvalid_ServiceState_InService() {
515         // SERVICE_STATE - IN_SERVICE, but SIM_STATE is invalid TelephonyCapable should be False
516         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
517         Bundle data = new Bundle();
518         ServiceState state = new ServiceState();
519         state.setState(ServiceState.STATE_IN_SERVICE);
520         state.fillInNotifierBundle(data);
521         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
522                 , putPhoneInfo(intent, data, false));
523         mTestableLooper.processAllMessages();
524         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
525     }
526 
527     @Test
testTelephonyCapable_SimValid_ServiceState_PowerOff()528     public void testTelephonyCapable_SimValid_ServiceState_PowerOff() {
529         // Simulate AirplaneMode case, SERVICE_STATE - POWER_OFF, check TelephonyCapable False
530         // Only receive ServiceState callback IN_SERVICE -> OUT_OF_SERVICE -> POWER_OFF
531         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
532         intent.putExtra(Intent.EXTRA_SIM_STATE
533                 , Intent.SIM_STATE_LOADED);
534         Bundle data = new Bundle();
535         ServiceState state = new ServiceState();
536         state.setState(ServiceState.STATE_POWER_OFF);
537         state.fillInNotifierBundle(data);
538         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
539                 , putPhoneInfo(intent, data, true));
540         mTestableLooper.processAllMessages();
541         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
542     }
543 
544     /* Normal SIM inserted flow
545      * ServiceState:    ---OutOfServie----->PowerOff->OutOfServie--->InService
546      * SimState:        ----NOT_READY---->READY----------------------LOADED>>>
547      * Subscription:    --------null---->null--->"Chunghwa Telecom"-------->>>
548      * System:          -------------------------------BOOT_COMPLETED------>>>
549      * TelephonyCapable:(F)-(F)-(F)-(F)-(F)-(F)-(F)-(F)-(F)-(F)------(T)-(T)>>
550      */
551     @Test
testTelephonyCapable_BootInitState_ServiceState_OutOfService()552     public void testTelephonyCapable_BootInitState_ServiceState_OutOfService() {
553         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
554         Bundle data = new Bundle();
555         ServiceState state = new ServiceState();
556         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
557         state.fillInNotifierBundle(data);
558         intent.putExtras(data);
559         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
560                 , putPhoneInfo(intent, data, false));
561         mTestableLooper.processAllMessages();
562         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
563     }
564 
565     @Test
testTelephonyCapable_BootInitState_SimState_NotReady()566     public void testTelephonyCapable_BootInitState_SimState_NotReady() {
567         Bundle data = new Bundle();
568         ServiceState state = new ServiceState();
569         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
570         state.fillInNotifierBundle(data);
571         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
572         intent.putExtra(Intent.EXTRA_SIM_STATE
573                 , Intent.SIM_STATE_NOT_READY);
574         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
575                 , putPhoneInfo(intent, data, false));
576         mTestableLooper.processAllMessages();
577         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
578     }
579 
580     @Test
testTelephonyCapable_BootInitState_SimState_Ready()581     public void testTelephonyCapable_BootInitState_SimState_Ready() {
582         Bundle data = new Bundle();
583         ServiceState state = new ServiceState();
584         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
585         state.fillInNotifierBundle(data);
586         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
587         intent.putExtra(Intent.EXTRA_SIM_STATE
588                 , Intent.SIM_STATE_READY);
589         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
590                 , putPhoneInfo(intent, data, false));
591         mTestableLooper.processAllMessages();
592         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
593     }
594 
595     @Test
testTelephonyCapable_BootInitState_ServiceState_PowerOff()596     public void testTelephonyCapable_BootInitState_ServiceState_PowerOff() {
597         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
598         Bundle data = new Bundle();
599         ServiceState state = new ServiceState();
600         state.setState(ServiceState.STATE_POWER_OFF);
601         state.fillInNotifierBundle(data);
602         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
603                 , putPhoneInfo(intent, data, false));
604         mTestableLooper.processAllMessages();
605         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
606     }
607 
608     @Test
testTelephonyCapable_SimValid_ServiceState_InService()609     public void testTelephonyCapable_SimValid_ServiceState_InService() {
610         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
611         Bundle data = new Bundle();
612         ServiceState state = new ServiceState();
613         state.setState(ServiceState.STATE_IN_SERVICE);
614         state.fillInNotifierBundle(data);
615         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
616                 , putPhoneInfo(intent, data, true));
617         mTestableLooper.processAllMessages();
618         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
619     }
620 
621     @Test
testTelephonyCapable_SimValid_SimState_Loaded()622     public void testTelephonyCapable_SimValid_SimState_Loaded() {
623         Bundle data = new Bundle();
624         ServiceState state = new ServiceState();
625         state.setState(ServiceState.STATE_IN_SERVICE);
626         state.fillInNotifierBundle(data);
627         Intent intentSimState = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
628         intentSimState.putExtra(Intent.EXTRA_SIM_STATE
629                 , Intent.SIM_STATE_LOADED);
630         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
631                 , putPhoneInfo(intentSimState, data, true));
632         mTestableLooper.processAllMessages();
633         // Even SimState Loaded, still need ACTION_SERVICE_STATE turn on mTelephonyCapable
634         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
635 
636         Intent intentServiceState = new Intent(Intent.ACTION_SERVICE_STATE);
637         intentSimState.putExtra(Intent.EXTRA_SIM_STATE
638                 , Intent.SIM_STATE_LOADED);
639         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
640                 , putPhoneInfo(intentServiceState, data, true));
641         mTestableLooper.processAllMessages();
642         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
643     }
644 
645     @Test
serviceProvidersUpdated_broadcastTriggersInfoRefresh()646     public void serviceProvidersUpdated_broadcastTriggersInfoRefresh() {
647         // The callback is invoked once on init
648         verify(mTestCallback, times(1)).onRefreshCarrierInfo();
649 
650         // WHEN the SERVICE_PROVIDERS_UPDATED broadcast is sent
651         Intent intent = new Intent(TelephonyManager.ACTION_SERVICE_PROVIDERS_UPDATED);
652         intent.putExtra(TelephonyManager.EXTRA_SPN, "spn");
653         intent.putExtra(TelephonyManager.EXTRA_PLMN, "plmn");
654         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
655                 putPhoneInfo(intent, null, true));
656         mTestableLooper.processAllMessages();
657 
658         // THEN verify keyguardUpdateMonitorCallback receives a refresh callback
659         // Note that we have times(2) here because it's been called once already
660         verify(mTestCallback, times(2)).onRefreshCarrierInfo();
661     }
662 
663     @Test
testHandleSimStateChange_Unknown()664     public void testHandleSimStateChange_Unknown() {
665         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
666         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_UNKNOWN);
667         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
668                 putPhoneInfo(intent, null, false));
669         mTestableLooper.processAllMessages();
670         Assert.assertEquals(TelephonyManager.SIM_STATE_UNKNOWN,
671                 mKeyguardUpdateMonitor.getCachedSimState());
672     }
673 
674     @Test
testHandleSimStateChange_Absent()675     public void testHandleSimStateChange_Absent() {
676         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
677         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_ABSENT);
678         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
679                 putPhoneInfo(intent, null, false));
680         mTestableLooper.processAllMessages();
681         Assert.assertEquals(TelephonyManager.SIM_STATE_ABSENT,
682                 mKeyguardUpdateMonitor.getCachedSimState());
683     }
684 
685     @Test
testHandleSimStateChange_CardIOError()686     public void testHandleSimStateChange_CardIOError() {
687         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
688         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_CARD_IO_ERROR);
689         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_STATE_CARD_IO_ERROR);
690         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
691                 putPhoneInfo(intent, null, false));
692         mTestableLooper.processAllMessages();
693         Assert.assertEquals(TelephonyManager.SIM_STATE_CARD_IO_ERROR,
694                 mKeyguardUpdateMonitor.getCachedSimState());
695     }
696 
697     @Test
testHandleSimStateChange_CardRestricted()698     public void testHandleSimStateChange_CardRestricted() {
699         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
700         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_CARD_RESTRICTED);
701         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_STATE_CARD_RESTRICTED);
702         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
703                 putPhoneInfo(intent, null, false));
704         mTestableLooper.processAllMessages();
705         Assert.assertEquals(TelephonyManager.SIM_STATE_CARD_RESTRICTED,
706                 mKeyguardUpdateMonitor.getCachedSimState());
707     }
708 
709     @Test
testHandleSimStateChange_Locked()710     public void testHandleSimStateChange_Locked() {
711         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
712         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_LOCKED);
713 
714         // locked on PIN1
715         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_LOCKED_ON_PIN);
716         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
717                 putPhoneInfo(intent, null, true));
718         mTestableLooper.processAllMessages();
719         Assert.assertEquals(TelephonyManager.SIM_STATE_PIN_REQUIRED,
720                 mKeyguardUpdateMonitor.getCachedSimState());
721 
722         // locked on PUK1
723         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_LOCKED_ON_PUK);
724         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
725                 putPhoneInfo(intent, null, true));
726         mTestableLooper.processAllMessages();
727         Assert.assertEquals(TelephonyManager.SIM_STATE_PUK_REQUIRED,
728                 mKeyguardUpdateMonitor.getCachedSimState());
729 
730         // locked on network personalization
731         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_LOCKED_NETWORK);
732         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
733                 putPhoneInfo(intent, null, true));
734         mTestableLooper.processAllMessages();
735         Assert.assertEquals(TelephonyManager.SIM_STATE_NETWORK_LOCKED,
736                 mKeyguardUpdateMonitor.getCachedSimState());
737 
738         // permanently disabled due to puk fails
739         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_ABSENT_ON_PERM_DISABLED);
740         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
741                 putPhoneInfo(intent, null, true));
742         mTestableLooper.processAllMessages();
743         Assert.assertEquals(TelephonyManager.SIM_STATE_PERM_DISABLED,
744                 mKeyguardUpdateMonitor.getCachedSimState());
745     }
746 
747     @Test
testHandleSimStateChange_NotReady()748     public void testHandleSimStateChange_NotReady() {
749         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
750         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_NOT_READY);
751         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
752                 putPhoneInfo(intent, null, false));
753         mTestableLooper.processAllMessages();
754         Assert.assertEquals(TelephonyManager.SIM_STATE_NOT_READY,
755                 mKeyguardUpdateMonitor.getCachedSimState());
756     }
757 
758     @Test
testHandleSimStateChange_Ready()759     public void testHandleSimStateChange_Ready() {
760         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
761 
762         // ICC IMSI is ready in property
763         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_IMSI);
764         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
765                 putPhoneInfo(intent, null, false));
766         mTestableLooper.processAllMessages();
767         Assert.assertEquals(TelephonyManager.SIM_STATE_READY,
768                 mKeyguardUpdateMonitor.getCachedSimState());
769 
770         // ICC is ready to access
771         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_READY);
772         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
773                 putPhoneInfo(intent, null, false));
774         mTestableLooper.processAllMessages();
775         Assert.assertEquals(TelephonyManager.SIM_STATE_READY,
776                 mKeyguardUpdateMonitor.getCachedSimState());
777 
778         // all ICC records, including IMSI, are loaded
779         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_LOADED);
780         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
781                 putPhoneInfo(intent, null, true));
782         mTestableLooper.processAllMessages();
783         Assert.assertEquals(TelephonyManager.SIM_STATE_READY,
784                 mKeyguardUpdateMonitor.getCachedSimState());
785     }
786 
787     @Test
testTriesToAuthenticateFingerprint_whenKeyguard()788     public void testTriesToAuthenticateFingerprint_whenKeyguard() {
789         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
790         mTestableLooper.processAllMessages();
791 
792         verifyFingerprintAuthenticateCall();
793         verifyFingerprintDetectNeverCalled();
794     }
795 
796     @Test
test_doesNotTryToAuthenticateFingerprint_whenAuthenticatorsNotRegistered()797     public void test_doesNotTryToAuthenticateFingerprint_whenAuthenticatorsNotRegistered() {
798         when(mAuthController.areAllFingerprintAuthenticatorsRegistered()).thenReturn(false);
799 
800         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
801         mTestableLooper.processAllMessages();
802 
803         verifyFingerprintAuthenticateNeverCalled();
804         verifyFingerprintDetectNeverCalled();
805     }
806 
807     @Test
testOnlyDetectFingerprint_whenFingerprintUnlockNotAllowed()808     public void testOnlyDetectFingerprint_whenFingerprintUnlockNotAllowed() {
809         givenDetectFingerprintWithClearingFingerprintManagerInvocations();
810 
811         verifyFingerprintAuthenticateNeverCalled();
812         verifyFingerprintDetectCall();
813     }
814 
815     @Test
whenDetectFingerprint_biometricDetectCallback()816     public void whenDetectFingerprint_biometricDetectCallback() {
817         ArgumentCaptor<FingerprintManager.FingerprintDetectionCallback> fpDetectCallbackCaptor =
818                 ArgumentCaptor.forClass(FingerprintManager.FingerprintDetectionCallback.class);
819 
820         givenDetectFingerprintWithClearingFingerprintManagerInvocations();
821         verify(mFingerprintManager).detectFingerprint(
822                 any(), fpDetectCallbackCaptor.capture(), any());
823         fpDetectCallbackCaptor.getValue().onFingerprintDetected(0, 0, true);
824 
825         // THEN verify keyguardUpdateMonitorCallback receives a detect callback
826         // and NO authenticate callbacks
827         verify(mTestCallback).onBiometricDetected(
828                 eq(0), eq(BiometricSourceType.FINGERPRINT), eq(true));
829         verify(mTestCallback, never()).onBiometricAuthenticated(
830                 anyInt(), any(), anyBoolean());
831     }
832 
833     @Test
whenDetectFingerprint_detectError()834     public void whenDetectFingerprint_detectError() {
835         ArgumentCaptor<FingerprintManager.FingerprintDetectionCallback> fpDetectCallbackCaptor =
836                 ArgumentCaptor.forClass(FingerprintManager.FingerprintDetectionCallback.class);
837 
838         givenDetectFingerprintWithClearingFingerprintManagerInvocations();
839         verify(mFingerprintManager).detectFingerprint(
840                 any(), fpDetectCallbackCaptor.capture(), any());
841         fpDetectCallbackCaptor.getValue().onDetectionError(/* msgId */ 10);
842 
843         // THEN verify keyguardUpdateMonitorCallback receives a biometric error
844         verify(mTestCallback).onBiometricError(
845                 eq(10), eq(""), eq(BiometricSourceType.FINGERPRINT));
846         verify(mTestCallback, never()).onBiometricAuthenticated(
847                 anyInt(), any(), anyBoolean());
848     }
849 
850     @Test
whenDetectFace_biometricDetectCallback()851     public void whenDetectFace_biometricDetectCallback() {
852         mFaceAuthenticationListener.getValue().onDetectionStatusChanged(
853                 new FaceDetectionStatus(0, 0, false, 0L));
854 
855         // THEN verify keyguardUpdateMonitorCallback receives a detect callback
856         // and NO authenticate callbacks
857         verify(mTestCallback).onBiometricDetected(
858                 eq(0), eq(BiometricSourceType.FACE), eq(false));
859         verify(mTestCallback, never()).onBiometricAuthenticated(
860                 anyInt(), any(), anyBoolean());
861     }
862 
863     @Test
testUnlockingWithFaceAllowed_strongAuthTrackerUnlockingWithBiometricAllowed()864     public void testUnlockingWithFaceAllowed_strongAuthTrackerUnlockingWithBiometricAllowed() {
865         // GIVEN unlocking with biometric is allowed
866         primaryAuthNotRequiredByStrongAuthTracker();
867 
868         // THEN unlocking with face and fp is allowed
869         Assert.assertTrue(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
870                 BiometricSourceType.FACE));
871         Assert.assertTrue(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
872                 BiometricSourceType.FINGERPRINT));
873     }
874 
875     @Test
testUnlockingWithFaceAllowed_strongAuthTrackerUnlockingWithBiometricNotAllowed()876     public void testUnlockingWithFaceAllowed_strongAuthTrackerUnlockingWithBiometricNotAllowed() {
877         // GIVEN unlocking with biometric is not allowed
878         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
879 
880         // THEN unlocking with face is not allowed
881         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
882                 BiometricSourceType.FACE));
883     }
884 
885     @Test
class3FaceLockOut_lockOutClass3Fingerprint()886     public void class3FaceLockOut_lockOutClass3Fingerprint() throws RemoteException {
887         when(mFaceAuthInteractor.isFaceAuthStrong()).thenReturn(true);
888         when(mFaceAuthInteractor.isFaceAuthEnabledAndEnrolled()).thenReturn(true);
889 
890         setupFingerprintAuth(/* isClass3 */ true);
891 
892         // GIVEN primary auth is not required by StrongAuthTracker
893         primaryAuthNotRequiredByStrongAuthTracker();
894 
895         // WHEN face (class 3) is lock out
896         faceAuthLockOut();
897 
898         // THEN unlocking with fingerprint is not allowed
899         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
900                 BiometricSourceType.FINGERPRINT));
901     }
902 
903     @Test
class1FaceLockOut_doesNotLockOutClass3Fingerprint()904     public void class1FaceLockOut_doesNotLockOutClass3Fingerprint() throws RemoteException {
905         when(mFaceAuthInteractor.isFaceAuthStrong()).thenReturn(false);
906         setupFingerprintAuth(/* isClass3 */ true);
907 
908         // GIVEN primary auth is not required by StrongAuthTracker
909         primaryAuthNotRequiredByStrongAuthTracker();
910 
911         // WHEN face (class 1) is lock out
912         faceAuthLockOut();
913 
914         // THEN unlocking with fingerprint is still allowed
915         Assert.assertTrue(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
916                 BiometricSourceType.FINGERPRINT));
917     }
918 
919     @Test
testUnlockingWithFpAllowed_strongAuthTrackerUnlockingWithBiometricNotAllowed()920     public void testUnlockingWithFpAllowed_strongAuthTrackerUnlockingWithBiometricNotAllowed() {
921         // GIVEN unlocking with biometric is not allowed
922         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
923 
924         // THEN unlocking with fingerprint is not allowed
925         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
926                 BiometricSourceType.FINGERPRINT));
927     }
928 
929     @Test
testUnlockingWithFpAllowed_fingerprintLockout()930     public void testUnlockingWithFpAllowed_fingerprintLockout() {
931         // GIVEN unlocking with biometric is allowed
932         primaryAuthNotRequiredByStrongAuthTracker();
933 
934         // WHEN fingerprint is lock out
935         fingerprintErrorTemporaryLockOut();
936 
937         // THEN unlocking with fingerprint is not allowed
938         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
939                 BiometricSourceType.FINGERPRINT));
940     }
941 
942     @Test
trustAgentHasTrust()943     public void trustAgentHasTrust() {
944         // WHEN user has trust
945         mKeyguardUpdateMonitor.onTrustChanged(true, true,
946                 mSelectedUserInteractor.getSelectedUserId(), 0, null);
947 
948         // THEN user is considered as "having trust" and bouncer can be skipped
949         Assert.assertTrue(mKeyguardUpdateMonitor.getUserHasTrust(
950                 mSelectedUserInteractor.getSelectedUserId()));
951         Assert.assertTrue(mKeyguardUpdateMonitor.getUserCanSkipBouncer(
952                 mSelectedUserInteractor.getSelectedUserId()));
953     }
954 
955     @Test
testOnEnabledTrustAgentsChangedCallback()956     public void testOnEnabledTrustAgentsChangedCallback() {
957         final Random random = new Random();
958         final int userId = random.nextInt();
959         final KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
960 
961         mKeyguardUpdateMonitor.registerCallback(callback);
962         mKeyguardUpdateMonitor.onEnabledTrustAgentsChanged(userId);
963 
964         verify(callback).onEnabledTrustAgentsChanged(eq(userId));
965     }
966 
967     @Test
trustAgentHasTrust_fingerprintLockout()968     public void trustAgentHasTrust_fingerprintLockout() {
969         // GIVEN user has trust
970         mKeyguardUpdateMonitor.onTrustChanged(true, true,
971                 mSelectedUserInteractor.getSelectedUserId(), 0, null);
972         Assert.assertTrue(mKeyguardUpdateMonitor.getUserHasTrust(
973                 mSelectedUserInteractor.getSelectedUserId()));
974 
975         // WHEN fingerprint is lock out
976         fingerprintErrorTemporaryLockOut();
977 
978         // THEN user is NOT considered as "having trust" and bouncer cannot be skipped
979         Assert.assertFalse(mKeyguardUpdateMonitor.getUserHasTrust(
980                 mSelectedUserInteractor.getSelectedUserId()));
981         Assert.assertFalse(mKeyguardUpdateMonitor.getUserCanSkipBouncer(
982                 mSelectedUserInteractor.getSelectedUserId()));
983     }
984 
985     @Test
noFpListeningWhenKeyguardIsOccluded_unlessAlternateBouncerShowing()986     public void noFpListeningWhenKeyguardIsOccluded_unlessAlternateBouncerShowing() {
987         // GIVEN device is awake but occluded
988         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
989         mKeyguardUpdateMonitor.setKeyguardShowing(false, true);
990 
991         // THEN fingerprint shouldn't listen
992         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isFalse();
993         verifyFingerprintAuthenticateNeverCalled();
994         // WHEN alternate bouncer is shown
995         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
996         mKeyguardUpdateMonitor.setAlternateBouncerShowing(true);
997 
998         // THEN make sure FP listening begins
999         verifyFingerprintAuthenticateCall();
1000     }
1001 
1002     @Test
fpStopsListeningWhenBiometricPromptShows_resumesOnBpHidden()1003     public void fpStopsListeningWhenBiometricPromptShows_resumesOnBpHidden() {
1004         // verify AuthController.Callback is added:
1005         ArgumentCaptor<AuthController.Callback> captor = ArgumentCaptor.forClass(
1006                 AuthController.Callback.class);
1007         verify(mAuthController).addCallback(captor.capture());
1008         AuthController.Callback callback = captor.getValue();
1009 
1010         // GIVEN keyguard showing
1011         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1012         mKeyguardUpdateMonitor.setKeyguardShowing(true, false);
1013 
1014         // THEN fingerprint should listen
1015         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isTrue();
1016 
1017         // WHEN biometric prompt is shown
1018         callback.onBiometricPromptShown();
1019 
1020         // THEN shouldn't listen for fingerprint
1021         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isFalse();
1022 
1023         // WHEN biometric prompt is dismissed
1024         callback.onBiometricPromptDismissed();
1025 
1026         // THEN we should listen for fingerprint
1027         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isTrue();
1028     }
1029 
1030     @Test
testFingerprintPowerPressed_restartsFingerprintListeningStateWithDelay()1031     public void testFingerprintPowerPressed_restartsFingerprintListeningStateWithDelay() {
1032         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
1033                 .onAuthenticationError(FingerprintManager.BIOMETRIC_ERROR_POWER_PRESSED, "");
1034 
1035         // THEN doesn't authenticate immediately
1036         verifyFingerprintAuthenticateNeverCalled();
1037 
1038         // WHEN all messages (with delays) are processed
1039         mTestableLooper.moveTimeForward(HAL_POWER_PRESS_TIMEOUT);
1040         mTestableLooper.processAllMessages();
1041 
1042         // THEN fingerprint manager attempts to authenticate again
1043         verifyFingerprintAuthenticateCall();
1044     }
1045 
1046     @Test
testFaceAndFingerprintLockout_onlyFace()1047     public void testFaceAndFingerprintLockout_onlyFace() {
1048         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1049         mTestableLooper.processAllMessages();
1050         keyguardIsVisible();
1051 
1052         faceAuthLockOut();
1053 
1054         verify(mLockPatternUtils, never()).requireStrongAuth(anyInt(), anyInt());
1055     }
1056 
1057     @Test
testFaceAndFingerprintLockout_onlyFingerprint()1058     public void testFaceAndFingerprintLockout_onlyFingerprint() {
1059         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1060         mTestableLooper.processAllMessages();
1061         keyguardIsVisible();
1062 
1063         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
1064                 .onAuthenticationError(FINGERPRINT_ERROR_LOCKOUT_PERMANENT, "");
1065 
1066         verify(mLockPatternUtils).requireStrongAuth(anyInt(), anyInt());
1067     }
1068 
1069     @Test
testFaceAndFingerprintLockout()1070     public void testFaceAndFingerprintLockout() {
1071         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1072         mTestableLooper.processAllMessages();
1073         keyguardIsVisible();
1074 
1075         faceAuthLockOut();
1076         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
1077                 .onAuthenticationError(FINGERPRINT_ERROR_LOCKOUT_PERMANENT, "");
1078 
1079         verify(mLockPatternUtils).requireStrongAuth(anyInt(), anyInt());
1080     }
1081 
1082     @Test
testGetUserCanSkipBouncer_whenFace()1083     public void testGetUserCanSkipBouncer_whenFace() {
1084         int user = mSelectedUserInteractor.getSelectedUserId();
1085         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(true /* isClass3Biometric */))
1086                 .thenReturn(true);
1087         when(mFaceAuthInteractor.isFaceAuthStrong()).thenReturn(true);
1088         when(mFaceAuthInteractor.isAuthenticated()).thenReturn(MutableStateFlow(true));
1089 
1090         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
1091     }
1092 
1093     @Test
testGetUserCanSkipBouncer_whenFace_nonStrongAndDisallowed()1094     public void testGetUserCanSkipBouncer_whenFace_nonStrongAndDisallowed() {
1095         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(false /* isClass3Biometric */))
1096                 .thenReturn(false);
1097         int user = mSelectedUserInteractor.getSelectedUserId();
1098         when(mFaceAuthInteractor.isFaceAuthStrong()).thenReturn(false);
1099         when(mFaceAuthInteractor.isAuthenticated()).thenReturn(MutableStateFlow(true));
1100 
1101         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isFalse();
1102     }
1103 
1104     @Test
testGetUserCanSkipBouncer_whenFingerprint()1105     public void testGetUserCanSkipBouncer_whenFingerprint() {
1106         int user = mSelectedUserInteractor.getSelectedUserId();
1107         mKeyguardUpdateMonitor.onFingerprintAuthenticated(user, true /* isClass3Biometric */);
1108         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
1109     }
1110 
1111     @Test
testGetUserCanSkipBouncer_whenFingerprint_nonStrongAndDisallowed()1112     public void testGetUserCanSkipBouncer_whenFingerprint_nonStrongAndDisallowed() {
1113         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(false /* isClass3Biometric */))
1114                 .thenReturn(false);
1115         int user = mSelectedUserInteractor.getSelectedUserId();
1116         mKeyguardUpdateMonitor.onFingerprintAuthenticated(user, false /* isClass3Biometric */);
1117         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isFalse();
1118     }
1119 
1120     @Test
testBiometricsCleared_whenUserSwitches()1121     public void testBiometricsCleared_whenUserSwitches() {
1122         final BiometricAuthenticated dummyAuthentication =
1123                 new BiometricAuthenticated(true /* authenticated */, true /* strong */);
1124         mKeyguardUpdateMonitor.mUserFingerprintAuthenticated.put(0 /* user */, dummyAuthentication);
1125         assertThat(mKeyguardUpdateMonitor.mUserFingerprintAuthenticated.size()).isEqualTo(1);
1126 
1127         mKeyguardUpdateMonitor.handleUserSwitching(10 /* user */, () -> {
1128         });
1129         assertThat(mKeyguardUpdateMonitor.mUserFingerprintAuthenticated.size()).isEqualTo(0);
1130     }
1131 
1132     @Test
testMultiUserJankMonitor_whenUserSwitches()1133     public void testMultiUserJankMonitor_whenUserSwitches() {
1134         mKeyguardUpdateMonitor.handleUserSwitchComplete(10 /* user */);
1135         verify(mInteractionJankMonitor).end(InteractionJankMonitor.CUJ_USER_SWITCH);
1136         verify(mLatencyTracker).onActionEnd(LatencyTracker.ACTION_USER_SWITCH);
1137     }
1138 
1139     @Test
testMultiUserLockoutChanged_whenUserSwitches()1140     public void testMultiUserLockoutChanged_whenUserSwitches() {
1141         testMultiUserLockout_whenUserSwitches(BiometricConstants.BIOMETRIC_LOCKOUT_PERMANENT);
1142     }
1143 
1144     @Test
testMultiUserLockoutNotChanged_whenUserSwitches()1145     public void testMultiUserLockoutNotChanged_whenUserSwitches() {
1146         testMultiUserLockout_whenUserSwitches(BiometricConstants.BIOMETRIC_LOCKOUT_NONE);
1147     }
1148 
testMultiUserLockout_whenUserSwitches( @iometricConstants.LockoutMode int fingerprintLockoutMode)1149     private void testMultiUserLockout_whenUserSwitches(
1150             @BiometricConstants.LockoutMode int fingerprintLockoutMode) {
1151         final int newUser = 12;
1152         final boolean fpLockOut =
1153                 fingerprintLockoutMode != BiometricConstants.BIOMETRIC_LOCKOUT_NONE;
1154 
1155         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1156         mTestableLooper.processAllMessages();
1157         keyguardIsVisible();
1158 
1159         verifyFingerprintAuthenticateCall();
1160 
1161         when(mFingerprintManager.getLockoutModeForUser(eq(FINGERPRINT_SENSOR_ID), eq(newUser)))
1162                 .thenReturn(fingerprintLockoutMode);
1163         final CancellationSignal fpCancel = spy(mKeyguardUpdateMonitor.mFingerprintCancelSignal);
1164         mKeyguardUpdateMonitor.mFingerprintCancelSignal = fpCancel;
1165         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1166         mKeyguardUpdateMonitor.registerCallback(callback);
1167 
1168         mKeyguardUpdateMonitor.handleUserSwitchComplete(newUser);
1169         mTestableLooper.processAllMessages();
1170 
1171         // THEN fingerprint listening are always cancelled immediately
1172         verify(fpCancel).cancel();
1173         verify(callback).onBiometricRunningStateChanged(
1174                 eq(false), eq(BiometricSourceType.FINGERPRINT));
1175 
1176         // THEN locked out states are updated
1177         assertThat(mKeyguardUpdateMonitor.isFingerprintLockedOut()).isEqualTo(fpLockOut);
1178 
1179         // Fingerprint should be cancelled on lockout if going to lockout state, else
1180         // restarted if it's not
1181         assertThat(mKeyguardUpdateMonitor.mFingerprintRunningState)
1182                 .isEqualTo(BIOMETRIC_STATE_CANCELLING_RESTARTING);
1183     }
1184 
1185     @Test
testGetUserCanSkipBouncer_whenTrust()1186     public void testGetUserCanSkipBouncer_whenTrust() {
1187         int user = mSelectedUserInteractor.getSelectedUserId();
1188         mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, true /* newlyUnlocked */,
1189                 user, 0 /* flags */, new ArrayList<>());
1190         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
1191     }
1192 
1193     @Test
testGetSubscriptionInfo_whenInGroupedSubWithOpportunistic()1194     public void testGetSubscriptionInfo_whenInGroupedSubWithOpportunistic() {
1195         List<SubscriptionInfo> list = new ArrayList<>();
1196         list.add(TEST_SUBSCRIPTION);
1197         list.add(TEST_SUBSCRIPTION_2);
1198         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
1199         mKeyguardUpdateMonitor.mPhoneStateListener.onActiveDataSubscriptionIdChanged(
1200                 TEST_SUBSCRIPTION_2.getSubscriptionId());
1201         mTestableLooper.processAllMessages();
1202 
1203         List<SubscriptionInfo> listToVerify = mKeyguardUpdateMonitor
1204                 .getFilteredSubscriptionInfo();
1205         assertThat(listToVerify.size()).isEqualTo(1);
1206         assertThat(listToVerify.get(0)).isEqualTo(TEST_SUBSCRIPTION_2);
1207     }
1208 
1209     @Test
testActiveSubscriptionBecomesInactive()1210     public void testActiveSubscriptionBecomesInactive() {
1211         List<SubscriptionInfo> list = new ArrayList<>();
1212         list.add(TEST_SUBSCRIPTION);
1213         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
1214         mKeyguardUpdateMonitor.mPhoneStateListener.onActiveDataSubscriptionIdChanged(
1215                 TEST_SUBSCRIPTION.getSubscriptionId());
1216         mTestableLooper.processAllMessages();
1217         assertThat(mKeyguardUpdateMonitor.mSimDatas.get(TEST_SUBSCRIPTION.getSubscriptionId()))
1218                 .isNotNull();
1219 
1220         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
1221                 .thenReturn(new ArrayList<>());
1222         mKeyguardUpdateMonitor.mPhoneStateListener.onActiveDataSubscriptionIdChanged(
1223                 SubscriptionManager.INVALID_SUBSCRIPTION_ID);
1224         mTestableLooper.processAllMessages();
1225 
1226         assertThat(mKeyguardUpdateMonitor.mSimDatas.get(TEST_SUBSCRIPTION.getSubscriptionId()))
1227                 .isNull();
1228         assertThat(mKeyguardUpdateMonitor.mSimDatas.get(
1229                 SubscriptionManager.INVALID_SUBSCRIPTION_ID)).isNull();
1230     }
1231 
1232     @Test
testActiveSubscriptionList_filtersProvisioningNetworks()1233     public void testActiveSubscriptionList_filtersProvisioningNetworks() {
1234         List<SubscriptionInfo> list = new ArrayList<>();
1235         list.add(TEST_SUBSCRIPTION_PROVISIONING);
1236         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
1237         mKeyguardUpdateMonitor.mSubscriptionListener.onSubscriptionsChanged();
1238 
1239         assertThat(mKeyguardUpdateMonitor.getSubscriptionInfo(true)).isEmpty();
1240 
1241         SubscriptionInfo.Builder b = new SubscriptionInfo.Builder(TEST_SUBSCRIPTION_PROVISIONING);
1242         b.setProfileClass(PROFILE_CLASS_DEFAULT);
1243         SubscriptionInfo validInfo = b.build();
1244 
1245         list.clear();
1246         list.add(validInfo);
1247         mKeyguardUpdateMonitor.mSubscriptionListener.onSubscriptionsChanged();
1248 
1249         assertThat(mKeyguardUpdateMonitor.getSubscriptionInfo(true)).hasSize(1);
1250     }
1251 
1252     @Test
testActiveSubscriptionList_filtersProvisioningNetworks_untilValid()1253     public void testActiveSubscriptionList_filtersProvisioningNetworks_untilValid() {
1254         List<SubscriptionInfo> list = new ArrayList<>();
1255         list.add(TEST_SUBSCRIPTION_PROVISIONING);
1256         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
1257         mKeyguardUpdateMonitor.mSubscriptionListener.onSubscriptionsChanged();
1258 
1259         assertThat(mKeyguardUpdateMonitor.getSubscriptionInfo(true)).isEmpty();
1260 
1261     }
1262 
1263     @Test
testIsUserUnlocked()1264     public void testIsUserUnlocked() {
1265         // mUserManager will report the user as unlocked on @Before
1266         assertThat(
1267                 mKeyguardUpdateMonitor.isUserUnlocked(mSelectedUserInteractor.getSelectedUserId()))
1268                 .isTrue();
1269         // Invalid user should not be unlocked.
1270         int randomUser = 99;
1271         assertThat(mKeyguardUpdateMonitor.isUserUnlocked(randomUser)).isFalse();
1272     }
1273 
1274     @Test
testTrustUsuallyManaged_whenTrustChanges()1275     public void testTrustUsuallyManaged_whenTrustChanges() {
1276         int user = mSelectedUserInteractor.getSelectedUserId();
1277         when(mTrustManager.isTrustUsuallyManaged(eq(user))).thenReturn(true);
1278         mKeyguardUpdateMonitor.onTrustManagedChanged(false /* managed */, user);
1279         assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isTrue();
1280     }
1281 
1282     @Test
testTrustUsuallyManaged_resetWhenUserIsRemoved()1283     public void testTrustUsuallyManaged_resetWhenUserIsRemoved() {
1284         int user = mSelectedUserInteractor.getSelectedUserId();
1285         when(mTrustManager.isTrustUsuallyManaged(eq(user))).thenReturn(true);
1286         mKeyguardUpdateMonitor.onTrustManagedChanged(false /* managed */, user);
1287         assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isTrue();
1288 
1289         mKeyguardUpdateMonitor.handleUserRemoved(user);
1290         assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isFalse();
1291     }
1292 
1293     @Test
testSecondaryLockscreenRequirement()1294     public void testSecondaryLockscreenRequirement() {
1295         when(mSelectedUserInteractor.getSelectedUserId()).thenReturn(UserHandle.myUserId());
1296         when(mUserTracker.getUserId()).thenReturn(UserHandle.myUserId());
1297         int user = mSelectedUserInteractor.getSelectedUserId();
1298         String packageName = "fake.test.package";
1299         String cls = "FakeService";
1300         ServiceInfo serviceInfo = new ServiceInfo();
1301         serviceInfo.packageName = packageName;
1302         serviceInfo.name = cls;
1303         ResolveInfo resolveInfo = new ResolveInfo();
1304         resolveInfo.serviceInfo = serviceInfo;
1305         when(mPackageManager.resolveService(any(Intent.class), eq(0))).thenReturn(resolveInfo);
1306         when(mDevicePolicyManager.isSecondaryLockscreenEnabled(eq(UserHandle.of(user))))
1307                 .thenReturn(true, false);
1308         when(mDevicePolicyManager.getProfileOwnerOrDeviceOwnerSupervisionComponent(
1309                 UserHandle.of(user)))
1310                 .thenReturn(new ComponentName(packageName, cls));
1311 
1312         // Initially null.
1313         assertThat(mKeyguardUpdateMonitor.getSecondaryLockscreenRequirement(user)).isNull();
1314 
1315         // Set non-null after DPM change.
1316         setBroadcastReceiverPendingResult(mKeyguardUpdateMonitor.mBroadcastAllReceiver);
1317         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1318         mKeyguardUpdateMonitor.mBroadcastAllReceiver.onReceive(getContext(), intent);
1319         mTestableLooper.processAllMessages();
1320 
1321         Intent storedIntent = mKeyguardUpdateMonitor.getSecondaryLockscreenRequirement(user);
1322         assertThat(storedIntent.getComponent().getClassName()).isEqualTo(cls);
1323         assertThat(storedIntent.getComponent().getPackageName()).isEqualTo(packageName);
1324 
1325         // Back to null after another DPM change.
1326         mKeyguardUpdateMonitor.mBroadcastAllReceiver.onReceive(getContext(), intent);
1327         mTestableLooper.processAllMessages();
1328         assertThat(mKeyguardUpdateMonitor.getSecondaryLockscreenRequirement(user)).isNull();
1329     }
1330 
1331     @Test
testRegisterAuthControllerCallback()1332     public void testRegisterAuthControllerCallback() {
1333         assertThat(mKeyguardUpdateMonitor.isUdfpsEnrolled()).isFalse();
1334 
1335         // verify AuthController.Callback is added:
1336         ArgumentCaptor<AuthController.Callback> captor = ArgumentCaptor.forClass(
1337                 AuthController.Callback.class);
1338         verify(mAuthController).addCallback(captor.capture());
1339         AuthController.Callback callback = captor.getValue();
1340 
1341         // WHEN udfps is now enrolled
1342         when(mAuthController.isUdfpsEnrolled(anyInt())).thenReturn(true);
1343         callback.onEnrollmentsChanged(TYPE_FINGERPRINT);
1344 
1345         // THEN isUdfspEnrolled is TRUE
1346         assertThat(mKeyguardUpdateMonitor.isUdfpsEnrolled()).isTrue();
1347     }
1348 
1349 
1350     @Test
testStartUdfpsServiceBeginsOnKeyguard()1351     public void testStartUdfpsServiceBeginsOnKeyguard() {
1352         // GIVEN
1353         // - status bar state is on the keyguard
1354         // - user has authenticated since boot
1355         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1356         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1357 
1358         // THEN we should listen for udfps
1359         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1360     }
1361 
1362     @Test
listenForFingerprint_whenOccludingAppPkgOnAllowlist()1363     public void listenForFingerprint_whenOccludingAppPkgOnAllowlist()
1364             throws RemoteException {
1365         // GIVEN keyguard isn't visible (app occluding)
1366         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1367         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1368         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1369 
1370         // GIVEN the top activity is from a package that allows fingerprint listening over its
1371         // occluding activities
1372         setTopStandardActivity(PKG_ALLOWING_FP_LISTEN_ON_OCCLUDING_ACTIVITY);
1373         onTaskStackChanged();
1374 
1375         // THEN we SHOULD listen for non-UDFPS fingerprint
1376         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(true);
1377 
1378         // THEN we should listen for udfps (hiding mechanism to actually auth is
1379         // controlled by UdfpsKeyguardViewController)
1380         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1381     }
1382 
1383     @Test
doNotListenForFingerprint_whenOccludingAppPkgNotOnAllowlist()1384     public void doNotListenForFingerprint_whenOccludingAppPkgNotOnAllowlist()
1385             throws RemoteException {
1386         // GIVEN keyguard isn't visible (app occluding)
1387         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1388         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1389         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1390 
1391         // GIVEN top activity is not in the allowlist for listening to fp over occluding activities
1392         setTopStandardActivity("notInAllowList");
1393 
1394         // THEN we should not listen for non-UDFPS fingerprint
1395         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(false);
1396 
1397         // THEN we should listen for udfps (hiding mechanism to actually auth is
1398         // controlled by UdfpsKeyguardViewController)
1399         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1400     }
1401 
1402     @Test
testOccludingAppFingerprintListeningState()1403     public void testOccludingAppFingerprintListeningState() {
1404         // GIVEN keyguard isn't visible (app occluding)
1405         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1406         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1407         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1408 
1409         // THEN we shouldn't listen for fingerprints
1410         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(false);
1411 
1412         // THEN we should listen for udfps (hiding of mechanism to actually auth is
1413         // controlled by UdfpsKeyguardViewController)
1414         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1415     }
1416 
1417     @Test
testOccludingAppRequestsFingerprint()1418     public void testOccludingAppRequestsFingerprint() {
1419         // GIVEN keyguard isn't visible (app occluding)
1420         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1421         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1422 
1423         // WHEN an occluding app requests fp
1424         mKeyguardUpdateMonitor.requestFingerprintAuthOnOccludingApp(true);
1425 
1426         // THEN we should listen for fingerprints
1427         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(true);
1428 
1429         // WHEN an occluding app stops requesting fp
1430         mKeyguardUpdateMonitor.requestFingerprintAuthOnOccludingApp(false);
1431 
1432         // THEN we shouldn't listen for fingeprints
1433         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(false);
1434     }
1435 
1436     @Test
testStartUdfpsServiceNoAuthenticationSinceLastBoot()1437     public void testStartUdfpsServiceNoAuthenticationSinceLastBoot() {
1438         // GIVEN status bar state is on the keyguard
1439         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1440 
1441         // WHEN user hasn't authenticated since last boot, cannot unlock with FP
1442         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
1443 
1444         // THEN we shouldn't listen for udfps
1445         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(false);
1446     }
1447 
1448     @Test
testStartUdfpsServiceStrongAuthRequiredAfterTimeout()1449     public void testStartUdfpsServiceStrongAuthRequiredAfterTimeout() {
1450         // GIVEN status bar state is on the keyguard
1451         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1452 
1453         // WHEN user loses smart unlock trust
1454         when(mStrongAuthTracker.getStrongAuthForUser(mSelectedUserInteractor.getSelectedUserId()))
1455                 .thenReturn(SOME_AUTH_REQUIRED_AFTER_USER_REQUEST);
1456 
1457         // THEN we should still listen for udfps
1458         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1459     }
1460 
1461     @Test
testShouldNotListenForUdfps_whenTrustEnabled()1462     public void testShouldNotListenForUdfps_whenTrustEnabled() {
1463         // GIVEN a "we should listen for udfps" state
1464         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1465         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1466 
1467         // WHEN trust is enabled (ie: via smartlock)
1468         mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, true /* newlyUnlocked */,
1469                 mSelectedUserInteractor.getSelectedUserId(), 0 /* flags */, new ArrayList<>());
1470 
1471         // THEN we shouldn't listen for udfps
1472         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(false);
1473     }
1474 
1475     @Test
testShouldNotListenForUdfps_whenFaceAuthenticated()1476     public void testShouldNotListenForUdfps_whenFaceAuthenticated() {
1477         // GIVEN a "we should listen for udfps" state
1478         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1479         when(mFaceAuthInteractor.isFaceAuthEnabledAndEnrolled()).thenReturn(true);
1480         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1481 
1482         // WHEN face authenticated
1483         when(mFaceAuthInteractor.isAuthenticated()).thenReturn(MutableStateFlow(true));
1484 
1485         // THEN we shouldn't listen for udfps
1486         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(false);
1487     }
1488 
1489     @Test
testShouldNotListenForUdfps_whenInLockDown()1490     public void testShouldNotListenForUdfps_whenInLockDown() {
1491         // GIVEN a "we should listen for udfps" state
1492         setKeyguardBouncerVisibility(false /* isVisible */);
1493         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1494         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1495 
1496         // WHEN device in lock down
1497         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
1498 
1499         // THEN we shouldn't listen for udfps
1500         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(false);
1501     }
1502 
1503     @Test
testRequireUnlockForNfc_Broadcast()1504     public void testRequireUnlockForNfc_Broadcast() {
1505         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1506         mKeyguardUpdateMonitor.registerCallback(callback);
1507         Intent intent = new Intent(NfcAdapter.ACTION_REQUIRE_UNLOCK_FOR_NFC);
1508         mKeyguardUpdateMonitor.mBroadcastAllReceiver.onReceive(getContext(), intent);
1509         mTestableLooper.processAllMessages();
1510 
1511         verify(callback, atLeastOnce()).onRequireUnlockForNfc();
1512     }
1513 
1514     @Test
testShowTrustGrantedMessage_onTrustGranted()1515     public void testShowTrustGrantedMessage_onTrustGranted() {
1516         // WHEN trust is enabled (ie: via some trust agent) with a trustGranted string
1517         mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, true /* newlyUnlocked */,
1518                 mSelectedUserInteractor.getSelectedUserId(), 0 /* flags */,
1519                 Arrays.asList("Unlocked by wearable"));
1520 
1521         // THEN the showTrustGrantedMessage should be called with the first message
1522         verify(mTestCallback).onTrustGrantedForCurrentUser(
1523                 anyBoolean() /* dismissKeyguard */,
1524                 eq(true) /* newlyUnlocked */,
1525                 eq(new TrustGrantFlags(0)),
1526                 eq("Unlocked by wearable"));
1527     }
1528 
1529     @Test
testFingerprintCanAuth_whenCancellationNotReceivedAndAuthFailed()1530     public void testFingerprintCanAuth_whenCancellationNotReceivedAndAuthFailed() {
1531         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1532         mTestableLooper.processAllMessages();
1533         keyguardIsVisible();
1534 
1535         verifyFingerprintAuthenticateCall();
1536 
1537         when(mFaceAuthInteractor.isAuthenticated()).thenReturn(MutableStateFlow(true));
1538         when(mFaceAuthInteractor.isFaceAuthStrong()).thenReturn(false);
1539         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(false /* isClass3Biometric */))
1540                 .thenReturn(false);
1541         // Make sure keyguard is going away after face auth attempt, and that it calls
1542         // updateBiometricStateListeningState.
1543         mKeyguardUpdateMonitor.setKeyguardShowing(false, false);
1544         mTestableLooper.processAllMessages();
1545 
1546         verify(mHandler).postDelayed(mKeyguardUpdateMonitor.mFpCancelNotReceived,
1547                 DEFAULT_CANCEL_SIGNAL_TIMEOUT);
1548         mKeyguardUpdateMonitor.onFingerprintAuthenticated(0, true);
1549         mTestableLooper.processAllMessages();
1550 
1551         verify(mHandler, times(1)).removeCallbacks(mKeyguardUpdateMonitor.mFpCancelNotReceived);
1552         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
1553         mTestableLooper.processAllMessages();
1554         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(true);
1555         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1556     }
1557 
1558     @Test
testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_deviceInteractive()1559     public void testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_deviceInteractive() {
1560         // GIVEN device is interactive
1561         deviceIsInteractive();
1562 
1563         // GIVEN callback is registered
1564         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1565         mKeyguardUpdateMonitor.registerCallback(callback);
1566 
1567         // WHEN onTrustChanged with TRUST_DISMISS_KEYGUARD flag
1568         mKeyguardUpdateMonitor.onTrustChanged(
1569                 true /* enabled */,
1570                 true /* newlyUnlocked */,
1571                 mSelectedUserInteractor.getSelectedUserId() /* userId */,
1572                 TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD /* flags */,
1573                 null /* trustGrantedMessages */);
1574 
1575         // THEN onTrustGrantedForCurrentUser callback called
1576         verify(callback).onTrustGrantedForCurrentUser(
1577                 eq(true) /* dismissKeyguard */,
1578                 eq(true) /* newlyUnlocked */,
1579                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD)),
1580                 eq(null) /* message */
1581         );
1582     }
1583 
1584     @Test
testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_doesNotDismiss()1585     public void testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_doesNotDismiss() {
1586         // GIVEN device is NOT interactive
1587 
1588         // GIVEN callback is registered
1589         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1590         mKeyguardUpdateMonitor.registerCallback(callback);
1591 
1592         // WHEN onTrustChanged with TRUST_DISMISS_KEYGUARD flag
1593         mKeyguardUpdateMonitor.onTrustChanged(
1594                 true /* enabled */,
1595                 true /* newlyUnlocked */,
1596                 mSelectedUserInteractor.getSelectedUserId() /* userId */,
1597                 TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD /* flags */,
1598                 null /* trustGrantedMessages */);
1599 
1600         // THEN onTrustGrantedForCurrentUser callback called
1601         verify(callback).onTrustGrantedForCurrentUser(
1602                 eq(false) /* dismissKeyguard */,
1603                 eq(true) /* newlyUnlocked */,
1604                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD)),
1605                 eq(null) /* message */
1606         );
1607     }
1608 
1609     @Test
testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_temporaryAndRenewable()1610     public void testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_temporaryAndRenewable() {
1611         // GIVEN device is interactive
1612         deviceIsInteractive();
1613 
1614         // GIVEN callback is registered
1615         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1616         mKeyguardUpdateMonitor.registerCallback(callback);
1617 
1618         // WHEN onTrustChanged for a different user
1619         mKeyguardUpdateMonitor.onTrustChanged(
1620                 true /* enabled */,
1621                 true /* newlyUnlocked */,
1622                 546 /* userId, not the current userId */,
1623                 0 /* flags */,
1624                 null /* trustGrantedMessages */);
1625 
1626         // THEN onTrustGrantedForCurrentUser callback called
1627         verify(callback, never()).onTrustGrantedForCurrentUser(
1628                 anyBoolean() /* dismissKeyguard */,
1629                 eq(true) /* newlyUnlocked */,
1630                 anyObject() /* flags */,
1631                 anyString() /* message */
1632         );
1633     }
1634 
1635     @Test
testOnTrustGranted_differentUser_noCallback()1636     public void testOnTrustGranted_differentUser_noCallback() {
1637         // GIVEN device is interactive
1638 
1639         // GIVEN callback is registered
1640         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1641         mKeyguardUpdateMonitor.registerCallback(callback);
1642 
1643         // WHEN onTrustChanged with TRUST_DISMISS_KEYGUARD AND TRUST_TEMPORARY_AND_RENEWABLE
1644         // flags (temporary & rewable is active unlock)
1645         mKeyguardUpdateMonitor.onTrustChanged(
1646                 true /* enabled */,
1647                 true /* newlyUnlocked */,
1648                 mSelectedUserInteractor.getSelectedUserId() /* userId */,
1649                 TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD
1650                         | TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE /* flags */,
1651                 null /* trustGrantedMessages */);
1652 
1653         // THEN onTrustGrantedForCurrentUser callback called
1654         verify(callback).onTrustGrantedForCurrentUser(
1655                 eq(true) /* dismissKeyguard */,
1656                 eq(true) /* newlyUnlocked */,
1657                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD
1658                         | TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE)),
1659                 eq(null) /* message */
1660         );
1661     }
1662 
1663     @Test
testOnTrustGrantedForCurrentUser_bouncerShowing_initiatedByUser()1664     public void testOnTrustGrantedForCurrentUser_bouncerShowing_initiatedByUser() {
1665         // GIVEN device is interactive & bouncer is showing
1666         deviceIsInteractive();
1667         bouncerFullyVisible();
1668 
1669         // GIVEN callback is registered
1670         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1671         mKeyguardUpdateMonitor.registerCallback(callback);
1672 
1673         // WHEN onTrustChanged with INITIATED_BY_USER flag
1674         mKeyguardUpdateMonitor.onTrustChanged(
1675                 true /* enabled */,
1676                 true /* newlyUnlocked */,
1677                 mSelectedUserInteractor.getSelectedUserId() /* userId, not the current userId */,
1678                 TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER /* flags */,
1679                 null /* trustGrantedMessages */);
1680 
1681         // THEN onTrustGrantedForCurrentUser callback called
1682         verify(callback, never()).onTrustGrantedForCurrentUser(
1683                 eq(true) /* dismissKeyguard */,
1684                 eq(true) /* newlyUnlocked */,
1685                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER)),
1686                 anyString() /* message */
1687         );
1688     }
1689 
1690     @Test
testOnTrustGrantedForCurrentUser_bouncerShowing_temporaryRenewable()1691     public void testOnTrustGrantedForCurrentUser_bouncerShowing_temporaryRenewable() {
1692         // GIVEN device is NOT interactive & bouncer is showing
1693         bouncerFullyVisible();
1694 
1695         // GIVEN callback is registered
1696         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1697         mKeyguardUpdateMonitor.registerCallback(callback);
1698 
1699         // WHEN onTrustChanged with INITIATED_BY_USER flag
1700         mKeyguardUpdateMonitor.onTrustChanged(
1701                 true /* enabled */,
1702                 true /* newlyUnlocked */,
1703                 mSelectedUserInteractor.getSelectedUserId() /* userId, not the current userId */,
1704                 TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER
1705                         | TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE /* flags */,
1706                 null /* trustGrantedMessages */);
1707 
1708         // THEN onTrustGrantedForCurrentUser callback called
1709         verify(callback, never()).onTrustGrantedForCurrentUser(
1710                 eq(true) /* dismissKeyguard */,
1711                 eq(true) /* newlyUnlocked */,
1712                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER
1713                         | TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE)),
1714                 anyString() /* message */
1715         );
1716     }
1717 
1718     @Test
testStrongAuthChange_lockDown_stopsFpListeningState()1719     public void testStrongAuthChange_lockDown_stopsFpListeningState() {
1720         // GIVEN device is listening for fingerprint
1721         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1722         mTestableLooper.processAllMessages();
1723         keyguardIsVisible();
1724 
1725         verifyFingerprintAuthenticateCall();
1726 
1727         final CancellationSignal fpCancel = spy(mKeyguardUpdateMonitor.mFingerprintCancelSignal);
1728         mKeyguardUpdateMonitor.mFingerprintCancelSignal = fpCancel;
1729         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1730         mKeyguardUpdateMonitor.registerCallback(callback);
1731 
1732         // WHEN strong auth changes and device is in user lockdown
1733         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
1734         userDeviceLockDown();
1735         mKeyguardUpdateMonitor.notifyStrongAuthAllowedChanged(
1736                 mSelectedUserInteractor.getSelectedUserId());
1737         mTestableLooper.processAllMessages();
1738 
1739         // THEN fingerprint listening are cancelled
1740         verify(fpCancel).cancel();
1741         verify(callback).onBiometricRunningStateChanged(
1742                 eq(false), eq(BiometricSourceType.FINGERPRINT));
1743     }
1744 
1745     @Test
assistantVisible_requestActiveUnlock()1746     public void assistantVisible_requestActiveUnlock() {
1747         // GIVEN active unlock requests from the assistant are allowed
1748         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
1749                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.ASSISTANT)).thenReturn(true);
1750 
1751         // GIVEN should trigger active unlock
1752         keyguardIsVisible();
1753         keyguardNotGoingAway();
1754         statusBarShadeIsNotLocked();
1755         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
1756                 true);
1757 
1758         // WHEN the assistant is visible
1759         mKeyguardUpdateMonitor.setAssistantVisible(true);
1760 
1761         // THEN request unlock with keyguard dismissal
1762         verify(mTrustManager).reportUserRequestedUnlock(
1763                 eq(mSelectedUserInteractor.getSelectedUserId()),
1764                 eq(true));
1765     }
1766 
1767     @Test
assistantVisible_sendEventToFaceAuthInteractor()1768     public void assistantVisible_sendEventToFaceAuthInteractor() {
1769         // WHEN the assistant is visible
1770         mKeyguardUpdateMonitor.setAssistantVisible(true);
1771 
1772         // THEN send event to face auth interactor
1773         verify(mFaceAuthInteractor).onAssistantTriggeredOnLockScreen();
1774     }
1775 
1776     @Test
assistantNotVisible_doesNotSendEventToFaceAuthInteractor()1777     public void assistantNotVisible_doesNotSendEventToFaceAuthInteractor() {
1778         // WHEN the assistant is visible
1779         mKeyguardUpdateMonitor.setAssistantVisible(false);
1780 
1781         // THEN never send event to face auth interactor
1782         verify(mFaceAuthInteractor, never()).onAssistantTriggeredOnLockScreen();
1783     }
1784 
1785     @Test
fingerprintFailure_requestActiveUnlock_dismissKeyguard()1786     public void fingerprintFailure_requestActiveUnlock_dismissKeyguard() {
1787         // GIVEN shouldTriggerActiveUnlock
1788         bouncerFullyVisible();
1789         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
1790                 true);
1791 
1792         // GIVEN active unlock triggers on biometric failures
1793         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
1794                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL))
1795                 .thenReturn(true);
1796 
1797         // WHEN fingerprint fails
1798         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback.onAuthenticationFailed();
1799 
1800         // ALWAYS request unlock with a keyguard dismissal
1801         verify(mTrustManager).reportUserRequestedUnlock(
1802                 eq(mSelectedUserInteractor.getSelectedUserId()),
1803                 eq(true));
1804     }
1805 
1806     @Test
faceNonBypassFailure_requestActiveUnlock_doesNotDismissKeyguard()1807     public void faceNonBypassFailure_requestActiveUnlock_doesNotDismissKeyguard() {
1808         // GIVEN shouldTriggerActiveUnlock
1809         when(mAuthController.isUdfpsFingerDown()).thenReturn(false);
1810         keyguardIsVisible();
1811         keyguardNotGoingAway();
1812         statusBarShadeIsNotLocked();
1813         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
1814                 true);
1815 
1816         // GIVEN active unlock triggers on biometric failures
1817         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
1818                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL))
1819                 .thenReturn(true);
1820 
1821         // WHEN face fails & bypass is not allowed
1822         lockscreenBypassIsNotAllowed();
1823         mFaceAuthenticationListener.getValue().onAuthenticationStatusChanged(
1824                 new FailedFaceAuthenticationStatus());
1825 
1826         // THEN request unlock with NO keyguard dismissal
1827         verify(mTrustManager).reportUserRequestedUnlock(
1828                 eq(mSelectedUserInteractor.getSelectedUserId()),
1829                 eq(false));
1830     }
1831 
1832     @Test
faceBypassFailure_requestActiveUnlock_dismissKeyguard()1833     public void faceBypassFailure_requestActiveUnlock_dismissKeyguard() {
1834         // GIVEN shouldTriggerActiveUnlock
1835         when(mAuthController.isUdfpsFingerDown()).thenReturn(false);
1836         when(mFaceAuthInteractor.isFaceAuthEnabledAndEnrolled()).thenReturn(true);
1837         keyguardIsVisible();
1838         keyguardNotGoingAway();
1839         statusBarShadeIsNotLocked();
1840         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
1841                 true);
1842 
1843         // GIVEN active unlock triggers on biometric failures
1844         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
1845                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL))
1846                 .thenReturn(true);
1847 
1848         // WHEN face fails & bypass is not allowed
1849         lockscreenBypassIsAllowed();
1850         mFaceAuthenticationListener.getValue().onAuthenticationStatusChanged(
1851                 new FailedFaceAuthenticationStatus());
1852 
1853         // THEN request unlock with a keyguard dismissal
1854         verify(mTrustManager).reportUserRequestedUnlock(
1855                 eq(mSelectedUserInteractor.getSelectedUserId()),
1856                 eq(true));
1857     }
1858 
1859     @Test
faceNonBypassFailure_requestActiveUnlock_dismissKeyguard()1860     public void faceNonBypassFailure_requestActiveUnlock_dismissKeyguard() {
1861         // GIVEN shouldTriggerActiveUnlock
1862         when(mAuthController.isUdfpsFingerDown()).thenReturn(false);
1863         when(mFaceAuthInteractor.isFaceAuthEnabledAndEnrolled()).thenReturn(true);
1864         lockscreenBypassIsNotAllowed();
1865         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
1866                 true);
1867 
1868         // GIVEN active unlock triggers on biometric failures
1869         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
1870                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL))
1871                 .thenReturn(true);
1872 
1873         // WHEN face fails & on the bouncer
1874         bouncerFullyVisible();
1875         mFaceAuthenticationListener.getValue().onAuthenticationStatusChanged(
1876                 new FailedFaceAuthenticationStatus());
1877 
1878         // THEN request unlock with a keyguard dismissal
1879         verify(mTrustManager).reportUserRequestedUnlock(
1880                 eq(mSelectedUserInteractor.getSelectedUserId()),
1881                 eq(true));
1882     }
1883 
1884     @Test
testBatteryChangedIntent_refreshBatteryInfo()1885     public void testBatteryChangedIntent_refreshBatteryInfo() {
1886         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(mContext, getBatteryIntent());
1887 
1888         BatteryStatus status = verifyRefreshBatteryInfo();
1889         assertThat(status.incompatibleCharger.get()).isFalse();
1890         assertThat(mKeyguardUpdateMonitor.mIncompatibleCharger).isFalse();
1891     }
1892 
1893     @Test
testUsbComplianceIntent_refreshBatteryInfo()1894     public void testUsbComplianceIntent_refreshBatteryInfo() {
1895         Context contextSpy = getSpyContext();
1896 
1897         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(
1898                 contextSpy, new Intent(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED));
1899 
1900         mTestableLooper.processAllMessages();
1901         assertThat(mKeyguardUpdateMonitor.mIncompatibleCharger).isFalse();
1902     }
1903 
1904     @Test
testUsbComplianceIntent_refreshBatteryInfoWithIncompatibleCharger()1905     public void testUsbComplianceIntent_refreshBatteryInfoWithIncompatibleCharger() {
1906         Context contextSpy = getSpyContext();
1907         setupIncompatibleCharging();
1908 
1909         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(
1910                 contextSpy, new Intent(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED));
1911 
1912         mTestableLooper.processAllMessages();
1913         assertThat(mKeyguardUpdateMonitor.mIncompatibleCharger).isTrue();
1914     }
1915 
1916     @Test
unfoldWakeup_requestActiveUnlock_forceDismissKeyguard()1917     public void unfoldWakeup_requestActiveUnlock_forceDismissKeyguard() {
1918         // GIVEN shouldTriggerActiveUnlock
1919         keyguardIsVisible();
1920         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
1921                 true);
1922 
1923         // GIVEN active unlock triggers on wakeup
1924         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
1925                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE))
1926                 .thenReturn(true);
1927 
1928         // GIVEN an unfold should force dismiss the keyguard
1929         when(mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(
1930                 PowerManager.WAKE_REASON_UNFOLD_DEVICE)).thenReturn(true);
1931 
1932         // WHEN device wakes up from an unfold
1933         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_UNFOLD_DEVICE);
1934         mTestableLooper.processAllMessages();
1935 
1936         // THEN request unlock with a keyguard dismissal
1937         verify(mTrustManager).reportUserRequestedUnlock(
1938                 eq(mSelectedUserInteractor.getSelectedUserId()),
1939                 eq(true));
1940     }
1941 
1942     @Test
unfoldWakeup_requestActiveUnlock_noDismissKeyguard()1943     public void unfoldWakeup_requestActiveUnlock_noDismissKeyguard() {
1944         // GIVEN shouldTriggerActiveUnlock on wake from UNFOLD_DEVICE
1945         keyguardIsVisible();
1946         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
1947                 true);
1948 
1949         // GIVEN active unlock triggers on wakeup
1950         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
1951                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE))
1952                 .thenReturn(true);
1953 
1954         // GIVEN an unfold should NOT force dismiss the keyguard
1955         when(mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(
1956                 PowerManager.WAKE_REASON_UNFOLD_DEVICE)).thenReturn(false);
1957 
1958         // WHEN device wakes up from an unfold
1959         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_UNFOLD_DEVICE);
1960         mTestableLooper.processAllMessages();
1961 
1962         // THEN request unlock WITHOUT a keyguard dismissal
1963         verify(mTrustManager).reportUserRequestedUnlock(
1964                 eq(mSelectedUserInteractor.getSelectedUserId()),
1965                 eq(false));
1966     }
1967 
1968     @Test
unfoldFromPostureChange_requestActiveUnlock_forceDismissKeyguard()1969     public void unfoldFromPostureChange_requestActiveUnlock_forceDismissKeyguard() {
1970         // GIVEN shouldTriggerActiveUnlock
1971         keyguardIsVisible();
1972         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
1973                 true);
1974 
1975         // GIVEN active unlock triggers on wakeup
1976         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
1977                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE))
1978                 .thenReturn(true);
1979 
1980         // GIVEN an unfold should force dismiss the keyguard
1981         when(mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(
1982                 PowerManager.WAKE_REASON_UNFOLD_DEVICE)).thenReturn(true);
1983 
1984         // WHEN device posture changes to unfold
1985         deviceInPostureStateOpened();
1986         mTestableLooper.processAllMessages();
1987 
1988         // THEN request unlock with a keyguard dismissal
1989         verify(mTrustManager).reportUserRequestedUnlock(
1990                 eq(mSelectedUserInteractor.getSelectedUserId()),
1991                 eq(true));
1992     }
1993 
1994 
1995     @Test
unfoldFromPostureChange_requestActiveUnlock_noDismissKeyguard()1996     public void unfoldFromPostureChange_requestActiveUnlock_noDismissKeyguard() {
1997         // GIVEN shouldTriggerActiveUnlock on wake from UNFOLD_DEVICE
1998         keyguardIsVisible();
1999         when(mLockPatternUtils.isSecure(mSelectedUserInteractor.getSelectedUserId())).thenReturn(
2000                 true);
2001 
2002         // GIVEN active unlock triggers on wakeup
2003         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2004                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE))
2005                 .thenReturn(true);
2006 
2007         // GIVEN an unfold should NOT force dismiss the keyguard
2008         when(mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(
2009                 PowerManager.WAKE_REASON_UNFOLD_DEVICE)).thenReturn(false);
2010 
2011         // WHEN device posture changes to unfold
2012         deviceInPostureStateOpened();
2013         mTestableLooper.processAllMessages();
2014 
2015         // THEN request unlock WITHOUT a keyguard dismissal
2016         verify(mTrustManager).reportUserRequestedUnlock(
2017                 eq(mSelectedUserInteractor.getSelectedUserId()),
2018                 eq(false));
2019     }
2020 
2021     @Test
unfoldFromPostureChange_sendActionToFaceAuthInteractor()2022     public void unfoldFromPostureChange_sendActionToFaceAuthInteractor() {
2023         // WHEN device posture changes to unfold
2024         deviceInPostureStateOpened();
2025         mTestableLooper.processAllMessages();
2026 
2027         // THEN request face auth
2028         verify(mFaceAuthInteractor).onDeviceUnfolded();
2029     }
2030 
2031     @Test
detectFingerprint_onTemporaryLockoutReset_authenticateFingerprint()2032     public void detectFingerprint_onTemporaryLockoutReset_authenticateFingerprint() {
2033         ArgumentCaptor<FingerprintManager.LockoutResetCallback> fpLockoutResetCallbackCaptor =
2034                 ArgumentCaptor.forClass(FingerprintManager.LockoutResetCallback.class);
2035         verify(mFingerprintManager).addLockoutResetCallback(fpLockoutResetCallbackCaptor.capture());
2036 
2037         // GIVEN device is locked out
2038         fingerprintErrorTemporaryLockOut();
2039 
2040         // GIVEN FP detection is running
2041         givenDetectFingerprintWithClearingFingerprintManagerInvocations();
2042         verifyFingerprintDetectCall();
2043         verifyFingerprintAuthenticateNeverCalled();
2044 
2045         // WHEN temporary lockout resets
2046         fpLockoutResetCallbackCaptor.getValue().onLockoutReset(0);
2047         mTestableLooper.processAllMessages();
2048 
2049         // THEN fingerprint detect state should cancel & then restart (for authenticate call)
2050         assertThat(mKeyguardUpdateMonitor.mFingerprintRunningState)
2051                 .isEqualTo(BIOMETRIC_STATE_CANCELLING_RESTARTING);
2052     }
2053 
2054     @Test
detectFingerprint_onSuccess_biometricStateStopped()2055     public void detectFingerprint_onSuccess_biometricStateStopped() {
2056         // GIVEN FP detection is running
2057         givenDetectFingerprintWithClearingFingerprintManagerInvocations();
2058 
2059         // WHEN detection is successful
2060         ArgumentCaptor<FingerprintManager.FingerprintDetectionCallback> fpDetectCallbackCaptor =
2061                 ArgumentCaptor.forClass(FingerprintManager.FingerprintDetectionCallback.class);
2062         verify(mFingerprintManager).detectFingerprint(
2063                 any(), fpDetectCallbackCaptor.capture(), any());
2064         fpDetectCallbackCaptor.getValue().onFingerprintDetected(0, 0, true);
2065         mTestableLooper.processAllMessages();
2066 
2067         // THEN fingerprint detect state should immediately update to STOPPED
2068         assertThat(mKeyguardUpdateMonitor.mFingerprintRunningState)
2069                 .isEqualTo(BIOMETRIC_STATE_STOPPED);
2070     }
2071 
2072     @Test
authenticateFingerprint_onFaceLockout_detectFingerprint()2073     public void authenticateFingerprint_onFaceLockout_detectFingerprint() throws RemoteException {
2074         // GIVEN fingerprintAuthenticate
2075         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
2076         mTestableLooper.processAllMessages();
2077         verifyFingerprintAuthenticateCall();
2078         verifyFingerprintDetectNeverCalled();
2079         clearInvocations(mFingerprintManager);
2080 
2081         // WHEN class 3 face is locked out
2082         when(mFaceAuthInteractor.isFaceAuthStrong()).thenReturn(true);
2083         when(mFaceAuthInteractor.isFaceAuthEnabledAndEnrolled()).thenReturn(true);
2084         setupFingerprintAuth(/* isClass3 */ true);
2085         // GIVEN primary auth is not required by StrongAuthTracker
2086         primaryAuthNotRequiredByStrongAuthTracker();
2087 
2088         // WHEN face (class 3) is locked out
2089         faceAuthLockOut();
2090         mTestableLooper.processAllMessages();
2091 
2092         // THEN unlocking with fingerprint is not allowed
2093         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
2094                 BiometricSourceType.FINGERPRINT));
2095 
2096         // THEN fingerprint detect gets called
2097         verifyFingerprintDetectCall();
2098     }
2099 
2100     @Test
testFingerprintSensorProperties()2101     public void testFingerprintSensorProperties() throws RemoteException {
2102         mFingerprintAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(
2103                 new ArrayList<>());
2104 
2105         assertThat(mKeyguardUpdateMonitor.isUnlockWithFingerprintPossible(
2106                 mSelectedUserInteractor.getSelectedUserId())).isFalse();
2107 
2108         mFingerprintAuthenticatorsRegisteredCallback
2109                 .onAllAuthenticatorsRegistered(mFingerprintSensorProperties);
2110 
2111         verifyFingerprintAuthenticateCall();
2112         assertThat(mKeyguardUpdateMonitor.isUnlockWithFingerprintPossible(
2113                 mSelectedUserInteractor.getSelectedUserId())).isTrue();
2114     }
2115 
2116     @Test
testFingerprintListeningStateWhenOccluded()2117     public void testFingerprintListeningStateWhenOccluded() {
2118         when(mAuthController.isUdfpsSupported()).thenReturn(true);
2119 
2120         mKeyguardUpdateMonitor.setKeyguardShowing(false, false);
2121         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_BIOMETRIC);
2122         mKeyguardUpdateMonitor.setKeyguardShowing(false, true);
2123 
2124         verifyFingerprintAuthenticateNeverCalled();
2125 
2126         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
2127         mKeyguardUpdateMonitor.setAlternateBouncerShowing(true);
2128 
2129         verifyFingerprintAuthenticateCall();
2130     }
2131 
2132     @Test
onTrustChangedCallbacksCalledBeforeOnTrustGrantedForCurrentUserCallback()2133     public void onTrustChangedCallbacksCalledBeforeOnTrustGrantedForCurrentUserCallback() {
2134         // GIVEN device is interactive
2135         deviceIsInteractive();
2136 
2137         // GIVEN callback is registered
2138         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2139         mKeyguardUpdateMonitor.registerCallback(callback);
2140 
2141         // WHEN onTrustChanged enabled=true
2142         mKeyguardUpdateMonitor.onTrustChanged(
2143                 true /* enabled */,
2144                 true /* newlyUnlocked */,
2145                 mSelectedUserInteractor.getSelectedUserId() /* userId */,
2146                 TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD /* flags */,
2147                 null /* trustGrantedMessages */);
2148 
2149         // THEN onTrustChanged is called FIRST
2150         final InOrder inOrder = Mockito.inOrder(callback);
2151         inOrder.verify(callback).onTrustChanged(eq(mSelectedUserInteractor.getSelectedUserId()));
2152 
2153         // AND THEN onTrustGrantedForCurrentUser callback called
2154         inOrder.verify(callback).onTrustGrantedForCurrentUser(
2155                 eq(true) /* dismissKeyguard */,
2156                 eq(true) /* newlyUnlocked */,
2157                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD)),
2158                 eq(null) /* message */
2159         );
2160     }
2161 
2162     @Test
testOnSimStateChanged_Unknown()2163     public void testOnSimStateChanged_Unknown() {
2164         KeyguardUpdateMonitorCallback keyguardUpdateMonitorCallback = spy(
2165                 KeyguardUpdateMonitorCallback.class);
2166         mKeyguardUpdateMonitor.registerCallback(keyguardUpdateMonitorCallback);
2167         mKeyguardUpdateMonitor.handleSimStateChange(-1, 0, TelephonyManager.SIM_STATE_UNKNOWN);
2168         verify(keyguardUpdateMonitorCallback).onSimStateChanged(-1, 0,
2169                 TelephonyManager.SIM_STATE_UNKNOWN);
2170     }
2171 
2172     @Test
testOnSimStateChanged_HandleSimStateNotReady()2173     public void testOnSimStateChanged_HandleSimStateNotReady() {
2174         KeyguardUpdateMonitorCallback keyguardUpdateMonitorCallback = spy(
2175                 KeyguardUpdateMonitorCallback.class);
2176         mKeyguardUpdateMonitor.registerCallback(keyguardUpdateMonitorCallback);
2177         mKeyguardUpdateMonitor.handleSimStateChange(-1, 0, TelephonyManager.SIM_STATE_NOT_READY);
2178         verify(keyguardUpdateMonitorCallback).onSimStateChanged(-1, 0,
2179                 TelephonyManager.SIM_STATE_NOT_READY);
2180     }
2181 
2182     @Test
onAuthEnrollmentChangesCallbacksAreNotified()2183     public void onAuthEnrollmentChangesCallbacksAreNotified() {
2184         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2185         ArgumentCaptor<AuthController.Callback> authCallback = ArgumentCaptor.forClass(
2186                 AuthController.Callback.class);
2187         verify(mAuthController).addCallback(authCallback.capture());
2188 
2189         mKeyguardUpdateMonitor.registerCallback(callback);
2190 
2191         authCallback.getValue().onEnrollmentsChanged(TYPE_FINGERPRINT);
2192         mTestableLooper.processAllMessages();
2193         verify(callback).onBiometricEnrollmentStateChanged(BiometricSourceType.FINGERPRINT);
2194 
2195         authCallback.getValue().onEnrollmentsChanged(BiometricAuthenticator.TYPE_FACE);
2196         mTestableLooper.processAllMessages();
2197         verify(callback).onBiometricEnrollmentStateChanged(BiometricSourceType.FACE);
2198 
2199         clearInvocations(callback);
2200         mFaceAuthenticationListener.getValue().onAuthEnrollmentStateChanged(false);
2201         mTestableLooper.processAllMessages();
2202         verify(callback).onBiometricEnrollmentStateChanged(BiometricSourceType.FACE);
2203     }
2204 
givenSelectedUserCanSkipBouncerFromTrustedState()2205     private void givenSelectedUserCanSkipBouncerFromTrustedState() {
2206         mKeyguardUpdateMonitor.onTrustChanged(true, true,
2207                 mSelectedUserInteractor.getSelectedUserId(), 0, null);
2208     }
2209 
2210     @Test
forceIsDismissibleKeyguard_foldingGracePeriodNotEnabled()2211     public void forceIsDismissibleKeyguard_foldingGracePeriodNotEnabled() {
2212         when(mFoldGracePeriodProvider.isEnabled()).thenReturn(false);
2213         primaryAuthNotRequiredByStrongAuthTracker();
2214         mKeyguardUpdateMonitor.tryForceIsDismissibleKeyguard();
2215         Assert.assertFalse(mKeyguardUpdateMonitor.forceIsDismissibleIsKeepingDeviceUnlocked());
2216     }
2217 
2218     @Test
forceIsDismissibleKeyguard()2219     public void forceIsDismissibleKeyguard() {
2220         when(mFoldGracePeriodProvider.isEnabled()).thenReturn(true);
2221         primaryAuthNotRequiredByStrongAuthTracker();
2222         mKeyguardUpdateMonitor.tryForceIsDismissibleKeyguard();
2223         Assert.assertTrue(mKeyguardUpdateMonitor.forceIsDismissibleIsKeepingDeviceUnlocked());
2224     }
2225 
2226     @Test
forceIsDismissibleKeyguard_respectsLockdown()2227     public void forceIsDismissibleKeyguard_respectsLockdown() {
2228         when(mFoldGracePeriodProvider.isEnabled()).thenReturn(true);
2229         userDeviceLockDown();
2230         mKeyguardUpdateMonitor.tryForceIsDismissibleKeyguard();
2231         Assert.assertFalse(mKeyguardUpdateMonitor.forceIsDismissibleIsKeepingDeviceUnlocked());
2232     }
2233 
verifyFingerprintAuthenticateNeverCalled()2234     private void verifyFingerprintAuthenticateNeverCalled() {
2235         verify(mFingerprintManager, never()).authenticate(any(), any(), any(), any(), any());
2236         verify(mFingerprintManager, never()).authenticate(any(), any(), any(), any(), anyInt(),
2237                 anyInt(), anyInt());
2238     }
2239 
verifyFingerprintAuthenticateCall()2240     private void verifyFingerprintAuthenticateCall() {
2241         verify(mFingerprintManager).authenticate(any(), any(), any(), any(), any());
2242     }
2243 
verifyFingerprintDetectNeverCalled()2244     private void verifyFingerprintDetectNeverCalled() {
2245         verify(mFingerprintManager, never()).detectFingerprint(any(), any(), any());
2246     }
2247 
verifyFingerprintDetectCall()2248     private void verifyFingerprintDetectCall() {
2249         verify(mFingerprintManager).detectFingerprint(any(), any(), any());
2250     }
2251 
userDeviceLockDown()2252     private void userDeviceLockDown() {
2253         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
2254         when(mStrongAuthTracker.getStrongAuthForUser(mCurrentUserId))
2255                 .thenReturn(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
2256     }
2257 
lockscreenBypassIsAllowed()2258     private void lockscreenBypassIsAllowed() {
2259         mockCanBypassLockscreen(true);
2260     }
2261 
mockCanBypassLockscreen(boolean canBypass)2262     private void mockCanBypassLockscreen(boolean canBypass) {
2263         mKeyguardUpdateMonitor.setKeyguardBypassController(mKeyguardBypassController);
2264         when(mKeyguardBypassController.canBypass()).thenReturn(canBypass);
2265     }
2266 
lockscreenBypassIsNotAllowed()2267     private void lockscreenBypassIsNotAllowed() {
2268         mockCanBypassLockscreen(false);
2269     }
2270 
cleanupKeyguardUpdateMonitor()2271     private void cleanupKeyguardUpdateMonitor() {
2272         if (mKeyguardUpdateMonitor != null) {
2273             mKeyguardUpdateMonitor.removeCallback(mTestCallback);
2274             mKeyguardUpdateMonitor.destroy();
2275             mKeyguardUpdateMonitor = null;
2276         }
2277     }
2278 
faceAuthLockOut()2279     private void faceAuthLockOut() {
2280         when(mFaceAuthInteractor.isLockedOut()).thenReturn(MutableStateFlow(true));
2281         mFaceAuthenticationListener.getValue().onAuthenticationStatusChanged(
2282                 new ErrorFaceAuthenticationStatus(FACE_ERROR_LOCKOUT_PERMANENT, "", 0L));
2283     }
2284 
statusBarShadeIsNotLocked()2285     private void statusBarShadeIsNotLocked() {
2286         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
2287     }
2288 
keyguardIsVisible()2289     private void keyguardIsVisible() {
2290         mKeyguardUpdateMonitor.setKeyguardShowing(true, false);
2291     }
2292 
fingerprintErrorTemporaryLockOut()2293     private void fingerprintErrorTemporaryLockOut() {
2294         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
2295                 .onAuthenticationError(FINGERPRINT_ERROR_LOCKOUT, "Fingerprint locked out");
2296     }
2297 
deviceInPostureStateOpened()2298     private void deviceInPostureStateOpened() {
2299         mKeyguardUpdateMonitor.mPostureCallback.onPostureChanged(DEVICE_POSTURE_OPENED);
2300     }
2301 
currentUserIsSystem()2302     private void currentUserIsSystem() {
2303         when(mUserManager.isSystemUser()).thenReturn(true);
2304     }
2305 
biometricsEnabledForCurrentUser()2306     private void biometricsEnabledForCurrentUser() throws RemoteException {
2307         mBiometricEnabledOnKeyguardCallback.onChanged(true,
2308                 mSelectedUserInteractor.getSelectedUserId());
2309     }
2310 
primaryAuthNotRequiredByStrongAuthTracker()2311     private void primaryAuthNotRequiredByStrongAuthTracker() {
2312         when(mStrongAuthTracker.getStrongAuthForUser(mSelectedUserInteractor.getSelectedUserId()))
2313                 .thenReturn(0);
2314         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(true);
2315     }
2316 
keyguardNotGoingAway()2317     private void keyguardNotGoingAway() {
2318         mKeyguardUpdateMonitor.setKeyguardGoingAway(false);
2319     }
2320 
deviceIsInteractive()2321     private void deviceIsInteractive() {
2322         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
2323     }
2324 
bouncerFullyVisible()2325     private void bouncerFullyVisible() {
2326         setKeyguardBouncerVisibility(true);
2327     }
2328 
setKeyguardBouncerVisibility(boolean isVisible)2329     private void setKeyguardBouncerVisibility(boolean isVisible) {
2330         mKeyguardUpdateMonitor.sendPrimaryBouncerChanged(isVisible, isVisible);
2331         mTestableLooper.processAllMessages();
2332     }
2333 
setBroadcastReceiverPendingResult(BroadcastReceiver receiver)2334     private void setBroadcastReceiverPendingResult(BroadcastReceiver receiver) {
2335         BroadcastReceiver.PendingResult pendingResult =
2336                 new BroadcastReceiver.PendingResult(Activity.RESULT_OK,
2337                         "resultData",
2338                         /* resultExtras= */ null,
2339                         BroadcastReceiver.PendingResult.TYPE_UNREGISTERED,
2340                         /* ordered= */ true,
2341                         /* sticky= */ false,
2342                         /* token= */ null,
2343                         UserHandle.myUserId(),
2344                         /* flags= */ 0);
2345         receiver.setPendingResult(pendingResult);
2346     }
2347 
givenDetectFingerprintWithClearingFingerprintManagerInvocations()2348     private void givenDetectFingerprintWithClearingFingerprintManagerInvocations() {
2349         // Clear invocations, since previous setup (e.g. registering BiometricManager callbacks)
2350         // will trigger updateBiometricListeningState();
2351         clearInvocations(mFingerprintManager);
2352         mKeyguardUpdateMonitor.resetBiometricListeningState();
2353 
2354         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
2355         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
2356         mTestableLooper.processAllMessages();
2357     }
2358 
putPhoneInfo(Intent intent, Bundle data, Boolean simInited)2359     private Intent putPhoneInfo(Intent intent, Bundle data, Boolean simInited) {
2360         int subscription = simInited
2361                 ? 1/* mock subid=1 */ : SubscriptionManager.PLACEHOLDER_SUBSCRIPTION_ID_BASE;
2362         if (data != null) intent.putExtras(data);
2363 
2364         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subscription);
2365         intent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0);
2366         return intent;
2367     }
2368 
verifyRefreshBatteryInfo()2369     private BatteryStatus verifyRefreshBatteryInfo() {
2370         mTestableLooper.processAllMessages();
2371         ArgumentCaptor<BatteryStatus> captor = ArgumentCaptor.forClass(BatteryStatus.class);
2372         verify(mTestCallback, atLeastOnce()).onRefreshBatteryInfo(captor.capture());
2373         List<BatteryStatus> batteryStatusList = captor.getAllValues();
2374         return batteryStatusList.get(batteryStatusList.size() - 1);
2375     }
2376 
setupIncompatibleCharging()2377     private void setupIncompatibleCharging() {
2378         final List<UsbPort> usbPorts = new ArrayList<>();
2379         usbPorts.add(mUsbPort);
2380         when(mUsbManager.getPorts()).thenReturn(usbPorts);
2381         when(mUsbPort.getStatus()).thenReturn(mUsbPortStatus);
2382         when(mUsbPort.supportsComplianceWarnings()).thenReturn(true);
2383         when(mUsbPortStatus.isConnected()).thenReturn(true);
2384         when(mUsbPortStatus.getComplianceWarnings())
2385                 .thenReturn(new int[]{UsbPortStatus.COMPLIANCE_WARNING_DEBUG_ACCESSORY});
2386     }
2387 
getSpyContext()2388     private Context getSpyContext() {
2389         mContext.addMockSystemService(UsbManager.class, mUsbManager);
2390         Context contextSpy = spy(mContext);
2391         doReturn(getBatteryIntent()).when(contextSpy).registerReceiver(eq(null),
2392                 any(IntentFilter.class));
2393         return contextSpy;
2394     }
2395 
getBatteryIntent()2396     private Intent getBatteryIntent() {
2397         return new Intent(Intent.ACTION_BATTERY_CHANGED).putExtra(
2398                 BatteryManager.EXTRA_CHARGING_STATUS,
2399                 BatteryManager.CHARGING_POLICY_ADAPTIVE_LONGLIFE);
2400     }
2401 
setTopStandardActivity(String pkgName)2402     private void setTopStandardActivity(String pkgName) throws RemoteException {
2403         final ActivityTaskManager.RootTaskInfo taskInfo = new ActivityTaskManager.RootTaskInfo();
2404         taskInfo.visible = true;
2405         taskInfo.topActivity = TextUtils.isEmpty(pkgName)
2406                 ? null : new ComponentName(pkgName, "testClass");
2407         when(mActivityTaskManager.getRootTaskInfo(anyInt(), eq(ACTIVITY_TYPE_STANDARD)))
2408                 .thenReturn(taskInfo);
2409     }
2410 
onTaskStackChanged()2411     private void onTaskStackChanged() {
2412         ArgumentCaptor<TaskStackChangeListener> taskStackChangeListenerCaptor =
2413                 ArgumentCaptor.forClass(TaskStackChangeListener.class);
2414         verify(mTaskStackChangeListeners).registerTaskStackListener(
2415                 taskStackChangeListenerCaptor.capture());
2416         taskStackChangeListenerCaptor.getValue().onTaskStackChangedBackground();
2417     }
2418 
2419     private class TestableKeyguardUpdateMonitor extends KeyguardUpdateMonitor {
2420         AtomicBoolean mSimStateChanged = new AtomicBoolean(false);
2421         AtomicInteger mCachedSimState = new AtomicInteger(-1);
2422 
TestableKeyguardUpdateMonitor(Context context)2423         protected TestableKeyguardUpdateMonitor(Context context) {
2424             super(context, mUserTracker,
2425                     TestableLooper.get(KeyguardUpdateMonitorTest.this).getLooper(),
2426                     mBroadcastDispatcher, mDumpManager,
2427                     mBackgroundExecutor, mMainExecutor,
2428                     mStatusBarStateController, mLockPatternUtils,
2429                     mAuthController, mTelephonyListenerManager,
2430                     mInteractionJankMonitor, mLatencyTracker, mActiveUnlockConfig,
2431                     mKeyguardUpdateMonitorLogger, mUiEventLogger, () -> mSessionTracker,
2432                     mTrustManager, mSubscriptionManager, mUserManager,
2433                     mDreamManager, mDevicePolicyManager, mSensorPrivacyManager, mTelephonyManager,
2434                     mPackageManager, mFingerprintManager, mBiometricManager,
2435                     mFaceWakeUpTriggersConfig, mDevicePostureController,
2436                     Optional.of(mInteractiveToAuthProvider),
2437                     mTaskStackChangeListeners, mSelectedUserInteractor, mActivityTaskManager);
2438             setStrongAuthTracker(KeyguardUpdateMonitorTest.this.mStrongAuthTracker);
2439             start();
2440         }
2441 
hasSimStateJustChanged()2442         public boolean hasSimStateJustChanged() {
2443             return mSimStateChanged.getAndSet(false);
2444         }
2445 
getCachedSimState()2446         public int getCachedSimState() {
2447             return mCachedSimState.getAndSet(-1);
2448         }
2449 
2450         @Override
handleSimStateChange(int subId, int slotId, int state)2451         protected void handleSimStateChange(int subId, int slotId, int state) {
2452             mSimStateChanged.set(true);
2453             mCachedSimState.set(state);
2454             super.handleSimStateChange(subId, slotId, state);
2455         }
2456 
2457         @Override
getBiometricLockoutDelay()2458         protected int getBiometricLockoutDelay() {
2459             return 0;
2460         }
2461     }
2462 }
2463