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.BiometricFingerprintConstants.FINGERPRINT_ERROR_LOCKOUT;
23 import static android.hardware.biometrics.BiometricFingerprintConstants.FINGERPRINT_ERROR_LOCKOUT_PERMANENT;
24 import static android.hardware.biometrics.SensorProperties.STRENGTH_CONVENIENCE;
25 import static android.hardware.biometrics.SensorProperties.STRENGTH_STRONG;
26 import static android.hardware.face.FaceAuthenticateOptions.AUTHENTICATE_REASON_PRIMARY_BOUNCER_SHOWN;
27 import static android.hardware.face.FaceAuthenticateOptions.AUTHENTICATE_REASON_STARTED_WAKING_UP;
28 import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_POWER_BUTTON;
29 import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_UDFPS_OPTICAL;
30 import static android.telephony.SubscriptionManager.DATA_ROAMING_DISABLE;
31 import static android.telephony.SubscriptionManager.NAME_SOURCE_CARRIER_ID;
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_BOOT;
35 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN;
36 import static com.android.keyguard.FaceAuthApiRequestReason.NOTIFICATION_PANEL_CLICKED;
37 import static com.android.keyguard.KeyguardUpdateMonitor.BIOMETRIC_HELP_FACE_NOT_AVAILABLE;
38 import static com.android.keyguard.KeyguardUpdateMonitor.BIOMETRIC_STATE_CANCELLING_RESTARTING;
39 import static com.android.keyguard.KeyguardUpdateMonitor.DEFAULT_CANCEL_SIGNAL_TIMEOUT;
40 import static com.android.keyguard.KeyguardUpdateMonitor.HAL_POWER_PRESS_TIMEOUT;
41 import static com.android.keyguard.KeyguardUpdateMonitor.getCurrentUser;
42 import static com.android.systemui.flags.Flags.FP_LISTEN_OCCLUDING_APPS;
43 import static com.android.systemui.flags.Flags.STOP_FACE_AUTH_ON_DISPLAY_OFF;
44 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_ASLEEP;
45 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_AWAKE;
46 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_WAKING;
47 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_CLOSED;
48 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_OPENED;
49 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_UNKNOWN;
50 
51 import static com.google.common.truth.Truth.assertThat;
52 
53 import static junit.framework.Assert.assertEquals;
54 
55 import static org.mockito.ArgumentMatchers.any;
56 import static org.mockito.ArgumentMatchers.anyBoolean;
57 import static org.mockito.ArgumentMatchers.anyInt;
58 import static org.mockito.ArgumentMatchers.anyObject;
59 import static org.mockito.ArgumentMatchers.anyString;
60 import static org.mockito.ArgumentMatchers.eq;
61 import static org.mockito.Mockito.atLeastOnce;
62 import static org.mockito.Mockito.clearInvocations;
63 import static org.mockito.Mockito.doNothing;
64 import static org.mockito.Mockito.doReturn;
65 import static org.mockito.Mockito.mock;
66 import static org.mockito.Mockito.never;
67 import static org.mockito.Mockito.spy;
68 import static org.mockito.Mockito.times;
69 import static org.mockito.Mockito.verify;
70 import static org.mockito.Mockito.when;
71 
72 import android.app.Activity;
73 import android.app.ActivityTaskManager;
74 import android.app.IActivityTaskManager;
75 import android.app.admin.DevicePolicyManager;
76 import android.app.trust.IStrongAuthTracker;
77 import android.app.trust.TrustManager;
78 import android.content.BroadcastReceiver;
79 import android.content.ComponentName;
80 import android.content.ContentResolver;
81 import android.content.Context;
82 import android.content.Intent;
83 import android.content.IntentFilter;
84 import android.content.pm.PackageManager;
85 import android.content.pm.ResolveInfo;
86 import android.content.pm.ServiceInfo;
87 import android.content.pm.UserInfo;
88 import android.database.ContentObserver;
89 import android.hardware.SensorPrivacyManager;
90 import android.hardware.biometrics.BiometricAuthenticator;
91 import android.hardware.biometrics.BiometricConstants;
92 import android.hardware.biometrics.BiometricManager;
93 import android.hardware.biometrics.BiometricSourceType;
94 import android.hardware.biometrics.ComponentInfoInternal;
95 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
96 import android.hardware.display.DisplayManagerGlobal;
97 import android.hardware.face.FaceAuthenticateOptions;
98 import android.hardware.face.FaceManager;
99 import android.hardware.face.FaceSensorProperties;
100 import android.hardware.face.FaceSensorPropertiesInternal;
101 import android.hardware.face.IFaceAuthenticatorsRegisteredCallback;
102 import android.hardware.fingerprint.FingerprintManager;
103 import android.hardware.fingerprint.FingerprintSensorProperties;
104 import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
105 import android.hardware.fingerprint.IFingerprintAuthenticatorsRegisteredCallback;
106 import android.hardware.usb.UsbManager;
107 import android.hardware.usb.UsbPort;
108 import android.hardware.usb.UsbPortStatus;
109 import android.net.Uri;
110 import android.nfc.NfcAdapter;
111 import android.os.BatteryManager;
112 import android.os.Bundle;
113 import android.os.CancellationSignal;
114 import android.os.Handler;
115 import android.os.PowerManager;
116 import android.os.RemoteException;
117 import android.os.UserHandle;
118 import android.os.UserManager;
119 import android.service.dreams.IDreamManager;
120 import android.service.trust.TrustAgentService;
121 import android.telephony.ServiceState;
122 import android.telephony.SubscriptionInfo;
123 import android.telephony.SubscriptionManager;
124 import android.telephony.TelephonyManager;
125 import android.test.suitebuilder.annotation.SmallTest;
126 import android.testing.AndroidTestingRunner;
127 import android.testing.TestableLooper;
128 import android.text.TextUtils;
129 import android.view.Display;
130 import android.view.DisplayAdjustments;
131 import android.view.DisplayInfo;
132 
133 import androidx.annotation.NonNull;
134 
135 import com.android.dx.mockito.inline.extended.ExtendedMockito;
136 import com.android.internal.jank.InteractionJankMonitor;
137 import com.android.internal.logging.InstanceId;
138 import com.android.internal.logging.UiEventLogger;
139 import com.android.internal.telephony.TelephonyIntents;
140 import com.android.internal.util.LatencyTracker;
141 import com.android.internal.widget.ILockSettings;
142 import com.android.internal.widget.LockPatternUtils;
143 import com.android.keyguard.KeyguardUpdateMonitor.BiometricAuthenticated;
144 import com.android.keyguard.logging.KeyguardUpdateMonitorLogger;
145 import com.android.settingslib.fuelgauge.BatteryStatus;
146 import com.android.systemui.SysuiTestCase;
147 import com.android.systemui.biometrics.AuthController;
148 import com.android.systemui.biometrics.FingerprintInteractiveToAuthProvider;
149 import com.android.systemui.broadcast.BroadcastDispatcher;
150 import com.android.systemui.dump.DumpManager;
151 import com.android.systemui.flags.FakeFeatureFlags;
152 import com.android.systemui.keyguard.WakefulnessLifecycle;
153 import com.android.systemui.log.SessionTracker;
154 import com.android.systemui.plugins.statusbar.StatusBarStateController;
155 import com.android.systemui.settings.FakeDisplayTracker;
156 import com.android.systemui.settings.UserTracker;
157 import com.android.systemui.shared.system.TaskStackChangeListener;
158 import com.android.systemui.shared.system.TaskStackChangeListeners;
159 import com.android.systemui.statusbar.StatusBarState;
160 import com.android.systemui.statusbar.phone.KeyguardBypassController;
161 import com.android.systemui.statusbar.policy.DevicePostureController;
162 import com.android.systemui.telephony.TelephonyListenerManager;
163 import com.android.systemui.util.settings.GlobalSettings;
164 import com.android.systemui.util.settings.SecureSettings;
165 
166 import org.junit.After;
167 import org.junit.Assert;
168 import org.junit.Before;
169 import org.junit.Test;
170 import org.junit.runner.RunWith;
171 import org.mockito.ArgumentCaptor;
172 import org.mockito.Captor;
173 import org.mockito.InOrder;
174 import org.mockito.Mock;
175 import org.mockito.Mockito;
176 import org.mockito.MockitoAnnotations;
177 import org.mockito.MockitoSession;
178 import org.mockito.internal.util.reflection.FieldSetter;
179 import org.mockito.quality.Strictness;
180 
181 import java.util.ArrayList;
182 import java.util.Arrays;
183 import java.util.List;
184 import java.util.Optional;
185 import java.util.Random;
186 import java.util.concurrent.CountDownLatch;
187 import java.util.concurrent.Executor;
188 import java.util.concurrent.atomic.AtomicBoolean;
189 import java.util.concurrent.atomic.AtomicInteger;
190 
191 @SmallTest
192 @RunWith(AndroidTestingRunner.class)
193 @TestableLooper.RunWithLooper
194 public class KeyguardUpdateMonitorTest extends SysuiTestCase {
195     private static final String PKG_ALLOWING_FP_LISTEN_ON_OCCLUDING_ACTIVITY =
196             "test_app_fp_listen_on_occluding_activity";
197     private static final String TEST_CARRIER = "TEST_CARRIER";
198     private static final String TEST_CARRIER_2 = "TEST_CARRIER_2";
199     private static final int TEST_CARRIER_ID = 1;
200     private static final String TEST_GROUP_UUID = "59b5c870-fc4c-47a4-a99e-9db826b48b24";
201     private static final SubscriptionInfo TEST_SUBSCRIPTION = new SubscriptionInfo(1, "", 0,
202             TEST_CARRIER, TEST_CARRIER, NAME_SOURCE_CARRIER_ID, 0xFFFFFF, "",
203             DATA_ROAMING_DISABLE, null, null, null, null, false, null, "", false, TEST_GROUP_UUID,
204             TEST_CARRIER_ID, 0);
205     private static final SubscriptionInfo TEST_SUBSCRIPTION_2 = new SubscriptionInfo(2, "", 0,
206             TEST_CARRIER, TEST_CARRIER_2, NAME_SOURCE_CARRIER_ID, 0xFFFFFF, "",
207             DATA_ROAMING_DISABLE, null, null, null, null, false, null, "", true, TEST_GROUP_UUID,
208             TEST_CARRIER_ID, 0);
209     private static final int FACE_SENSOR_ID = 0;
210     private static final int FINGERPRINT_SENSOR_ID = 1;
211 
212     @Mock
213     private UserTracker mUserTracker;
214     @Mock
215     private DumpManager mDumpManager;
216     @Mock
217     private KeyguardUpdateMonitor.StrongAuthTracker mStrongAuthTracker;
218     @Mock
219     private TrustManager mTrustManager;
220     @Mock
221     private LockPatternUtils mLockPatternUtils;
222     @Mock
223     private ILockSettings mLockSettings;
224     @Mock
225     private FingerprintManager mFingerprintManager;
226     @Mock
227     private FaceManager mFaceManager;
228     @Mock
229     private BiometricManager mBiometricManager;
230     @Mock
231     private PackageManager mPackageManager;
232     @Mock
233     private UserManager mUserManager;
234     @Mock
235     private DevicePolicyManager mDevicePolicyManager;
236     @Mock
237     private DevicePostureController mDevicePostureController;
238     @Mock
239     private IDreamManager mDreamManager;
240     @Mock
241     private KeyguardBypassController mKeyguardBypassController;
242     @Mock
243     private SubscriptionManager mSubscriptionManager;
244     @Mock
245     private BroadcastDispatcher mBroadcastDispatcher;
246     @Mock
247     private SecureSettings mSecureSettings;
248     @Mock
249     private TelephonyManager mTelephonyManager;
250     @Mock
251     private SensorPrivacyManager mSensorPrivacyManager;
252     @Mock
253     private StatusBarStateController mStatusBarStateController;
254     @Mock
255     private AuthController mAuthController;
256     @Mock
257     private TelephonyListenerManager mTelephonyListenerManager;
258     @Mock
259     private InteractionJankMonitor mInteractionJankMonitor;
260     @Mock
261     private LatencyTracker mLatencyTracker;
262     @Captor
263     private ArgumentCaptor<StatusBarStateController.StateListener> mStatusBarStateListenerCaptor;
264     @Mock
265     private KeyguardUpdateMonitorCallback mTestCallback;
266     @Mock
267     private ActiveUnlockConfig mActiveUnlockConfig;
268     @Mock
269     private KeyguardUpdateMonitorLogger mKeyguardUpdateMonitorLogger;
270     @Mock
271     private SessionTracker mSessionTracker;
272     @Mock
273     private UiEventLogger mUiEventLogger;
274     @Mock
275     private GlobalSettings mGlobalSettings;
276     @Mock
277     private FingerprintInteractiveToAuthProvider mInteractiveToAuthProvider;
278     @Mock
279     private UsbPort mUsbPort;
280     @Mock
281     private UsbManager mUsbManager;
282     @Mock
283     private UsbPortStatus mUsbPortStatus;
284     @Mock
285     private Uri mURI;
286     @Mock
287     private TaskStackChangeListeners mTaskStackChangeListeners;
288     @Mock
289     private IActivityTaskManager mActivityTaskManager;
290     @Mock
291     private WakefulnessLifecycle mWakefulness;
292 
293     private List<FaceSensorPropertiesInternal> mFaceSensorProperties;
294     private List<FingerprintSensorPropertiesInternal> mFingerprintSensorProperties;
295     private final int mCurrentUserId = 100;
296     private final UserInfo mCurrentUserInfo = new UserInfo(mCurrentUserId, "Test user", 0);
297 
298     @Captor
299     private ArgumentCaptor<IBiometricEnabledOnKeyguardCallback>
300             mBiometricEnabledCallbackArgCaptor;
301     @Captor
302     private ArgumentCaptor<FaceManager.AuthenticationCallback> mAuthenticationCallbackCaptor;
303 
304     // Direct executor
305     private final Executor mBackgroundExecutor = Runnable::run;
306     private final Executor mMainExecutor = Runnable::run;
307     private TestableLooper mTestableLooper;
308     private FakeFeatureFlags mFeatureFlags;
309     private Handler mHandler;
310     private TestableKeyguardUpdateMonitor mKeyguardUpdateMonitor;
311     private MockitoSession mMockitoSession;
312     private StatusBarStateController.StateListener mStatusBarStateListener;
313     private IBiometricEnabledOnKeyguardCallback mBiometricEnabledOnKeyguardCallback;
314     private FaceWakeUpTriggersConfig mFaceWakeUpTriggersConfig;
315     private IFingerprintAuthenticatorsRegisteredCallback
316             mFingerprintAuthenticatorsRegisteredCallback;
317     private IFaceAuthenticatorsRegisteredCallback mFaceAuthenticatorsRegisteredCallback;
318     private final InstanceId mKeyguardInstanceId = InstanceId.fakeInstanceId(999);
319     private FakeDisplayTracker mDisplayTracker;
320 
321     @Before
setup()322     public void setup() throws RemoteException {
323         MockitoAnnotations.initMocks(this);
324         mDisplayTracker = new FakeDisplayTracker(mContext);
325         when(mSessionTracker.getSessionId(SESSION_KEYGUARD)).thenReturn(mKeyguardInstanceId);
326 
327         when(mUserManager.isUserUnlocked(anyInt())).thenReturn(true);
328         currentUserIsSystem();
329         when(mStrongAuthTracker.getStub()).thenReturn(mock(IStrongAuthTracker.Stub.class));
330         when(mStrongAuthTracker
331                 .isUnlockingWithBiometricAllowed(anyBoolean() /* isClass3Biometric */))
332                 .thenReturn(true);
333         when(mTelephonyManager.getServiceStateForSubscriber(anyInt()))
334                 .thenReturn(new ServiceState());
335         when(mLockPatternUtils.getLockSettings()).thenReturn(mLockSettings);
336         when(mAuthController.isUdfpsEnrolled(anyInt())).thenReturn(false);
337         when(mDevicePostureController.getDevicePosture()).thenReturn(DEVICE_POSTURE_UNKNOWN);
338 
339         mMockitoSession = ExtendedMockito.mockitoSession()
340                 .spyStatic(SubscriptionManager.class)
341                 .strictness(Strictness.WARN)
342                 .startMocking();
343         ExtendedMockito.doReturn(SubscriptionManager.INVALID_SUBSCRIPTION_ID)
344                 .when(SubscriptionManager::getDefaultSubscriptionId);
345         KeyguardUpdateMonitor.setCurrentUser(mCurrentUserId);
346         when(mUserTracker.getUserId()).thenReturn(mCurrentUserId);
347 
348         mContext.getOrCreateTestableResources().addOverride(
349                 com.android.systemui.R.integer.config_face_auth_supported_posture,
350                 DEVICE_POSTURE_UNKNOWN);
351         mFaceWakeUpTriggersConfig = new FaceWakeUpTriggersConfig(
352                 mContext.getResources(),
353                 mGlobalSettings,
354                 mDumpManager
355         );
356 
357         mContext.getOrCreateTestableResources().addOverride(com.android.systemui
358                         .R.array.config_fingerprint_listen_on_occluding_activity_packages,
359                 new String[]{ PKG_ALLOWING_FP_LISTEN_ON_OCCLUDING_ACTIVITY });
360 
361         mTestableLooper = TestableLooper.get(this);
362         allowTestableLooperAsMainThread();
363         mFeatureFlags = new FakeFeatureFlags();
364         mFeatureFlags.set(FP_LISTEN_OCCLUDING_APPS, false);
365         mFeatureFlags.set(STOP_FACE_AUTH_ON_DISPLAY_OFF, false);
366 
367         when(mSecureSettings.getUriFor(anyString())).thenReturn(mURI);
368 
369         final ContentResolver contentResolver = mContext.getContentResolver();
370         ExtendedMockito.spyOn(contentResolver);
371         doNothing().when(contentResolver)
372                 .registerContentObserver(any(Uri.class), anyBoolean(), any(ContentObserver.class),
373                         anyInt());
374 
375         mKeyguardUpdateMonitor = new TestableKeyguardUpdateMonitor(mContext);
376         setupBiometrics(mKeyguardUpdateMonitor);
377     }
378 
setupBiometrics(KeyguardUpdateMonitor keyguardUpdateMonitor)379     private void setupBiometrics(KeyguardUpdateMonitor keyguardUpdateMonitor)
380             throws RemoteException {
381         captureAuthenticatorsRegisteredCallbacks();
382         setupFaceAuth(/* isClass3 */ false);
383         setupFingerprintAuth(/* isClass3 */ true);
384 
385         verify(mBiometricManager)
386                 .registerEnabledOnKeyguardCallback(mBiometricEnabledCallbackArgCaptor.capture());
387         mBiometricEnabledOnKeyguardCallback = mBiometricEnabledCallbackArgCaptor.getValue();
388         biometricsEnabledForCurrentUser();
389 
390         mHandler = spy(keyguardUpdateMonitor.getHandler());
391         try {
392             FieldSetter.setField(keyguardUpdateMonitor,
393                     KeyguardUpdateMonitor.class.getDeclaredField("mHandler"), mHandler);
394         } catch (NoSuchFieldException e) {
395 
396         }
397         verify(mStatusBarStateController).addCallback(mStatusBarStateListenerCaptor.capture());
398         mStatusBarStateListener = mStatusBarStateListenerCaptor.getValue();
399         mKeyguardUpdateMonitor.registerCallback(mTestCallback);
400 
401         mTestableLooper.processAllMessages();
402         when(mAuthController.areAllFingerprintAuthenticatorsRegistered()).thenReturn(true);
403     }
404 
captureAuthenticatorsRegisteredCallbacks()405     private void captureAuthenticatorsRegisteredCallbacks() throws RemoteException {
406         ArgumentCaptor<IFaceAuthenticatorsRegisteredCallback> faceCaptor =
407                 ArgumentCaptor.forClass(IFaceAuthenticatorsRegisteredCallback.class);
408         verify(mFaceManager).addAuthenticatorsRegisteredCallback(faceCaptor.capture());
409         mFaceAuthenticatorsRegisteredCallback = faceCaptor.getValue();
410         mFaceAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(mFaceSensorProperties);
411 
412         ArgumentCaptor<IFingerprintAuthenticatorsRegisteredCallback> fingerprintCaptor =
413                 ArgumentCaptor.forClass(IFingerprintAuthenticatorsRegisteredCallback.class);
414         verify(mFingerprintManager).addAuthenticatorsRegisteredCallback(
415                 fingerprintCaptor.capture());
416         mFingerprintAuthenticatorsRegisteredCallback = fingerprintCaptor.getValue();
417         mFingerprintAuthenticatorsRegisteredCallback
418                 .onAllAuthenticatorsRegistered(mFingerprintSensorProperties);
419     }
420 
setupFaceAuth(boolean isClass3)421     private void setupFaceAuth(boolean isClass3) throws RemoteException {
422         when(mFaceManager.isHardwareDetected()).thenReturn(true);
423         when(mAuthController.isFaceAuthEnrolled(anyInt())).thenReturn(true);
424         mFaceSensorProperties =
425                 List.of(createFaceSensorProperties(/* supportsFaceDetection = */ false, isClass3));
426         when(mFaceManager.getSensorPropertiesInternal()).thenReturn(mFaceSensorProperties);
427         mFaceAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(mFaceSensorProperties);
428         assertEquals(isClass3, mKeyguardUpdateMonitor.isFaceClass3());
429     }
430 
setupFingerprintAuth(boolean isClass3)431     private void setupFingerprintAuth(boolean isClass3) throws RemoteException {
432         when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
433         when(mFingerprintManager.hasEnrolledTemplates(anyInt())).thenReturn(true);
434         mFingerprintSensorProperties = List.of(
435                 createFingerprintSensorPropertiesInternal(TYPE_UDFPS_OPTICAL, isClass3));
436         when(mFingerprintManager.getSensorPropertiesInternal()).thenReturn(
437                 mFingerprintSensorProperties);
438         mFingerprintAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(
439                 mFingerprintSensorProperties);
440         assertEquals(isClass3, mKeyguardUpdateMonitor.isFingerprintClass3());
441     }
442 
createFingerprintSensorPropertiesInternal( @ingerprintSensorProperties.SensorType int sensorType, boolean isClass3)443     private FingerprintSensorPropertiesInternal createFingerprintSensorPropertiesInternal(
444             @FingerprintSensorProperties.SensorType int sensorType,
445             boolean isClass3) {
446         final List<ComponentInfoInternal> componentInfo =
447                 List.of(new ComponentInfoInternal("fingerprintSensor" /* componentId */,
448                         "vendor/model/revision" /* hardwareVersion */,
449                         "1.01" /* firmwareVersion */,
450                         "00000001" /* serialNumber */, "" /* softwareVersion */));
451         return new FingerprintSensorPropertiesInternal(
452                 FINGERPRINT_SENSOR_ID,
453                 isClass3 ? STRENGTH_STRONG : STRENGTH_CONVENIENCE,
454                 1 /* maxEnrollmentsPerUser */,
455                 componentInfo,
456                 sensorType,
457                 true /* resetLockoutRequiresHardwareAuthToken */);
458     }
459 
460     @NonNull
createFaceSensorProperties( boolean supportsFaceDetection, boolean isClass3)461     private FaceSensorPropertiesInternal createFaceSensorProperties(
462             boolean supportsFaceDetection, boolean isClass3) {
463         final List<ComponentInfoInternal> componentInfo = new ArrayList<>();
464         componentInfo.add(new ComponentInfoInternal("faceSensor" /* componentId */,
465                 "vendor/model/revision" /* hardwareVersion */, "1.01" /* firmwareVersion */,
466                 "00000001" /* serialNumber */, "" /* softwareVersion */));
467         componentInfo.add(new ComponentInfoInternal("matchingAlgorithm" /* componentId */,
468                 "" /* hardwareVersion */, "" /* firmwareVersion */, "" /* serialNumber */,
469                 "vendor/version/revision" /* softwareVersion */));
470 
471         return new FaceSensorPropertiesInternal(
472                 FACE_SENSOR_ID /* id */,
473                 isClass3 ? STRENGTH_STRONG : STRENGTH_CONVENIENCE,
474                 1 /* maxTemplatesAllowed */,
475                 componentInfo,
476                 FaceSensorProperties.TYPE_UNKNOWN,
477                 supportsFaceDetection /* supportsFaceDetection */,
478                 true /* supportsSelfIllumination */,
479                 false /* resetLockoutRequiresChallenge */);
480     }
481 
482     @After
tearDown()483     public void tearDown() {
484         if (mMockitoSession != null) {
485             mMockitoSession.finishMocking();
486         }
487         cleanupKeyguardUpdateMonitor();
488     }
489 
490     @Test
testInitialBatteryLevelRequested()491     public void testInitialBatteryLevelRequested() {
492         mTestableLooper.processAllMessages();
493 
494         assertThat(mKeyguardUpdateMonitor.mBatteryStatus).isNotNull();
495     }
496 
497     @Test
testReceiversRegistered()498     public void testReceiversRegistered() {
499         verify(mBroadcastDispatcher, atLeastOnce()).registerReceiverWithHandler(
500                 eq(mKeyguardUpdateMonitor.mBroadcastReceiver),
501                 any(IntentFilter.class), any(Handler.class));
502         verify(mBroadcastDispatcher, atLeastOnce()).registerReceiverWithHandler(
503                 eq(mKeyguardUpdateMonitor.mBroadcastAllReceiver),
504                 any(IntentFilter.class), any(Handler.class), eq(UserHandle.ALL));
505     }
506 
507     @Test
testSimStateInitialized()508     public void testSimStateInitialized() {
509         cleanupKeyguardUpdateMonitor();
510         final int subId = 3;
511         final int state = TelephonyManager.SIM_STATE_ABSENT;
512 
513         when(mTelephonyManager.getActiveModemCount()).thenReturn(1);
514         when(mTelephonyManager.getSimState(anyInt())).thenReturn(state);
515         when(mSubscriptionManager.getSubscriptionIds(anyInt())).thenReturn(new int[]{subId});
516 
517         KeyguardUpdateMonitor testKUM = new TestableKeyguardUpdateMonitor(mContext);
518 
519         mTestableLooper.processAllMessages();
520 
521         assertThat(testKUM.getSimState(subId)).isEqualTo(state);
522     }
523 
524     @Test
testIgnoresSimStateCallback_rebroadcast()525     public void testIgnoresSimStateCallback_rebroadcast() {
526         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
527 
528         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(), intent);
529         mTestableLooper.processAllMessages();
530         Assert.assertTrue("onSimStateChanged not called",
531                 mKeyguardUpdateMonitor.hasSimStateJustChanged());
532 
533         intent.putExtra(Intent.EXTRA_REBROADCAST_ON_UNLOCK, true);
534         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(), intent);
535         mTestableLooper.processAllMessages();
536         Assert.assertFalse("onSimStateChanged should have been skipped",
537                 mKeyguardUpdateMonitor.hasSimStateJustChanged());
538     }
539 
540     @Test
testTelephonyCapable_BootInitState()541     public void testTelephonyCapable_BootInitState() {
542         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
543     }
544 
545     @Test
testTelephonyCapable_SimState_Absent()546     public void testTelephonyCapable_SimState_Absent() {
547         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
548         intent.putExtra(Intent.EXTRA_SIM_STATE,
549                 Intent.SIM_STATE_ABSENT);
550         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
551                 putPhoneInfo(intent, null, false));
552         mTestableLooper.processAllMessages();
553         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
554     }
555 
556     @Test
testTelephonyCapable_SimState_CardIOError()557     public void testTelephonyCapable_SimState_CardIOError() {
558         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
559         intent.putExtra(Intent.EXTRA_SIM_STATE,
560                 Intent.SIM_STATE_CARD_IO_ERROR);
561         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
562                 putPhoneInfo(intent, null, false));
563         mTestableLooper.processAllMessages();
564         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
565     }
566 
567     @Test
testTelephonyCapable_SimInvalid_ServiceState_InService()568     public void testTelephonyCapable_SimInvalid_ServiceState_InService() {
569         // SERVICE_STATE - IN_SERVICE, but SIM_STATE is invalid TelephonyCapable should be False
570         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
571         Bundle data = new Bundle();
572         ServiceState state = new ServiceState();
573         state.setState(ServiceState.STATE_IN_SERVICE);
574         state.fillInNotifierBundle(data);
575         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
576                 , putPhoneInfo(intent, data, false));
577         mTestableLooper.processAllMessages();
578         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
579     }
580 
581     @Test
testTelephonyCapable_SimValid_ServiceState_PowerOff()582     public void testTelephonyCapable_SimValid_ServiceState_PowerOff() {
583         // Simulate AirplaneMode case, SERVICE_STATE - POWER_OFF, check TelephonyCapable False
584         // Only receive ServiceState callback IN_SERVICE -> OUT_OF_SERVICE -> POWER_OFF
585         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
586         intent.putExtra(Intent.EXTRA_SIM_STATE
587                 , Intent.SIM_STATE_LOADED);
588         Bundle data = new Bundle();
589         ServiceState state = new ServiceState();
590         state.setState(ServiceState.STATE_POWER_OFF);
591         state.fillInNotifierBundle(data);
592         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
593                 , putPhoneInfo(intent, data, true));
594         mTestableLooper.processAllMessages();
595         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
596     }
597 
598     /* Normal SIM inserted flow
599      * ServiceState:    ---OutOfServie----->PowerOff->OutOfServie--->InService
600      * SimState:        ----NOT_READY---->READY----------------------LOADED>>>
601      * Subscription:    --------null---->null--->"Chunghwa Telecom"-------->>>
602      * System:          -------------------------------BOOT_COMPLETED------>>>
603      * TelephonyCapable:(F)-(F)-(F)-(F)-(F)-(F)-(F)-(F)-(F)-(F)------(T)-(T)>>
604      */
605     @Test
testTelephonyCapable_BootInitState_ServiceState_OutOfService()606     public void testTelephonyCapable_BootInitState_ServiceState_OutOfService() {
607         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
608         Bundle data = new Bundle();
609         ServiceState state = new ServiceState();
610         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
611         state.fillInNotifierBundle(data);
612         intent.putExtras(data);
613         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
614                 , putPhoneInfo(intent, data, false));
615         mTestableLooper.processAllMessages();
616         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
617     }
618 
619     @Test
testTelephonyCapable_BootInitState_SimState_NotReady()620     public void testTelephonyCapable_BootInitState_SimState_NotReady() {
621         Bundle data = new Bundle();
622         ServiceState state = new ServiceState();
623         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
624         state.fillInNotifierBundle(data);
625         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
626         intent.putExtra(Intent.EXTRA_SIM_STATE
627                 , Intent.SIM_STATE_NOT_READY);
628         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
629                 , putPhoneInfo(intent, data, false));
630         mTestableLooper.processAllMessages();
631         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
632     }
633 
634     @Test
testTelephonyCapable_BootInitState_SimState_Ready()635     public void testTelephonyCapable_BootInitState_SimState_Ready() {
636         Bundle data = new Bundle();
637         ServiceState state = new ServiceState();
638         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
639         state.fillInNotifierBundle(data);
640         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
641         intent.putExtra(Intent.EXTRA_SIM_STATE
642                 , Intent.SIM_STATE_READY);
643         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
644                 , putPhoneInfo(intent, data, false));
645         mTestableLooper.processAllMessages();
646         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
647     }
648 
649     @Test
testTelephonyCapable_BootInitState_ServiceState_PowerOff()650     public void testTelephonyCapable_BootInitState_ServiceState_PowerOff() {
651         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
652         Bundle data = new Bundle();
653         ServiceState state = new ServiceState();
654         state.setState(ServiceState.STATE_POWER_OFF);
655         state.fillInNotifierBundle(data);
656         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
657                 , putPhoneInfo(intent, data, false));
658         mTestableLooper.processAllMessages();
659         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
660     }
661 
662     @Test
testTelephonyCapable_SimValid_ServiceState_InService()663     public void testTelephonyCapable_SimValid_ServiceState_InService() {
664         Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
665         Bundle data = new Bundle();
666         ServiceState state = new ServiceState();
667         state.setState(ServiceState.STATE_IN_SERVICE);
668         state.fillInNotifierBundle(data);
669         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
670                 , putPhoneInfo(intent, data, true));
671         mTestableLooper.processAllMessages();
672         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
673     }
674 
675     @Test
testTelephonyCapable_SimValid_SimState_Loaded()676     public void testTelephonyCapable_SimValid_SimState_Loaded() {
677         Bundle data = new Bundle();
678         ServiceState state = new ServiceState();
679         state.setState(ServiceState.STATE_IN_SERVICE);
680         state.fillInNotifierBundle(data);
681         Intent intentSimState = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
682         intentSimState.putExtra(Intent.EXTRA_SIM_STATE
683                 , Intent.SIM_STATE_LOADED);
684         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
685                 , putPhoneInfo(intentSimState, data, true));
686         mTestableLooper.processAllMessages();
687         // Even SimState Loaded, still need ACTION_SERVICE_STATE turn on mTelephonyCapable
688         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
689 
690         Intent intentServiceState = new Intent(Intent.ACTION_SERVICE_STATE);
691         intentSimState.putExtra(Intent.EXTRA_SIM_STATE
692                 , Intent.SIM_STATE_LOADED);
693         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
694                 , putPhoneInfo(intentServiceState, data, true));
695         mTestableLooper.processAllMessages();
696         assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
697     }
698 
699     @Test
serviceProvidersUpdated_broadcastTriggersInfoRefresh()700     public void serviceProvidersUpdated_broadcastTriggersInfoRefresh() {
701         // The callback is invoked once on init
702         verify(mTestCallback, times(1)).onRefreshCarrierInfo();
703 
704         // WHEN the SERVICE_PROVIDERS_UPDATED broadcast is sent
705         Intent intent = new Intent(TelephonyManager.ACTION_SERVICE_PROVIDERS_UPDATED);
706         intent.putExtra(TelephonyManager.EXTRA_SPN, "spn");
707         intent.putExtra(TelephonyManager.EXTRA_PLMN, "plmn");
708         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
709                 putPhoneInfo(intent, null, true));
710         mTestableLooper.processAllMessages();
711 
712         // THEN verify keyguardUpdateMonitorCallback receives a refresh callback
713         // Note that we have times(2) here because it's been called once already
714         verify(mTestCallback, times(2)).onRefreshCarrierInfo();
715     }
716 
717     @Test
testHandleSimStateChange_Unknown()718     public void testHandleSimStateChange_Unknown() {
719         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
720         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_UNKNOWN);
721         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
722                 putPhoneInfo(intent, null, false));
723         mTestableLooper.processAllMessages();
724         Assert.assertEquals(TelephonyManager.SIM_STATE_UNKNOWN,
725                 mKeyguardUpdateMonitor.getCachedSimState());
726     }
727 
728     @Test
testHandleSimStateChange_Absent()729     public void testHandleSimStateChange_Absent() {
730         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
731         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_ABSENT);
732         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
733                 putPhoneInfo(intent, null, false));
734         mTestableLooper.processAllMessages();
735         Assert.assertEquals(TelephonyManager.SIM_STATE_ABSENT,
736                 mKeyguardUpdateMonitor.getCachedSimState());
737     }
738 
739     @Test
testHandleSimStateChange_CardIOError()740     public void testHandleSimStateChange_CardIOError() {
741         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
742         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_CARD_IO_ERROR);
743         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_STATE_CARD_IO_ERROR);
744         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
745                 putPhoneInfo(intent, null, false));
746         mTestableLooper.processAllMessages();
747         Assert.assertEquals(TelephonyManager.SIM_STATE_CARD_IO_ERROR,
748                 mKeyguardUpdateMonitor.getCachedSimState());
749     }
750 
751     @Test
testHandleSimStateChange_CardRestricted()752     public void testHandleSimStateChange_CardRestricted() {
753         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
754         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_CARD_RESTRICTED);
755         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_STATE_CARD_RESTRICTED);
756         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
757                 putPhoneInfo(intent, null, false));
758         mTestableLooper.processAllMessages();
759         Assert.assertEquals(TelephonyManager.SIM_STATE_CARD_RESTRICTED,
760                 mKeyguardUpdateMonitor.getCachedSimState());
761     }
762 
763     @Test
testHandleSimStateChange_Locked()764     public void testHandleSimStateChange_Locked() {
765         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
766         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_LOCKED);
767 
768         // locked on PIN1
769         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_LOCKED_ON_PIN);
770         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
771                 putPhoneInfo(intent, null, true));
772         mTestableLooper.processAllMessages();
773         Assert.assertEquals(TelephonyManager.SIM_STATE_PIN_REQUIRED,
774                 mKeyguardUpdateMonitor.getCachedSimState());
775 
776         // locked on PUK1
777         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_LOCKED_ON_PUK);
778         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
779                 putPhoneInfo(intent, null, true));
780         mTestableLooper.processAllMessages();
781         Assert.assertEquals(TelephonyManager.SIM_STATE_PUK_REQUIRED,
782                 mKeyguardUpdateMonitor.getCachedSimState());
783 
784         // locked on network personalization
785         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_LOCKED_NETWORK);
786         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
787                 putPhoneInfo(intent, null, true));
788         mTestableLooper.processAllMessages();
789         Assert.assertEquals(TelephonyManager.SIM_STATE_NETWORK_LOCKED,
790                 mKeyguardUpdateMonitor.getCachedSimState());
791 
792         // permanently disabled due to puk fails
793         intent.putExtra(Intent.EXTRA_SIM_LOCKED_REASON, Intent.SIM_ABSENT_ON_PERM_DISABLED);
794         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
795                 putPhoneInfo(intent, null, true));
796         mTestableLooper.processAllMessages();
797         Assert.assertEquals(TelephonyManager.SIM_STATE_PERM_DISABLED,
798                 mKeyguardUpdateMonitor.getCachedSimState());
799     }
800 
801     @Test
testHandleSimStateChange_NotReady()802     public void testHandleSimStateChange_NotReady() {
803         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
804         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_NOT_READY);
805         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
806                 putPhoneInfo(intent, null, false));
807         mTestableLooper.processAllMessages();
808         Assert.assertEquals(TelephonyManager.SIM_STATE_NOT_READY,
809                 mKeyguardUpdateMonitor.getCachedSimState());
810     }
811 
812     @Test
testHandleSimStateChange_Ready()813     public void testHandleSimStateChange_Ready() {
814         Intent intent = new Intent(Intent.ACTION_SIM_STATE_CHANGED);
815 
816         // ICC IMSI is ready in property
817         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_IMSI);
818         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
819                 putPhoneInfo(intent, null, false));
820         mTestableLooper.processAllMessages();
821         Assert.assertEquals(TelephonyManager.SIM_STATE_READY,
822                 mKeyguardUpdateMonitor.getCachedSimState());
823 
824         // ICC is ready to access
825         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_READY);
826         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
827                 putPhoneInfo(intent, null, false));
828         mTestableLooper.processAllMessages();
829         Assert.assertEquals(TelephonyManager.SIM_STATE_READY,
830                 mKeyguardUpdateMonitor.getCachedSimState());
831 
832         // all ICC records, including IMSI, are loaded
833         intent.putExtra(Intent.EXTRA_SIM_STATE, Intent.SIM_STATE_LOADED);
834         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(),
835                 putPhoneInfo(intent, null, true));
836         mTestableLooper.processAllMessages();
837         Assert.assertEquals(TelephonyManager.SIM_STATE_READY,
838                 mKeyguardUpdateMonitor.getCachedSimState());
839     }
840 
841     @Test
testTriesToAuthenticateFingerprint_whenKeyguard()842     public void testTriesToAuthenticateFingerprint_whenKeyguard() {
843         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
844         mTestableLooper.processAllMessages();
845 
846         verifyFingerprintAuthenticateCall();
847         verifyFingerprintDetectNeverCalled();
848     }
849 
850     @Test
test_doesNotTryToAuthenticateFingerprint_whenAuthenticatorsNotRegistered()851     public void test_doesNotTryToAuthenticateFingerprint_whenAuthenticatorsNotRegistered() {
852         when(mAuthController.areAllFingerprintAuthenticatorsRegistered()).thenReturn(false);
853 
854         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
855         mTestableLooper.processAllMessages();
856 
857         verifyFingerprintAuthenticateNeverCalled();
858         verifyFingerprintDetectNeverCalled();
859     }
860 
861     @Test
testOnlyDetectFingerprint_whenFingerprintUnlockNotAllowed()862     public void testOnlyDetectFingerprint_whenFingerprintUnlockNotAllowed() {
863         givenDetectFingerprintWithClearingFingerprintManagerInvocations();
864 
865         verifyFingerprintAuthenticateNeverCalled();
866         verifyFingerprintDetectCall();
867     }
868 
869     @Test
whenDetectFingerprint_biometricDetectCallback()870     public void whenDetectFingerprint_biometricDetectCallback() {
871         ArgumentCaptor<FingerprintManager.FingerprintDetectionCallback> fpDetectCallbackCaptor =
872                 ArgumentCaptor.forClass(FingerprintManager.FingerprintDetectionCallback.class);
873 
874         givenDetectFingerprintWithClearingFingerprintManagerInvocations();
875         verify(mFingerprintManager).detectFingerprint(
876                 any(), fpDetectCallbackCaptor.capture(), any());
877         fpDetectCallbackCaptor.getValue().onFingerprintDetected(0, 0, true);
878 
879         // THEN verify keyguardUpdateMonitorCallback receives a detect callback
880         // and NO authenticate callbacks
881         verify(mTestCallback).onBiometricDetected(
882                 eq(0), eq(BiometricSourceType.FINGERPRINT), eq(true));
883         verify(mTestCallback, never()).onBiometricAuthenticated(
884                 anyInt(), any(), anyBoolean());
885     }
886 
887     @Test
whenDetectFace_biometricDetectCallback()888     public void whenDetectFace_biometricDetectCallback() throws RemoteException {
889         ArgumentCaptor<FaceManager.FaceDetectionCallback> faceDetectCallbackCaptor =
890                 ArgumentCaptor.forClass(FaceManager.FaceDetectionCallback.class);
891 
892         givenDetectFace();
893         verify(mFaceManager).detectFace(any(), faceDetectCallbackCaptor.capture(), any());
894         faceDetectCallbackCaptor.getValue().onFaceDetected(0, 0, false);
895 
896         // THEN verify keyguardUpdateMonitorCallback receives a detect callback
897         // and NO authenticate callbacks
898         verify(mTestCallback).onBiometricDetected(
899                 eq(0), eq(BiometricSourceType.FACE), eq(false));
900         verify(mTestCallback, never()).onBiometricAuthenticated(
901                 anyInt(), any(), anyBoolean());
902     }
903 
904     @Test
testUnlockingWithFaceAllowed_strongAuthTrackerUnlockingWithBiometricAllowed()905     public void testUnlockingWithFaceAllowed_strongAuthTrackerUnlockingWithBiometricAllowed() {
906         // GIVEN unlocking with biometric is allowed
907         primaryAuthNotRequiredByStrongAuthTracker();
908 
909         // THEN unlocking with face and fp is allowed
910         Assert.assertTrue(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
911                 BiometricSourceType.FACE));
912         Assert.assertTrue(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
913                 BiometricSourceType.FINGERPRINT));
914     }
915 
916     @Test
testUnlockingWithFaceAllowed_strongAuthTrackerUnlockingWithBiometricNotAllowed()917     public void testUnlockingWithFaceAllowed_strongAuthTrackerUnlockingWithBiometricNotAllowed() {
918         // GIVEN unlocking with biometric is not allowed
919         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
920 
921         // THEN unlocking with face is not allowed
922         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
923                 BiometricSourceType.FACE));
924     }
925 
926     @Test
class3FingerprintLockOut_lockOutClass1Face()927     public void class3FingerprintLockOut_lockOutClass1Face() throws RemoteException {
928         setupFaceAuth(/* isClass3 */ false);
929         setupFingerprintAuth(/* isClass3 */ true);
930 
931         // GIVEN primary auth is not required by StrongAuthTracker
932         primaryAuthNotRequiredByStrongAuthTracker();
933 
934         // WHEN fingerprint (class 3) is lock out
935         fingerprintErrorTemporaryLockOut();
936 
937         // THEN unlocking with face is not allowed
938         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
939                 BiometricSourceType.FACE));
940     }
941 
942     @Test
class3FingerprintLockOut_lockOutClass3Face()943     public void class3FingerprintLockOut_lockOutClass3Face() throws RemoteException {
944         setupFaceAuth(/* isClass3 */ true);
945         setupFingerprintAuth(/* isClass3 */ true);
946 
947         // GIVEN primary auth is not required by StrongAuthTracker
948         primaryAuthNotRequiredByStrongAuthTracker();
949 
950         // WHEN fingerprint (class 3) is lock out
951         fingerprintErrorTemporaryLockOut();
952 
953         // THEN unlocking with face is not allowed
954         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
955                 BiometricSourceType.FACE));
956     }
957 
958     @Test
class3FaceLockOut_lockOutClass3Fingerprint()959     public void class3FaceLockOut_lockOutClass3Fingerprint() throws RemoteException {
960         setupFaceAuth(/* isClass3 */ true);
961         setupFingerprintAuth(/* isClass3 */ true);
962 
963         // GIVEN primary auth is not required by StrongAuthTracker
964         primaryAuthNotRequiredByStrongAuthTracker();
965 
966         // WHEN face (class 3) is lock out
967         faceAuthLockOut();
968 
969         // THEN unlocking with fingerprint is not allowed
970         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
971                 BiometricSourceType.FINGERPRINT));
972     }
973 
974     @Test
class1FaceLockOut_doesNotLockOutClass3Fingerprint()975     public void class1FaceLockOut_doesNotLockOutClass3Fingerprint() throws RemoteException {
976         setupFaceAuth(/* isClass3 */ false);
977         setupFingerprintAuth(/* isClass3 */ true);
978 
979         // GIVEN primary auth is not required by StrongAuthTracker
980         primaryAuthNotRequiredByStrongAuthTracker();
981 
982         // WHEN face (class 1) is lock out
983         faceAuthLockOut();
984 
985         // THEN unlocking with fingerprint is still allowed
986         Assert.assertTrue(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
987                 BiometricSourceType.FINGERPRINT));
988     }
989 
990     @Test
testUnlockingWithFpAllowed_strongAuthTrackerUnlockingWithBiometricNotAllowed()991     public void testUnlockingWithFpAllowed_strongAuthTrackerUnlockingWithBiometricNotAllowed() {
992         // GIVEN unlocking with biometric is not allowed
993         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
994 
995         // THEN unlocking with fingerprint is not allowed
996         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
997                 BiometricSourceType.FINGERPRINT));
998     }
999 
1000     @Test
testUnlockingWithFpAllowed_fingerprintLockout()1001     public void testUnlockingWithFpAllowed_fingerprintLockout() {
1002         // GIVEN unlocking with biometric is allowed
1003         primaryAuthNotRequiredByStrongAuthTracker();
1004 
1005         // WHEN fingerprint is lock out
1006         fingerprintErrorTemporaryLockOut();
1007 
1008         // THEN unlocking with fingerprint is not allowed
1009         Assert.assertFalse(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
1010                 BiometricSourceType.FINGERPRINT));
1011     }
1012 
1013     @Test
trustAgentHasTrust()1014     public void trustAgentHasTrust() {
1015         // WHEN user has trust
1016         mKeyguardUpdateMonitor.onTrustChanged(true, true, getCurrentUser(), 0, null);
1017 
1018         // THEN user is considered as "having trust" and bouncer can be skipped
1019         Assert.assertTrue(mKeyguardUpdateMonitor.getUserHasTrust(getCurrentUser()));
1020         Assert.assertTrue(mKeyguardUpdateMonitor.getUserCanSkipBouncer(getCurrentUser()));
1021     }
1022 
1023     @Test
testOnEnabledTrustAgentsChangedCallback()1024     public void testOnEnabledTrustAgentsChangedCallback() {
1025         final Random random = new Random();
1026         final int userId = random.nextInt();
1027         final KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1028 
1029         mKeyguardUpdateMonitor.registerCallback(callback);
1030         mKeyguardUpdateMonitor.onEnabledTrustAgentsChanged(userId);
1031 
1032         verify(callback).onEnabledTrustAgentsChanged(eq(userId));
1033     }
1034 
1035     @Test
trustAgentHasTrust_fingerprintLockout()1036     public void trustAgentHasTrust_fingerprintLockout() {
1037         // GIVEN user has trust
1038         mKeyguardUpdateMonitor.onTrustChanged(true, true, getCurrentUser(), 0, null);
1039         Assert.assertTrue(mKeyguardUpdateMonitor.getUserHasTrust(getCurrentUser()));
1040 
1041         // WHEN fingerprint is lock out
1042         fingerprintErrorTemporaryLockOut();
1043 
1044         // THEN user is NOT considered as "having trust" and bouncer cannot be skipped
1045         Assert.assertFalse(mKeyguardUpdateMonitor.getUserHasTrust(getCurrentUser()));
1046         Assert.assertFalse(mKeyguardUpdateMonitor.getUserCanSkipBouncer(getCurrentUser()));
1047     }
1048 
1049     @Test
testTriesToAuthenticate_whenBouncer()1050     public void testTriesToAuthenticate_whenBouncer() {
1051         setKeyguardBouncerVisibility(true);
1052         verifyFaceAuthenticateCall();
1053     }
1054 
1055     @Test
testNoStartAuthenticate_whenAboutToShowBouncer()1056     public void testNoStartAuthenticate_whenAboutToShowBouncer() {
1057         mKeyguardUpdateMonitor.sendPrimaryBouncerChanged(
1058                 /* bouncerIsOrWillBeShowing */ true, /* bouncerFullyShown */ false);
1059 
1060         verifyFaceAuthenticateNeverCalled();
1061     }
1062 
1063     @Test
testTriesToAuthenticate_whenKeyguard()1064     public void testTriesToAuthenticate_whenKeyguard() {
1065         keyguardIsVisible();
1066         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1067         mTestableLooper.processAllMessages();
1068 
1069         verifyFaceAuthenticateCall();
1070         verify(mUiEventLogger).logWithInstanceIdAndPosition(
1071                 eq(FaceAuthUiEvent.FACE_AUTH_UPDATED_STARTED_WAKING_UP),
1072                 eq(0),
1073                 eq(null),
1074                 any(),
1075                 eq(PowerManager.WAKE_REASON_POWER_BUTTON));
1076     }
1077 
1078     @Test
skipsAuthentication_whenStatusBarShadeLocked()1079     public void skipsAuthentication_whenStatusBarShadeLocked() {
1080         mStatusBarStateListener.onStateChanged(StatusBarState.SHADE_LOCKED);
1081         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1082         mTestableLooper.processAllMessages();
1083 
1084         keyguardIsVisible();
1085         verifyFaceAuthenticateNeverCalled();
1086     }
1087 
1088     @Test
skipsAuthentication_whenStrongAuthRequired_nonBypass()1089     public void skipsAuthentication_whenStrongAuthRequired_nonBypass() {
1090         lockscreenBypassIsNotAllowed();
1091         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
1092 
1093         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1094         mTestableLooper.processAllMessages();
1095         keyguardIsVisible();
1096 
1097         verifyFaceAuthenticateNeverCalled();
1098     }
1099 
1100     @Test
nofaceDetect_whenStrongAuthRequiredAndBypassUdfpsSupportedAndFpRunning()1101     public void nofaceDetect_whenStrongAuthRequiredAndBypassUdfpsSupportedAndFpRunning()
1102             throws RemoteException {
1103         // GIVEN bypass is enabled, face detection is supported
1104         lockscreenBypassIsAllowed();
1105         supportsFaceDetection();
1106         keyguardIsVisible();
1107 
1108         // GIVEN udfps is supported and strong auth required for weak biometrics (face) only
1109         givenUdfpsSupported();
1110         primaryAuthRequiredForWeakBiometricOnly(); // allows class3 fp to run but not class1 face
1111 
1112         // WHEN the device wakes up
1113         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1114         mTestableLooper.processAllMessages();
1115 
1116         // THEN face detect and authenticate are NOT triggered
1117         verifyFaceDetectNeverCalled();
1118         verifyFaceAuthenticateNeverCalled();
1119 
1120         // THEN biometric help message sent to callback
1121         verify(mTestCallback).onBiometricHelp(
1122                 eq(BIOMETRIC_HELP_FACE_NOT_AVAILABLE), anyString(), eq(BiometricSourceType.FACE));
1123     }
1124 
1125     @Test
faceDetect_whenStrongAuthRequiredAndBypass()1126     public void faceDetect_whenStrongAuthRequiredAndBypass() throws RemoteException {
1127         givenDetectFace();
1128 
1129         // FACE detect is triggered, not authenticate
1130         verifyFaceDetectCall();
1131         verifyFaceAuthenticateNeverCalled();
1132 
1133         // WHEN bouncer becomes visible
1134         setKeyguardBouncerVisibility(true);
1135         clearInvocations(mFaceManager);
1136 
1137         // THEN face scanning is not run
1138         mKeyguardUpdateMonitor.requestFaceAuth(FaceAuthApiRequestReason.UDFPS_POINTER_DOWN);
1139         verifyFaceAuthenticateNeverCalled();
1140         verifyFaceDetectNeverCalled();
1141     }
1142 
1143     @Test
noFaceDetect_whenStrongAuthRequiredAndBypass_faceDetectionUnsupported()1144     public void noFaceDetect_whenStrongAuthRequiredAndBypass_faceDetectionUnsupported() {
1145         // GIVEN bypass is enabled, face detection is NOT supported and strong auth is required
1146         lockscreenBypassIsAllowed();
1147         primaryAuthRequiredEncrypted();
1148         keyguardIsVisible();
1149 
1150         // WHEN the device wakes up
1151         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1152         mTestableLooper.processAllMessages();
1153 
1154         // FACE detect and authenticate are NOT triggered
1155         verifyFaceDetectNeverCalled();
1156         verifyFaceAuthenticateNeverCalled();
1157     }
1158 
1159     @Test
requestFaceAuth_whenFaceAuthWasStarted_returnsTrue()1160     public void requestFaceAuth_whenFaceAuthWasStarted_returnsTrue() throws RemoteException {
1161         // This satisfies all the preconditions to run face auth.
1162         keyguardNotGoingAway();
1163         currentUserIsSystem();
1164         currentUserDoesNotHaveTrust();
1165         biometricsNotDisabledThroughDevicePolicyManager();
1166         biometricsEnabledForCurrentUser();
1167         userNotCurrentlySwitching();
1168         bouncerFullyVisibleAndNotGoingToSleep();
1169         mTestableLooper.processAllMessages();
1170 
1171         boolean didFaceAuthRun = mKeyguardUpdateMonitor.requestFaceAuth(
1172                 NOTIFICATION_PANEL_CLICKED);
1173 
1174         assertThat(didFaceAuthRun).isTrue();
1175     }
1176 
1177     @Test
requestFaceAuth_whenFaceAuthWasNotStarted_returnsFalse()1178     public void requestFaceAuth_whenFaceAuthWasNotStarted_returnsFalse() throws RemoteException {
1179         // This ensures face auth won't run.
1180         biometricsDisabledForCurrentUser();
1181         mTestableLooper.processAllMessages();
1182 
1183         boolean didFaceAuthRun = mKeyguardUpdateMonitor.requestFaceAuth(
1184                 NOTIFICATION_PANEL_CLICKED);
1185 
1186         assertThat(didFaceAuthRun).isFalse();
1187     }
1188 
1189     @Test
testTriesToAuthenticate_whenAssistant()1190     public void testTriesToAuthenticate_whenAssistant() {
1191         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1192         mKeyguardUpdateMonitor.setAssistantVisible(true);
1193 
1194         verifyFaceAuthenticateCall();
1195     }
1196 
1197     @Test
doesNotTryToAuthenticateWhenKeyguardIsNotShowingButOccluded_whenAssistant()1198     public void doesNotTryToAuthenticateWhenKeyguardIsNotShowingButOccluded_whenAssistant() {
1199         mKeyguardUpdateMonitor.setKeyguardShowing(false, true);
1200         mKeyguardUpdateMonitor.setAssistantVisible(true);
1201 
1202         verifyFaceAuthenticateNeverCalled();
1203     }
1204 
1205     @Test
noFpListeningWhenKeyguardIsOccluded_unlessAlternateBouncerShowing()1206     public void noFpListeningWhenKeyguardIsOccluded_unlessAlternateBouncerShowing() {
1207         // GIVEN device is awake but occluded
1208         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1209         mKeyguardUpdateMonitor.setKeyguardShowing(false, true);
1210 
1211         // THEN fingerprint shouldn't listen
1212         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isFalse();
1213         verifyFingerprintAuthenticateNeverCalled();
1214         // WHEN alternate bouncer is shown
1215         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1216         mKeyguardUpdateMonitor.setAlternateBouncerShowing(true);
1217 
1218         // THEN make sure FP listening begins
1219         verifyFingerprintAuthenticateCall();
1220     }
1221 
1222     @Test
testTriesToAuthenticate_whenTrustOnAgentKeyguard_ifBypass()1223     public void testTriesToAuthenticate_whenTrustOnAgentKeyguard_ifBypass() {
1224         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1225         mTestableLooper.processAllMessages();
1226         lockscreenBypassIsAllowed();
1227         mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, true /* newlyUnlocked */,
1228                 KeyguardUpdateMonitor.getCurrentUser(), 0 /* flags */,
1229                 new ArrayList<>());
1230         keyguardIsVisible();
1231         verifyFaceAuthenticateCall();
1232     }
1233 
1234     @Test
faceUnlockDoesNotRunWhenDeviceIsGoingToSleepWithAssistantVisible()1235     public void faceUnlockDoesNotRunWhenDeviceIsGoingToSleepWithAssistantVisible() {
1236         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1237         mKeyguardUpdateMonitor.setAssistantVisible(true);
1238 
1239         verifyFaceAuthenticateCall();
1240         mTestableLooper.processAllMessages();
1241         clearInvocations(mFaceManager);
1242 
1243         // Device going to sleep while assistant is visible
1244         mKeyguardUpdateMonitor.handleStartedGoingToSleep(0);
1245         mKeyguardUpdateMonitor.handleFinishedGoingToSleep(0);
1246         mTestableLooper.moveTimeForward(DEFAULT_CANCEL_SIGNAL_TIMEOUT);
1247         mTestableLooper.processAllMessages();
1248 
1249         mKeyguardUpdateMonitor.handleKeyguardReset();
1250 
1251         assertThat(mKeyguardUpdateMonitor.isFaceDetectionRunning()).isFalse();
1252         verifyFaceAuthenticateNeverCalled();
1253     }
1254 
1255     @Test
testIgnoresAuth_whenTrustAgentOnKeyguard_withoutBypass()1256     public void testIgnoresAuth_whenTrustAgentOnKeyguard_withoutBypass() {
1257         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1258         mTestableLooper.processAllMessages();
1259         mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, true /* newlyUnlocked */,
1260                 KeyguardUpdateMonitor.getCurrentUser(), 0 /* flags */, new ArrayList<>());
1261         keyguardIsVisible();
1262         verifyFaceAuthenticateNeverCalled();
1263     }
1264 
1265     @Test
testNoFaceAuth_whenLockDown()1266     public void testNoFaceAuth_whenLockDown() {
1267         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
1268         userDeviceLockDown();
1269 
1270         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1271         keyguardIsVisible();
1272         mTestableLooper.processAllMessages();
1273 
1274         verifyFaceAuthenticateNeverCalled();
1275         verifyFaceDetectNeverCalled();
1276     }
1277 
1278     @Test
testFingerprintPowerPressed_restartsFingerprintListeningStateWithDelay()1279     public void testFingerprintPowerPressed_restartsFingerprintListeningStateWithDelay() {
1280         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
1281                 .onAuthenticationError(FingerprintManager.BIOMETRIC_ERROR_POWER_PRESSED, "");
1282 
1283         // THEN doesn't authenticate immediately
1284         verifyFingerprintAuthenticateNeverCalled();
1285 
1286         // WHEN all messages (with delays) are processed
1287         mTestableLooper.moveTimeForward(HAL_POWER_PRESS_TIMEOUT);
1288         mTestableLooper.processAllMessages();
1289 
1290         // THEN fingerprint manager attempts to authenticate again
1291         verifyFingerprintAuthenticateCall();
1292     }
1293 
1294     @Test
testOnFaceAuthenticated_skipsFaceWhenAuthenticated()1295     public void testOnFaceAuthenticated_skipsFaceWhenAuthenticated() {
1296         // test whether face will be skipped if authenticated, so the value of isClass3Biometric
1297         // doesn't matter here
1298         mKeyguardUpdateMonitor.onFaceAuthenticated(KeyguardUpdateMonitor.getCurrentUser(),
1299                 true /* isClass3Biometric */);
1300         setKeyguardBouncerVisibility(true);
1301         mTestableLooper.processAllMessages();
1302 
1303         verifyFaceAuthenticateNeverCalled();
1304     }
1305 
1306     @Test
testFaceAndFingerprintLockout_onlyFace()1307     public void testFaceAndFingerprintLockout_onlyFace() {
1308         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1309         mTestableLooper.processAllMessages();
1310         keyguardIsVisible();
1311 
1312         faceAuthLockOut();
1313 
1314         verify(mLockPatternUtils, never()).requireStrongAuth(anyInt(), anyInt());
1315     }
1316 
1317     @Test
testFaceAndFingerprintLockout_onlyFingerprint()1318     public void testFaceAndFingerprintLockout_onlyFingerprint() {
1319         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1320         mTestableLooper.processAllMessages();
1321         keyguardIsVisible();
1322 
1323         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
1324                 .onAuthenticationError(FINGERPRINT_ERROR_LOCKOUT_PERMANENT, "");
1325 
1326         verify(mLockPatternUtils).requireStrongAuth(anyInt(), anyInt());
1327     }
1328 
1329     @Test
testFaceAndFingerprintLockout()1330     public void testFaceAndFingerprintLockout() {
1331         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1332         mTestableLooper.processAllMessages();
1333         keyguardIsVisible();
1334 
1335         faceAuthLockOut();
1336         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
1337                 .onAuthenticationError(FINGERPRINT_ERROR_LOCKOUT_PERMANENT, "");
1338 
1339         verify(mLockPatternUtils).requireStrongAuth(anyInt(), anyInt());
1340     }
1341 
1342     @Test
testGetUserCanSkipBouncer_whenFace()1343     public void testGetUserCanSkipBouncer_whenFace() {
1344         int user = KeyguardUpdateMonitor.getCurrentUser();
1345         mKeyguardUpdateMonitor.onFaceAuthenticated(user, true /* isClass3Biometric */);
1346         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
1347     }
1348 
1349     @Test
testGetUserCanSkipBouncer_whenFace_nonStrongAndDisallowed()1350     public void testGetUserCanSkipBouncer_whenFace_nonStrongAndDisallowed() {
1351         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(false /* isClass3Biometric */))
1352                 .thenReturn(false);
1353         int user = KeyguardUpdateMonitor.getCurrentUser();
1354         mKeyguardUpdateMonitor.onFaceAuthenticated(user, false /* isClass3Biometric */);
1355         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isFalse();
1356     }
1357 
1358     @Test
testGetUserCanSkipBouncer_whenFingerprint()1359     public void testGetUserCanSkipBouncer_whenFingerprint() {
1360         int user = KeyguardUpdateMonitor.getCurrentUser();
1361         mKeyguardUpdateMonitor.onFingerprintAuthenticated(user, true /* isClass3Biometric */);
1362         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
1363     }
1364 
1365     @Test
testGetUserCanSkipBouncer_whenFingerprint_nonStrongAndDisallowed()1366     public void testGetUserCanSkipBouncer_whenFingerprint_nonStrongAndDisallowed() {
1367         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(false /* isClass3Biometric */))
1368                 .thenReturn(false);
1369         int user = KeyguardUpdateMonitor.getCurrentUser();
1370         mKeyguardUpdateMonitor.onFingerprintAuthenticated(user, false /* isClass3Biometric */);
1371         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isFalse();
1372     }
1373 
1374     @Test
testBiometricsCleared_whenUserSwitches()1375     public void testBiometricsCleared_whenUserSwitches() throws Exception {
1376         final BiometricAuthenticated dummyAuthentication =
1377                 new BiometricAuthenticated(true /* authenticated */, true /* strong */);
1378         mKeyguardUpdateMonitor.mUserFaceAuthenticated.put(0 /* user */, dummyAuthentication);
1379         mKeyguardUpdateMonitor.mUserFingerprintAuthenticated.put(0 /* user */, dummyAuthentication);
1380         assertThat(mKeyguardUpdateMonitor.mUserFingerprintAuthenticated.size()).isEqualTo(1);
1381         assertThat(mKeyguardUpdateMonitor.mUserFaceAuthenticated.size()).isEqualTo(1);
1382 
1383         mKeyguardUpdateMonitor.handleUserSwitching(10 /* user */, new CountDownLatch(0));
1384         assertThat(mKeyguardUpdateMonitor.mUserFingerprintAuthenticated.size()).isEqualTo(0);
1385         assertThat(mKeyguardUpdateMonitor.mUserFaceAuthenticated.size()).isEqualTo(0);
1386     }
1387 
1388     @Test
testMultiUserJankMonitor_whenUserSwitches()1389     public void testMultiUserJankMonitor_whenUserSwitches() throws Exception {
1390         mKeyguardUpdateMonitor.handleUserSwitchComplete(10 /* user */);
1391         verify(mInteractionJankMonitor).end(InteractionJankMonitor.CUJ_USER_SWITCH);
1392         verify(mLatencyTracker).onActionEnd(LatencyTracker.ACTION_USER_SWITCH);
1393     }
1394 
1395     @Test
testMultiUserLockoutChanged_whenUserSwitches()1396     public void testMultiUserLockoutChanged_whenUserSwitches() {
1397         testMultiUserLockout_whenUserSwitches(BiometricConstants.BIOMETRIC_LOCKOUT_PERMANENT,
1398                 BiometricConstants.BIOMETRIC_LOCKOUT_PERMANENT);
1399     }
1400 
1401     @Test
testMultiUserLockoutNotChanged_whenUserSwitches()1402     public void testMultiUserLockoutNotChanged_whenUserSwitches() {
1403         testMultiUserLockout_whenUserSwitches(BiometricConstants.BIOMETRIC_LOCKOUT_NONE,
1404                 BiometricConstants.BIOMETRIC_LOCKOUT_NONE);
1405     }
1406 
testMultiUserLockout_whenUserSwitches( @iometricConstants.LockoutMode int fingerprintLockoutMode, @BiometricConstants.LockoutMode int faceLockoutMode)1407     private void testMultiUserLockout_whenUserSwitches(
1408             @BiometricConstants.LockoutMode int fingerprintLockoutMode,
1409             @BiometricConstants.LockoutMode int faceLockoutMode) {
1410         final int newUser = 12;
1411         final boolean faceLockOut =
1412                 faceLockoutMode != BiometricConstants.BIOMETRIC_LOCKOUT_NONE;
1413         final boolean fpLockOut =
1414                 fingerprintLockoutMode != BiometricConstants.BIOMETRIC_LOCKOUT_NONE;
1415 
1416         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1417         mTestableLooper.processAllMessages();
1418         keyguardIsVisible();
1419 
1420         verifyFaceAuthenticateCall();
1421         verifyFingerprintAuthenticateCall();
1422 
1423         when(mFingerprintManager.getLockoutModeForUser(eq(FINGERPRINT_SENSOR_ID), eq(newUser)))
1424                 .thenReturn(fingerprintLockoutMode);
1425         when(mFaceManager.getLockoutModeForUser(eq(FACE_SENSOR_ID), eq(newUser)))
1426                 .thenReturn(faceLockoutMode);
1427         final CancellationSignal faceCancel = spy(mKeyguardUpdateMonitor.mFaceCancelSignal);
1428         final CancellationSignal fpCancel = spy(mKeyguardUpdateMonitor.mFingerprintCancelSignal);
1429         mKeyguardUpdateMonitor.mFaceCancelSignal = faceCancel;
1430         mKeyguardUpdateMonitor.mFingerprintCancelSignal = fpCancel;
1431         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1432         mKeyguardUpdateMonitor.registerCallback(callback);
1433 
1434         mKeyguardUpdateMonitor.handleUserSwitchComplete(newUser);
1435         mTestableLooper.processAllMessages();
1436 
1437         // THEN face and fingerprint listening are always cancelled immediately
1438         verify(faceCancel).cancel();
1439         verify(callback).onBiometricRunningStateChanged(
1440                 eq(false), eq(BiometricSourceType.FACE));
1441         verify(fpCancel).cancel();
1442         verify(callback).onBiometricRunningStateChanged(
1443                 eq(false), eq(BiometricSourceType.FINGERPRINT));
1444 
1445         // THEN locked out states are updated
1446         assertThat(mKeyguardUpdateMonitor.isFingerprintLockedOut()).isEqualTo(fpLockOut);
1447         assertThat(mKeyguardUpdateMonitor.isFaceLockedOut()).isEqualTo(faceLockOut);
1448 
1449         // Fingerprint should be cancelled on lockout if going to lockout state, else
1450         // restarted if it's not
1451         assertThat(mKeyguardUpdateMonitor.mFingerprintRunningState)
1452                 .isEqualTo(BIOMETRIC_STATE_CANCELLING_RESTARTING);
1453     }
1454 
1455     @Test
testGetUserCanSkipBouncer_whenTrust()1456     public void testGetUserCanSkipBouncer_whenTrust() {
1457         int user = KeyguardUpdateMonitor.getCurrentUser();
1458         mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, true /* newlyUnlocked */,
1459                 user, 0 /* flags */, new ArrayList<>());
1460         assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
1461     }
1462 
1463     @Test
testGetSubscriptionInfo_whenInGroupedSubWithOpportunistic()1464     public void testGetSubscriptionInfo_whenInGroupedSubWithOpportunistic() {
1465         List<SubscriptionInfo> list = new ArrayList<>();
1466         list.add(TEST_SUBSCRIPTION);
1467         list.add(TEST_SUBSCRIPTION_2);
1468         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
1469         mKeyguardUpdateMonitor.mPhoneStateListener.onActiveDataSubscriptionIdChanged(
1470                 TEST_SUBSCRIPTION_2.getSubscriptionId());
1471         mTestableLooper.processAllMessages();
1472 
1473         List<SubscriptionInfo> listToVerify = mKeyguardUpdateMonitor
1474                 .getFilteredSubscriptionInfo();
1475         assertThat(listToVerify.size()).isEqualTo(1);
1476         assertThat(listToVerify.get(0)).isEqualTo(TEST_SUBSCRIPTION_2);
1477     }
1478 
1479     @Test
testActiveSubscriptionBecomesInactive()1480     public void testActiveSubscriptionBecomesInactive() {
1481         List<SubscriptionInfo> list = new ArrayList<>();
1482         list.add(TEST_SUBSCRIPTION);
1483         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
1484         mKeyguardUpdateMonitor.mPhoneStateListener.onActiveDataSubscriptionIdChanged(
1485                 TEST_SUBSCRIPTION.getSubscriptionId());
1486         mTestableLooper.processAllMessages();
1487         assertThat(mKeyguardUpdateMonitor.mSimDatas.get(TEST_SUBSCRIPTION.getSubscriptionId()))
1488                 .isNotNull();
1489 
1490         when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(null);
1491         mKeyguardUpdateMonitor.mPhoneStateListener.onActiveDataSubscriptionIdChanged(
1492                 SubscriptionManager.INVALID_SUBSCRIPTION_ID);
1493         mTestableLooper.processAllMessages();
1494 
1495         assertThat(mKeyguardUpdateMonitor.mSimDatas.get(TEST_SUBSCRIPTION.getSubscriptionId()))
1496                 .isNull();
1497         assertThat(mKeyguardUpdateMonitor.mSimDatas.get(
1498                 SubscriptionManager.INVALID_SUBSCRIPTION_ID)).isNull();
1499     }
1500 
1501     @Test
testIsUserUnlocked()1502     public void testIsUserUnlocked() {
1503         // mUserManager will report the user as unlocked on @Before
1504         assertThat(mKeyguardUpdateMonitor.isUserUnlocked(KeyguardUpdateMonitor.getCurrentUser()))
1505                 .isTrue();
1506         // Invalid user should not be unlocked.
1507         int randomUser = 99;
1508         assertThat(mKeyguardUpdateMonitor.isUserUnlocked(randomUser)).isFalse();
1509     }
1510 
1511     @Test
testTrustUsuallyManaged_whenTrustChanges()1512     public void testTrustUsuallyManaged_whenTrustChanges() {
1513         int user = KeyguardUpdateMonitor.getCurrentUser();
1514         when(mTrustManager.isTrustUsuallyManaged(eq(user))).thenReturn(true);
1515         mKeyguardUpdateMonitor.onTrustManagedChanged(false /* managed */, user);
1516         assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isTrue();
1517     }
1518 
1519     @Test
testTrustUsuallyManaged_resetWhenUserIsRemoved()1520     public void testTrustUsuallyManaged_resetWhenUserIsRemoved() {
1521         int user = KeyguardUpdateMonitor.getCurrentUser();
1522         when(mTrustManager.isTrustUsuallyManaged(eq(user))).thenReturn(true);
1523         mKeyguardUpdateMonitor.onTrustManagedChanged(false /* managed */, user);
1524         assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isTrue();
1525 
1526         mKeyguardUpdateMonitor.handleUserRemoved(user);
1527         assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isFalse();
1528     }
1529 
1530     @Test
testSecondaryLockscreenRequirement()1531     public void testSecondaryLockscreenRequirement() {
1532         KeyguardUpdateMonitor.setCurrentUser(UserHandle.myUserId());
1533         when(mUserTracker.getUserId()).thenReturn(UserHandle.myUserId());
1534         int user = KeyguardUpdateMonitor.getCurrentUser();
1535         String packageName = "fake.test.package";
1536         String cls = "FakeService";
1537         ServiceInfo serviceInfo = new ServiceInfo();
1538         serviceInfo.packageName = packageName;
1539         serviceInfo.name = cls;
1540         ResolveInfo resolveInfo = new ResolveInfo();
1541         resolveInfo.serviceInfo = serviceInfo;
1542         when(mPackageManager.resolveService(any(Intent.class), eq(0))).thenReturn(resolveInfo);
1543         when(mDevicePolicyManager.isSecondaryLockscreenEnabled(eq(UserHandle.of(user))))
1544                 .thenReturn(true, false);
1545         when(mDevicePolicyManager.getProfileOwnerOrDeviceOwnerSupervisionComponent(
1546                 UserHandle.of(user)))
1547                 .thenReturn(new ComponentName(packageName, cls));
1548 
1549         // Initially null.
1550         assertThat(mKeyguardUpdateMonitor.getSecondaryLockscreenRequirement(user)).isNull();
1551 
1552         // Set non-null after DPM change.
1553         setBroadcastReceiverPendingResult(mKeyguardUpdateMonitor.mBroadcastAllReceiver);
1554         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1555         mKeyguardUpdateMonitor.mBroadcastAllReceiver.onReceive(getContext(), intent);
1556         mTestableLooper.processAllMessages();
1557 
1558         Intent storedIntent = mKeyguardUpdateMonitor.getSecondaryLockscreenRequirement(user);
1559         assertThat(storedIntent.getComponent().getClassName()).isEqualTo(cls);
1560         assertThat(storedIntent.getComponent().getPackageName()).isEqualTo(packageName);
1561 
1562         // Back to null after another DPM change.
1563         mKeyguardUpdateMonitor.mBroadcastAllReceiver.onReceive(getContext(), intent);
1564         mTestableLooper.processAllMessages();
1565         assertThat(mKeyguardUpdateMonitor.getSecondaryLockscreenRequirement(user)).isNull();
1566     }
1567 
1568     @Test
testRegisterAuthControllerCallback()1569     public void testRegisterAuthControllerCallback() {
1570         assertThat(mKeyguardUpdateMonitor.isUdfpsEnrolled()).isFalse();
1571 
1572         // verify AuthController.Callback is added:
1573         ArgumentCaptor<AuthController.Callback> captor = ArgumentCaptor.forClass(
1574                 AuthController.Callback.class);
1575         verify(mAuthController).addCallback(captor.capture());
1576         AuthController.Callback callback = captor.getValue();
1577 
1578         // WHEN udfps is now enrolled
1579         when(mAuthController.isUdfpsEnrolled(anyInt())).thenReturn(true);
1580         callback.onEnrollmentsChanged(TYPE_FINGERPRINT);
1581 
1582         // THEN isUdfspEnrolled is TRUE
1583         assertThat(mKeyguardUpdateMonitor.isUdfpsEnrolled()).isTrue();
1584     }
1585 
1586 
1587     @Test
testStartUdfpsServiceBeginsOnKeyguard()1588     public void testStartUdfpsServiceBeginsOnKeyguard() {
1589         // GIVEN
1590         // - status bar state is on the keyguard
1591         // - user has authenticated since boot
1592         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1593         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1594 
1595         // THEN we should listen for udfps
1596         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1597     }
1598 
1599     @Test
listenForFingerprint_whenOccludingAppPkgOnAllowlist()1600     public void listenForFingerprint_whenOccludingAppPkgOnAllowlist()
1601             throws RemoteException {
1602         mFeatureFlags.set(FP_LISTEN_OCCLUDING_APPS, true);
1603 
1604         // GIVEN keyguard isn't visible (app occluding)
1605         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1606         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1607         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1608 
1609         // GIVEN the top activity is from a package that allows fingerprint listening over its
1610         // occluding activities
1611         setTopStandardActivity(PKG_ALLOWING_FP_LISTEN_ON_OCCLUDING_ACTIVITY);
1612         onTaskStackChanged();
1613 
1614         // THEN we SHOULD listen for non-UDFPS fingerprint
1615         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(true);
1616 
1617         // THEN we should listen for udfps (hiding mechanism to actually auth is
1618         // controlled by UdfpsKeyguardViewController)
1619         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1620     }
1621 
1622     @Test
doNotListenForFingerprint_whenOccludingAppPkgNotOnAllowlist()1623     public void doNotListenForFingerprint_whenOccludingAppPkgNotOnAllowlist()
1624             throws RemoteException {
1625         mFeatureFlags.set(FP_LISTEN_OCCLUDING_APPS, true);
1626 
1627         // GIVEN keyguard isn't visible (app occluding)
1628         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1629         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1630         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1631 
1632         // GIVEN top activity is not in the allowlist for listening to fp over occluding activities
1633         setTopStandardActivity("notInAllowList");
1634 
1635         // THEN we should not listen for non-UDFPS fingerprint
1636         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(false);
1637 
1638         // THEN we should listen for udfps (hiding mechanism to actually auth is
1639         // controlled by UdfpsKeyguardViewController)
1640         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1641     }
1642 
1643     @Test
testOccludingAppFingerprintListeningState()1644     public void testOccludingAppFingerprintListeningState() {
1645         // GIVEN keyguard isn't visible (app occluding)
1646         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1647         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1648         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1649 
1650         // THEN we shouldn't listen for fingerprints
1651         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(false);
1652 
1653         // THEN we should listen for udfps (hiding of mechanism to actually auth is
1654         // controlled by UdfpsKeyguardViewController)
1655         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1656     }
1657 
1658     @Test
testOccludingAppRequestsFingerprint()1659     public void testOccludingAppRequestsFingerprint() {
1660         // GIVEN keyguard isn't visible (app occluding)
1661         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1662         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
1663 
1664         // WHEN an occluding app requests fp
1665         mKeyguardUpdateMonitor.requestFingerprintAuthOnOccludingApp(true);
1666 
1667         // THEN we should listen for fingerprints
1668         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(true);
1669 
1670         // WHEN an occluding app stops requesting fp
1671         mKeyguardUpdateMonitor.requestFingerprintAuthOnOccludingApp(false);
1672 
1673         // THEN we shouldn't listen for fingeprints
1674         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(false);
1675     }
1676 
1677     @Test
testStartUdfpsServiceNoAuthenticationSinceLastBoot()1678     public void testStartUdfpsServiceNoAuthenticationSinceLastBoot() {
1679         // GIVEN status bar state is on the keyguard
1680         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1681 
1682         // WHEN user hasn't authenticated since last boot, cannot unlock with FP
1683         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
1684 
1685         // THEN we shouldn't listen for udfps
1686         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(false);
1687     }
1688 
1689     @Test
testStartUdfpsServiceStrongAuthRequiredAfterTimeout()1690     public void testStartUdfpsServiceStrongAuthRequiredAfterTimeout() {
1691         // GIVEN status bar state is on the keyguard
1692         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1693 
1694         // WHEN user loses smart unlock trust
1695         when(mStrongAuthTracker.getStrongAuthForUser(KeyguardUpdateMonitor.getCurrentUser()))
1696                 .thenReturn(SOME_AUTH_REQUIRED_AFTER_USER_REQUEST);
1697 
1698         // THEN we should still listen for udfps
1699         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
1700     }
1701 
1702     @Test
startsListeningForSfps_whenKeyguardIsVisible_ifRequireInteractiveToAuthEnabled()1703     public void startsListeningForSfps_whenKeyguardIsVisible_ifRequireInteractiveToAuthEnabled()
1704             throws RemoteException {
1705         // SFPS supported and enrolled
1706         when(mAuthController.isSfpsSupported()).thenReturn(true);
1707         when(mAuthController.isSfpsEnrolled(anyInt())).thenReturn(true);
1708 
1709         // WHEN require interactive to auth is disabled, and keyguard is not awake
1710         when(mInteractiveToAuthProvider.isEnabled(anyInt())).thenReturn(false);
1711 
1712         // Preconditions for sfps auth to run
1713         keyguardNotGoingAway();
1714         currentUserIsSystem();
1715         currentUserDoesNotHaveTrust();
1716         biometricsNotDisabledThroughDevicePolicyManager();
1717         biometricsEnabledForCurrentUser();
1718         userNotCurrentlySwitching();
1719 
1720         statusBarShadeIsLocked();
1721         mTestableLooper.processAllMessages();
1722 
1723         // THEN we should listen for sfps when screen off, because require screen on is disabled
1724         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isTrue();
1725 
1726         // WHEN require interactive to auth is enabled, and keyguard is not awake
1727         when(mInteractiveToAuthProvider.isEnabled(anyInt())).thenReturn(true);
1728 
1729         // THEN we shouldn't listen for sfps when screen off, because require screen on is enabled
1730         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isFalse();
1731 
1732         // Device now awake & keyguard is now interactive
1733         deviceNotGoingToSleep();
1734         deviceIsInteractive();
1735         keyguardIsVisible();
1736 
1737         // THEN we should listen for sfps when screen on, and require screen on is enabled
1738         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isTrue();
1739     }
1740 
1741     @Test
notListeningForSfps_whenGoingToSleep_ifRequireInteractiveToAuthEnabled()1742     public void notListeningForSfps_whenGoingToSleep_ifRequireInteractiveToAuthEnabled()
1743             throws RemoteException {
1744         // GIVEN SFPS supported and enrolled
1745         when(mAuthController.isSfpsSupported()).thenReturn(true);
1746         when(mAuthController.isSfpsEnrolled(anyInt())).thenReturn(true);
1747 
1748         // GIVEN Preconditions for sfps auth to run
1749         keyguardNotGoingAway();
1750         currentUserIsSystem();
1751         currentUserDoesNotHaveTrust();
1752         biometricsNotDisabledThroughDevicePolicyManager();
1753         biometricsEnabledForCurrentUser();
1754         userNotCurrentlySwitching();
1755         statusBarShadeIsLocked();
1756 
1757         // WHEN require interactive to auth is enabled & keyguard is going to sleep
1758         when(mInteractiveToAuthProvider.isEnabled(anyInt())).thenReturn(true);
1759         deviceGoingToSleep();
1760 
1761         mTestableLooper.processAllMessages();
1762 
1763         // THEN we should NOT listen for sfps because device is going to sleep
1764         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isFalse();
1765     }
1766 
1767     @Test
listeningForSfps_whenGoingToSleep_ifRequireInteractiveToAuthDisabled()1768     public void listeningForSfps_whenGoingToSleep_ifRequireInteractiveToAuthDisabled()
1769             throws RemoteException {
1770         // GIVEN SFPS supported and enrolled
1771         final ArrayList<FingerprintSensorPropertiesInternal> props = new ArrayList<>();
1772         props.add(createFingerprintSensorPropertiesInternal(TYPE_POWER_BUTTON,
1773                 /* isClass3 */ true));
1774         when(mAuthController.getSfpsProps()).thenReturn(props);
1775         when(mAuthController.isSfpsEnrolled(anyInt())).thenReturn(true);
1776 
1777         // GIVEN Preconditions for sfps auth to run
1778         keyguardNotGoingAway();
1779         currentUserIsSystem();
1780         currentUserDoesNotHaveTrust();
1781         biometricsNotDisabledThroughDevicePolicyManager();
1782         biometricsEnabledForCurrentUser();
1783         userNotCurrentlySwitching();
1784         statusBarShadeIsLocked();
1785 
1786         // WHEN require interactive to auth is disabled & keyguard is going to sleep
1787         when(mInteractiveToAuthProvider.isEnabled(anyInt())).thenReturn(false);
1788         deviceGoingToSleep();
1789 
1790         mTestableLooper.processAllMessages();
1791 
1792         // THEN we should listen for sfps because screen on to auth is  disabled
1793         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isTrue();
1794     }
1795 
1796     @Test
testShouldNotListenForUdfps_whenTrustEnabled()1797     public void testShouldNotListenForUdfps_whenTrustEnabled() {
1798         // GIVEN a "we should listen for udfps" state
1799         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1800         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1801 
1802         // WHEN trust is enabled (ie: via smartlock)
1803         mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, true /* newlyUnlocked */,
1804                 KeyguardUpdateMonitor.getCurrentUser(), 0 /* flags */, new ArrayList<>());
1805 
1806         // THEN we shouldn't listen for udfps
1807         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(false);
1808     }
1809 
1810     @Test
testShouldNotListenForUdfps_whenFaceAuthenticated()1811     public void testShouldNotListenForUdfps_whenFaceAuthenticated() {
1812         // GIVEN a "we should listen for udfps" state
1813         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1814         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1815 
1816         // WHEN face authenticated
1817         mKeyguardUpdateMonitor.onFaceAuthenticated(
1818                 KeyguardUpdateMonitor.getCurrentUser(), false);
1819 
1820         // THEN we shouldn't listen for udfps
1821         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(false);
1822     }
1823 
1824     @Test
testShouldNotListenForUdfps_whenInLockDown()1825     public void testShouldNotListenForUdfps_whenInLockDown() {
1826         // GIVEN a "we should listen for udfps" state
1827         setKeyguardBouncerVisibility(false /* isVisible */);
1828         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1829         when(mStrongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
1830 
1831         // WHEN device in lock down
1832         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
1833 
1834         // THEN we shouldn't listen for udfps
1835         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(false);
1836     }
1837 
1838     @Test
testShouldNotUpdateBiometricListeningStateOnStatusBarStateChange()1839     public void testShouldNotUpdateBiometricListeningStateOnStatusBarStateChange() {
1840         // GIVEN state for face auth should run aside from StatusBarState
1841         biometricsNotDisabledThroughDevicePolicyManager();
1842         mStatusBarStateListener.onStateChanged(StatusBarState.SHADE_LOCKED);
1843         setKeyguardBouncerVisibility(false /* isVisible */);
1844         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
1845         lockscreenBypassIsAllowed();
1846         keyguardIsVisible();
1847 
1848         // WHEN status bar state reports a change to the keyguard that would normally indicate to
1849         // start running face auth
1850         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
1851         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isEqualTo(true);
1852 
1853         // THEN face unlock is not running b/c status bar state changes don't cause biometric
1854         // listening state to update
1855         assertThat(mKeyguardUpdateMonitor.isFaceDetectionRunning()).isEqualTo(false);
1856 
1857         // WHEN biometric listening state is updated when showing state changes from false => true
1858         mKeyguardUpdateMonitor.setKeyguardShowing(false, false);
1859         mKeyguardUpdateMonitor.setKeyguardShowing(true, false);
1860 
1861         // THEN face unlock is running
1862         assertThat(mKeyguardUpdateMonitor.isFaceDetectionRunning()).isEqualTo(true);
1863     }
1864 
1865     @Test
testRequestFaceAuthFromOccludingApp_whenInvoked_startsFaceAuth()1866     public void testRequestFaceAuthFromOccludingApp_whenInvoked_startsFaceAuth() {
1867         mKeyguardUpdateMonitor.requestFaceAuthOnOccludingApp(true);
1868 
1869         assertThat(mKeyguardUpdateMonitor.isFaceDetectionRunning()).isTrue();
1870     }
1871 
1872     @Test
testRequestFaceAuthFromOccludingApp_whenInvoked_stopsFaceAuth()1873     public void testRequestFaceAuthFromOccludingApp_whenInvoked_stopsFaceAuth() {
1874         mKeyguardUpdateMonitor.requestFaceAuthOnOccludingApp(true);
1875 
1876         assertThat(mKeyguardUpdateMonitor.isFaceDetectionRunning()).isTrue();
1877 
1878         mKeyguardUpdateMonitor.requestFaceAuthOnOccludingApp(false);
1879 
1880         assertThat(mKeyguardUpdateMonitor.isFaceDetectionRunning()).isFalse();
1881     }
1882 
1883     @Test
testRequireUnlockForNfc_Broadcast()1884     public void testRequireUnlockForNfc_Broadcast() {
1885         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
1886         mKeyguardUpdateMonitor.registerCallback(callback);
1887         Intent intent = new Intent(NfcAdapter.ACTION_REQUIRE_UNLOCK_FOR_NFC);
1888         mKeyguardUpdateMonitor.mBroadcastAllReceiver.onReceive(getContext(), intent);
1889         mTestableLooper.processAllMessages();
1890 
1891         verify(callback, atLeastOnce()).onRequireUnlockForNfc();
1892     }
1893 
1894     @Test
testFaceDoesNotAuth_afterPinAttempt()1895     public void testFaceDoesNotAuth_afterPinAttempt() {
1896         mTestableLooper.processAllMessages();
1897         mKeyguardUpdateMonitor.setCredentialAttempted();
1898         verifyFaceAuthenticateNeverCalled();
1899     }
1900 
1901     @Test
testShowTrustGrantedMessage_onTrustGranted()1902     public void testShowTrustGrantedMessage_onTrustGranted() {
1903         // WHEN trust is enabled (ie: via some trust agent) with a trustGranted string
1904         mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, true /* newlyUnlocked */,
1905                 KeyguardUpdateMonitor.getCurrentUser(), 0 /* flags */,
1906                 Arrays.asList("Unlocked by wearable"));
1907 
1908         // THEN the showTrustGrantedMessage should be called with the first message
1909         verify(mTestCallback).onTrustGrantedForCurrentUser(
1910                 anyBoolean() /* dismissKeyguard */,
1911                 eq(true) /* newlyUnlocked */,
1912                 eq(new TrustGrantFlags(0)),
1913                 eq("Unlocked by wearable"));
1914     }
1915 
1916     @Test
testShouldListenForFace_whenFaceManagerNotAvailable_returnsFalse()1917     public void testShouldListenForFace_whenFaceManagerNotAvailable_returnsFalse() {
1918         cleanupKeyguardUpdateMonitor();
1919         mFaceManager = null;
1920 
1921         mKeyguardUpdateMonitor = new TestableKeyguardUpdateMonitor(mContext);
1922 
1923         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
1924     }
1925 
1926     @Test
testShouldListenForFace_whenFpIsLockedOut_returnsFalse()1927     public void testShouldListenForFace_whenFpIsLockedOut_returnsFalse() throws RemoteException {
1928         // Face auth should run when the following is true.
1929         keyguardNotGoingAway();
1930         occludingAppRequestsFaceAuth();
1931         currentUserIsSystem();
1932         primaryAuthNotRequiredByStrongAuthTracker();
1933         biometricsEnabledForCurrentUser();
1934         currentUserDoesNotHaveTrust();
1935         biometricsNotDisabledThroughDevicePolicyManager();
1936         userNotCurrentlySwitching();
1937         mTestableLooper.processAllMessages();
1938         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
1939 
1940         // Fingerprint is locked out.
1941         fingerprintErrorTemporaryLockOut();
1942 
1943         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
1944     }
1945 
1946     @Test
testShouldListenForFace_whenFaceIsAlreadyAuthenticated_returnsFalse()1947     public void testShouldListenForFace_whenFaceIsAlreadyAuthenticated_returnsFalse()
1948             throws RemoteException {
1949         // Face auth should run when the following is true.
1950         bouncerFullyVisibleAndNotGoingToSleep();
1951         keyguardNotGoingAway();
1952         currentUserIsSystem();
1953         primaryAuthNotRequiredByStrongAuthTracker();
1954         biometricsEnabledForCurrentUser();
1955         currentUserDoesNotHaveTrust();
1956         biometricsNotDisabledThroughDevicePolicyManager();
1957         userNotCurrentlySwitching();
1958 
1959         mTestableLooper.processAllMessages();
1960 
1961         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
1962 
1963         triggerSuccessfulFaceAuth();
1964         mTestableLooper.processAllMessages();
1965 
1966         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
1967     }
1968 
1969     @Test
testShouldListenForFace_whenFpIsAlreadyAuthenticated_returnsFalse()1970     public void testShouldListenForFace_whenFpIsAlreadyAuthenticated_returnsFalse()
1971             throws RemoteException {
1972         // Face auth should run when the following is true.
1973         bouncerFullyVisibleAndNotGoingToSleep();
1974         keyguardNotGoingAway();
1975         currentUserIsSystem();
1976         primaryAuthNotRequiredByStrongAuthTracker();
1977         biometricsEnabledForCurrentUser();
1978         currentUserDoesNotHaveTrust();
1979         biometricsNotDisabledThroughDevicePolicyManager();
1980         userNotCurrentlySwitching();
1981 
1982         mTestableLooper.processAllMessages();
1983 
1984         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
1985 
1986         successfulFingerprintAuth();
1987         mTestableLooper.processAllMessages();
1988 
1989         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
1990     }
1991 
1992     @Test
testShouldListenForFace_whenUserIsNotPrimary_returnsFalse()1993     public void testShouldListenForFace_whenUserIsNotPrimary_returnsFalse() throws RemoteException {
1994         cleanupKeyguardUpdateMonitor();
1995         // This disables face auth
1996         when(mUserManager.isSystemUser()).thenReturn(false);
1997         mKeyguardUpdateMonitor =
1998                 new TestableKeyguardUpdateMonitor(mContext);
1999 
2000         // Face auth should run when the following is true.
2001         keyguardNotGoingAway();
2002         bouncerFullyVisibleAndNotGoingToSleep();
2003         primaryAuthNotRequiredByStrongAuthTracker();
2004         biometricsEnabledForCurrentUser();
2005         currentUserDoesNotHaveTrust();
2006         biometricsNotDisabledThroughDevicePolicyManager();
2007         userNotCurrentlySwitching();
2008         mTestableLooper.processAllMessages();
2009 
2010 
2011         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2012     }
2013 
2014     @Test
testShouldListenForFace_whenStrongAuthDoesNotAllowScanning_returnsFalse()2015     public void testShouldListenForFace_whenStrongAuthDoesNotAllowScanning_returnsFalse()
2016             throws RemoteException {
2017         // Face auth should run when the following is true.
2018         keyguardNotGoingAway();
2019         bouncerFullyVisibleAndNotGoingToSleep();
2020         currentUserIsSystem();
2021         biometricsEnabledForCurrentUser();
2022         currentUserDoesNotHaveTrust();
2023         biometricsNotDisabledThroughDevicePolicyManager();
2024         userNotCurrentlySwitching();
2025 
2026         // This disables face auth
2027         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
2028         mTestableLooper.processAllMessages();
2029 
2030         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2031     }
2032 
2033     @Test
testShouldListenForFace_whenBiometricsDisabledForUser_returnsFalse()2034     public void testShouldListenForFace_whenBiometricsDisabledForUser_returnsFalse()
2035             throws RemoteException {
2036         keyguardNotGoingAway();
2037         bouncerFullyVisibleAndNotGoingToSleep();
2038         currentUserIsSystem();
2039         currentUserDoesNotHaveTrust();
2040         biometricsNotDisabledThroughDevicePolicyManager();
2041         biometricsEnabledForCurrentUser();
2042         userNotCurrentlySwitching();
2043         mTestableLooper.processAllMessages();
2044 
2045         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2046 
2047         // This disables face auth
2048         biometricsDisabledForCurrentUser();
2049         mTestableLooper.processAllMessages();
2050 
2051         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2052     }
2053 
2054     @Test
testShouldListenForFace_whenUserCurrentlySwitching_returnsFalse()2055     public void testShouldListenForFace_whenUserCurrentlySwitching_returnsFalse()
2056             throws RemoteException {
2057         // Face auth should run when the following is true.
2058         keyguardNotGoingAway();
2059         bouncerFullyVisibleAndNotGoingToSleep();
2060         currentUserIsSystem();
2061         currentUserDoesNotHaveTrust();
2062         biometricsNotDisabledThroughDevicePolicyManager();
2063         biometricsEnabledForCurrentUser();
2064         userNotCurrentlySwitching();
2065         mTestableLooper.processAllMessages();
2066 
2067         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2068 
2069         userCurrentlySwitching();
2070         mTestableLooper.processAllMessages();
2071 
2072         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2073     }
2074 
2075     @Test
testShouldListenForFace_whenSecureCameraLaunched_returnsFalse()2076     public void testShouldListenForFace_whenSecureCameraLaunched_returnsFalse()
2077             throws RemoteException {
2078         keyguardNotGoingAway();
2079         bouncerFullyVisibleAndNotGoingToSleep();
2080         currentUserIsSystem();
2081         currentUserDoesNotHaveTrust();
2082         biometricsNotDisabledThroughDevicePolicyManager();
2083         biometricsEnabledForCurrentUser();
2084         userNotCurrentlySwitching();
2085         mTestableLooper.processAllMessages();
2086 
2087         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2088 
2089         secureCameraLaunched();
2090         mTestableLooper.processAllMessages();
2091 
2092         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2093     }
2094 
2095     @Test
shouldListenForFace_secureCameraLaunchedButAlternateBouncerIsLaunched_returnsTrue()2096     public void shouldListenForFace_secureCameraLaunchedButAlternateBouncerIsLaunched_returnsTrue()
2097             throws RemoteException {
2098         // Face auth should run when the following is true.
2099         keyguardNotGoingAway();
2100         bouncerFullyVisibleAndNotGoingToSleep();
2101         currentUserIsSystem();
2102         currentUserDoesNotHaveTrust();
2103         biometricsNotDisabledThroughDevicePolicyManager();
2104         biometricsEnabledForCurrentUser();
2105         userNotCurrentlySwitching();
2106         mTestableLooper.processAllMessages();
2107 
2108         secureCameraLaunched();
2109 
2110         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2111 
2112         alternateBouncerVisible();
2113         mTestableLooper.processAllMessages();
2114 
2115         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2116     }
2117 
2118     @Test
testShouldListenForFace_whenBouncerShowingAndDeviceIsAwake_returnsTrue()2119     public void testShouldListenForFace_whenBouncerShowingAndDeviceIsAwake_returnsTrue()
2120             throws RemoteException {
2121         // Face auth should run when the following is true.
2122         keyguardNotGoingAway();
2123         currentUserIsSystem();
2124         currentUserDoesNotHaveTrust();
2125         biometricsNotDisabledThroughDevicePolicyManager();
2126         biometricsEnabledForCurrentUser();
2127         userNotCurrentlySwitching();
2128         mTestableLooper.processAllMessages();
2129 
2130         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2131 
2132         bouncerFullyVisibleAndNotGoingToSleep();
2133         mTestableLooper.processAllMessages();
2134 
2135         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2136     }
2137 
2138     @Test
testShouldListenForFace_whenAuthInterruptIsActive_returnsTrue()2139     public void testShouldListenForFace_whenAuthInterruptIsActive_returnsTrue()
2140             throws RemoteException {
2141         // Face auth should run when the following is true.
2142         keyguardNotGoingAway();
2143         currentUserIsSystem();
2144         currentUserDoesNotHaveTrust();
2145         biometricsNotDisabledThroughDevicePolicyManager();
2146         biometricsEnabledForCurrentUser();
2147         userNotCurrentlySwitching();
2148         mTestableLooper.processAllMessages();
2149 
2150         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2151 
2152         triggerAuthInterrupt();
2153         mTestableLooper.processAllMessages();
2154 
2155         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2156     }
2157 
2158     @Test
testShouldListenForFace_whenKeyguardIsAwake_returnsTrue()2159     public void testShouldListenForFace_whenKeyguardIsAwake_returnsTrue() throws RemoteException {
2160         // Preconditions for face auth to run
2161         keyguardNotGoingAway();
2162         currentUserIsSystem();
2163         currentUserDoesNotHaveTrust();
2164         biometricsNotDisabledThroughDevicePolicyManager();
2165         biometricsEnabledForCurrentUser();
2166         userNotCurrentlySwitching();
2167 
2168         statusBarShadeIsLocked();
2169         mTestableLooper.processAllMessages();
2170 
2171         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2172 
2173         deviceNotGoingToSleep();
2174         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2175         deviceIsInteractive();
2176         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2177         keyguardIsVisible();
2178         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2179         statusBarShadeIsNotLocked();
2180         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2181     }
2182 
2183     @Test
testShouldListenForFace_whenUdfpsFingerDown_returnsTrue()2184     public void testShouldListenForFace_whenUdfpsFingerDown_returnsTrue() throws RemoteException {
2185         // Preconditions for face auth to run
2186         keyguardNotGoingAway();
2187         currentUserIsSystem();
2188         currentUserDoesNotHaveTrust();
2189         biometricsNotDisabledThroughDevicePolicyManager();
2190         biometricsEnabledForCurrentUser();
2191         userNotCurrentlySwitching();
2192         when(mAuthController.isUdfpsFingerDown()).thenReturn(false);
2193         mTestableLooper.processAllMessages();
2194 
2195         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2196 
2197         when(mAuthController.isUdfpsFingerDown()).thenReturn(true);
2198         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2199     }
2200 
2201     @Test
testShouldListenForFace_whenAlternateBouncerIsShowing_returnsTrue()2202     public void testShouldListenForFace_whenAlternateBouncerIsShowing_returnsTrue()
2203             throws RemoteException {
2204         // Preconditions for face auth to run
2205         keyguardNotGoingAway();
2206         currentUserIsSystem();
2207         currentUserDoesNotHaveTrust();
2208         biometricsNotDisabledThroughDevicePolicyManager();
2209         biometricsEnabledForCurrentUser();
2210         userNotCurrentlySwitching();
2211         mTestableLooper.processAllMessages();
2212         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2213 
2214         mKeyguardUpdateMonitor.setAlternateBouncerShowing(true);
2215 
2216         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2217     }
2218 
2219     @Test
testShouldListenForFace_alternateBouncerShowingButDeviceGoingToSleep_returnsFalse()2220     public void testShouldListenForFace_alternateBouncerShowingButDeviceGoingToSleep_returnsFalse()
2221             throws RemoteException {
2222         // Preconditions for face auth to run
2223         keyguardNotGoingAway();
2224         currentUserIsSystem();
2225         currentUserDoesNotHaveTrust();
2226         biometricsNotDisabledThroughDevicePolicyManager();
2227         biometricsEnabledForCurrentUser();
2228         userNotCurrentlySwitching();
2229         deviceNotGoingToSleep();
2230         alternateBouncerVisible();
2231         mTestableLooper.processAllMessages();
2232         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2233 
2234         deviceGoingToSleep();
2235         mTestableLooper.processAllMessages();
2236 
2237         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2238     }
2239 
alternateBouncerVisible()2240     private void alternateBouncerVisible() {
2241         mKeyguardUpdateMonitor.setAlternateBouncerShowing(true);
2242     }
2243 
2244     @Test
testShouldListenForFace_whenFaceIsLockedOut_returnsTrue()2245     public void testShouldListenForFace_whenFaceIsLockedOut_returnsTrue()
2246             throws RemoteException {
2247         // Preconditions for face auth to run
2248         keyguardNotGoingAway();
2249         currentUserIsSystem();
2250         currentUserDoesNotHaveTrust();
2251         biometricsNotDisabledThroughDevicePolicyManager();
2252         biometricsEnabledForCurrentUser();
2253         userNotCurrentlySwitching();
2254         mKeyguardUpdateMonitor.setAlternateBouncerShowing(true);
2255         mTestableLooper.processAllMessages();
2256         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2257 
2258         // Face is locked out.
2259         faceAuthLockOut();
2260         mTestableLooper.processAllMessages();
2261 
2262         // This is needed beccause we want to show face locked out error message whenever face auth
2263         // is supposed to run.
2264         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2265     }
2266 
2267     @Test
testFingerprintCanAuth_whenCancellationNotReceivedAndAuthFailed()2268     public void testFingerprintCanAuth_whenCancellationNotReceivedAndAuthFailed() {
2269         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
2270         mTestableLooper.processAllMessages();
2271         keyguardIsVisible();
2272 
2273         verifyFaceAuthenticateCall();
2274         verifyFingerprintAuthenticateCall();
2275 
2276         mKeyguardUpdateMonitor.onFaceAuthenticated(0, false);
2277         // Make sure keyguard is going away after face auth attempt, and that it calls
2278         // updateBiometricStateListeningState.
2279         mKeyguardUpdateMonitor.setKeyguardShowing(false, false);
2280         mTestableLooper.processAllMessages();
2281 
2282         verify(mHandler).postDelayed(mKeyguardUpdateMonitor.mFpCancelNotReceived,
2283                 DEFAULT_CANCEL_SIGNAL_TIMEOUT);
2284 
2285         mKeyguardUpdateMonitor.onFingerprintAuthenticated(0, true);
2286         mTestableLooper.processAllMessages();
2287 
2288         verify(mHandler, times(1)).removeCallbacks(mKeyguardUpdateMonitor.mFpCancelNotReceived);
2289         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
2290         mTestableLooper.processAllMessages();
2291         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isEqualTo(true);
2292         assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(true)).isEqualTo(true);
2293     }
2294 
2295     @Test
testDreamingStopped_faceDoesNotRun()2296     public void testDreamingStopped_faceDoesNotRun() {
2297         mKeyguardUpdateMonitor.dispatchDreamingStopped();
2298         mTestableLooper.processAllMessages();
2299 
2300         verifyFaceAuthenticateNeverCalled();
2301     }
2302 
2303     @Test
testFaceWakeupTrigger_runFaceAuth_onlyOnConfiguredTriggers()2304     public void testFaceWakeupTrigger_runFaceAuth_onlyOnConfiguredTriggers() {
2305         // keyguard is visible
2306         keyguardIsVisible();
2307 
2308         // WHEN device wakes up from an application
2309         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_APPLICATION);
2310         mTestableLooper.processAllMessages();
2311 
2312         // THEN face auth isn't triggered
2313         verifyFaceAuthenticateNeverCalled();
2314 
2315         // WHEN device wakes up from the power button
2316         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
2317         mTestableLooper.processAllMessages();
2318 
2319         // THEN face auth is triggered
2320         verifyFaceAuthenticateCall();
2321     }
2322 
2323     @Test
testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_deviceInteractive()2324     public void testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_deviceInteractive() {
2325         // GIVEN device is interactive
2326         deviceIsInteractive();
2327 
2328         // GIVEN callback is registered
2329         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2330         mKeyguardUpdateMonitor.registerCallback(callback);
2331 
2332         // WHEN onTrustChanged with TRUST_DISMISS_KEYGUARD flag
2333         mKeyguardUpdateMonitor.onTrustChanged(
2334                 true /* enabled */,
2335                 true /* newlyUnlocked */,
2336                 getCurrentUser() /* userId */,
2337                 TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD /* flags */,
2338                 null /* trustGrantedMessages */);
2339 
2340         // THEN onTrustGrantedForCurrentUser callback called
2341         verify(callback).onTrustGrantedForCurrentUser(
2342                 eq(true) /* dismissKeyguard */,
2343                 eq(true) /* newlyUnlocked */,
2344                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD)),
2345                 eq(null) /* message */
2346         );
2347     }
2348 
2349     @Test
testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_doesNotDismiss()2350     public void testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_doesNotDismiss() {
2351         // GIVEN device is NOT interactive
2352 
2353         // GIVEN callback is registered
2354         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2355         mKeyguardUpdateMonitor.registerCallback(callback);
2356 
2357         // WHEN onTrustChanged with TRUST_DISMISS_KEYGUARD flag
2358         mKeyguardUpdateMonitor.onTrustChanged(
2359                 true /* enabled */,
2360                 true /* newlyUnlocked */,
2361                 getCurrentUser() /* userId */,
2362                 TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD /* flags */,
2363                 null /* trustGrantedMessages */);
2364 
2365         // THEN onTrustGrantedForCurrentUser callback called
2366         verify(callback).onTrustGrantedForCurrentUser(
2367                 eq(false) /* dismissKeyguard */,
2368                 eq(true) /* newlyUnlocked */,
2369                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD)),
2370                 eq(null) /* message */
2371         );
2372     }
2373 
2374     @Test
testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_temporaryAndRenewable()2375     public void testOnTrustGrantedForCurrentUser_dismissKeyguardRequested_temporaryAndRenewable() {
2376         // GIVEN device is interactive
2377         deviceIsInteractive();
2378 
2379         // GIVEN callback is registered
2380         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2381         mKeyguardUpdateMonitor.registerCallback(callback);
2382 
2383         // WHEN onTrustChanged for a different user
2384         mKeyguardUpdateMonitor.onTrustChanged(
2385                 true /* enabled */,
2386                 true /* newlyUnlocked */,
2387                 546 /* userId, not the current userId */,
2388                 0 /* flags */,
2389                 null /* trustGrantedMessages */);
2390 
2391         // THEN onTrustGrantedForCurrentUser callback called
2392         verify(callback, never()).onTrustGrantedForCurrentUser(
2393                 anyBoolean() /* dismissKeyguard */,
2394                 eq(true) /* newlyUnlocked */,
2395                 anyObject() /* flags */,
2396                 anyString() /* message */
2397         );
2398     }
2399 
2400     @Test
testOnTrustGranted_differentUser_noCallback()2401     public void testOnTrustGranted_differentUser_noCallback() {
2402         // GIVEN device is interactive
2403 
2404         // GIVEN callback is registered
2405         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2406         mKeyguardUpdateMonitor.registerCallback(callback);
2407 
2408         // WHEN onTrustChanged with TRUST_DISMISS_KEYGUARD AND TRUST_TEMPORARY_AND_RENEWABLE
2409         // flags (temporary & rewable is active unlock)
2410         mKeyguardUpdateMonitor.onTrustChanged(
2411                 true /* enabled */,
2412                 true /* newlyUnlocked */,
2413                 getCurrentUser() /* userId */,
2414                 TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD
2415                         | TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE /* flags */,
2416                 null /* trustGrantedMessages */);
2417 
2418         // THEN onTrustGrantedForCurrentUser callback called
2419         verify(callback).onTrustGrantedForCurrentUser(
2420                 eq(true) /* dismissKeyguard */,
2421                 eq(true) /* newlyUnlocked */,
2422                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD
2423                         | TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE)),
2424                 eq(null) /* message */
2425         );
2426     }
2427 
2428     @Test
testOnTrustGrantedForCurrentUser_bouncerShowing_initiatedByUser()2429     public void testOnTrustGrantedForCurrentUser_bouncerShowing_initiatedByUser() {
2430         // GIVEN device is interactive & bouncer is showing
2431         deviceIsInteractive();
2432         bouncerFullyVisible();
2433 
2434         // GIVEN callback is registered
2435         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2436         mKeyguardUpdateMonitor.registerCallback(callback);
2437 
2438         // WHEN onTrustChanged with INITIATED_BY_USER flag
2439         mKeyguardUpdateMonitor.onTrustChanged(
2440                 true /* enabled */,
2441                 true /* newlyUnlocked */,
2442                 getCurrentUser() /* userId, not the current userId */,
2443                 TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER /* flags */,
2444                 null /* trustGrantedMessages */);
2445 
2446         // THEN onTrustGrantedForCurrentUser callback called
2447         verify(callback, never()).onTrustGrantedForCurrentUser(
2448                 eq(true) /* dismissKeyguard */,
2449                 eq(true) /* newlyUnlocked */,
2450                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER)),
2451                 anyString() /* message */
2452         );
2453     }
2454 
2455     @Test
testOnTrustGrantedForCurrentUser_bouncerShowing_temporaryRenewable()2456     public void testOnTrustGrantedForCurrentUser_bouncerShowing_temporaryRenewable() {
2457         // GIVEN device is NOT interactive & bouncer is showing
2458         bouncerFullyVisible();
2459 
2460         // GIVEN callback is registered
2461         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2462         mKeyguardUpdateMonitor.registerCallback(callback);
2463 
2464         // WHEN onTrustChanged with INITIATED_BY_USER flag
2465         mKeyguardUpdateMonitor.onTrustChanged(
2466                 true /* enabled */,
2467                 true /* newlyUnlocked */,
2468                 getCurrentUser() /* userId, not the current userId */,
2469                 TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER
2470                         | TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE /* flags */,
2471                 null /* trustGrantedMessages */);
2472 
2473         // THEN onTrustGrantedForCurrentUser callback called
2474         verify(callback, never()).onTrustGrantedForCurrentUser(
2475                 eq(true) /* dismissKeyguard */,
2476                 eq(true) /* newlyUnlocked */,
2477                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER
2478                         | TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE)),
2479                 anyString() /* message */
2480         );
2481     }
2482 
2483     @Test
testStrongAuthChange_lockDown_stopsFpAndFaceListeningState()2484     public void testStrongAuthChange_lockDown_stopsFpAndFaceListeningState() {
2485         // GIVEN device is listening for face and fingerprint
2486         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
2487         mTestableLooper.processAllMessages();
2488         keyguardIsVisible();
2489 
2490         verifyFaceAuthenticateCall();
2491         verifyFingerprintAuthenticateCall();
2492 
2493         final CancellationSignal faceCancel = spy(mKeyguardUpdateMonitor.mFaceCancelSignal);
2494         final CancellationSignal fpCancel = spy(mKeyguardUpdateMonitor.mFingerprintCancelSignal);
2495         mKeyguardUpdateMonitor.mFaceCancelSignal = faceCancel;
2496         mKeyguardUpdateMonitor.mFingerprintCancelSignal = fpCancel;
2497         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2498         mKeyguardUpdateMonitor.registerCallback(callback);
2499 
2500         // WHEN strong auth changes and device is in user lockdown
2501         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
2502         userDeviceLockDown();
2503         mKeyguardUpdateMonitor.notifyStrongAuthAllowedChanged(getCurrentUser());
2504         mTestableLooper.processAllMessages();
2505 
2506         // THEN face and fingerprint listening are cancelled
2507         verify(faceCancel).cancel();
2508         verify(callback).onBiometricRunningStateChanged(
2509                 eq(false), eq(BiometricSourceType.FACE));
2510         verify(fpCancel).cancel();
2511         verify(callback).onBiometricRunningStateChanged(
2512                 eq(false), eq(BiometricSourceType.FINGERPRINT));
2513     }
2514 
2515     @Test
testNonStrongBiometricAllowedChanged_stopsFaceListeningState()2516     public void testNonStrongBiometricAllowedChanged_stopsFaceListeningState() {
2517         // GIVEN device is listening for face and fingerprint
2518         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
2519         mTestableLooper.processAllMessages();
2520         keyguardIsVisible();
2521 
2522         verifyFaceAuthenticateCall();
2523 
2524         final CancellationSignal faceCancel = spy(mKeyguardUpdateMonitor.mFaceCancelSignal);
2525         mKeyguardUpdateMonitor.mFaceCancelSignal = faceCancel;
2526         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2527         mKeyguardUpdateMonitor.registerCallback(callback);
2528 
2529         // WHEN non-strong biometric allowed changes
2530         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
2531         mKeyguardUpdateMonitor.notifyNonStrongBiometricAllowedChanged(getCurrentUser());
2532         mTestableLooper.processAllMessages();
2533 
2534         // THEN face and fingerprint listening are cancelled
2535         verify(faceCancel).cancel();
2536         verify(callback).onBiometricRunningStateChanged(
2537                 eq(false), eq(BiometricSourceType.FACE));
2538     }
2539 
2540     @Test
testPostureChangeToUnsupported_stopsFaceListeningState()2541     public void testPostureChangeToUnsupported_stopsFaceListeningState() {
2542         // GIVEN device is listening for face
2543         mKeyguardUpdateMonitor.mConfigFaceAuthSupportedPosture = DEVICE_POSTURE_CLOSED;
2544         deviceInPostureStateClosed();
2545         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
2546         mTestableLooper.processAllMessages();
2547         keyguardIsVisible();
2548 
2549         verifyFaceAuthenticateCall();
2550 
2551         final CancellationSignal faceCancel = spy(mKeyguardUpdateMonitor.mFaceCancelSignal);
2552         mKeyguardUpdateMonitor.mFaceCancelSignal = faceCancel;
2553         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2554         mKeyguardUpdateMonitor.registerCallback(callback);
2555 
2556         // WHEN device is opened
2557         deviceInPostureStateOpened();
2558         mTestableLooper.processAllMessages();
2559 
2560         // THEN face listening is stopped.
2561         verify(faceCancel).cancel();
2562         verify(callback).onBiometricRunningStateChanged(
2563                 eq(false), eq(BiometricSourceType.FACE));
2564     }
2565 
2566     @Test
testShouldListenForFace_withLockedDown_returnsFalse()2567     public void testShouldListenForFace_withLockedDown_returnsFalse()
2568             throws RemoteException {
2569         keyguardNotGoingAway();
2570         bouncerFullyVisibleAndNotGoingToSleep();
2571         currentUserIsSystem();
2572         currentUserDoesNotHaveTrust();
2573         biometricsNotDisabledThroughDevicePolicyManager();
2574         biometricsEnabledForCurrentUser();
2575         userNotCurrentlySwitching();
2576         supportsFaceDetection();
2577         mTestableLooper.processAllMessages();
2578 
2579         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2580 
2581         userDeviceLockDown();
2582 
2583         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2584     }
2585 
2586     @Test
assistantVisible_requestActiveUnlock()2587     public void assistantVisible_requestActiveUnlock() {
2588         // GIVEN active unlock requests from the assistant are allowed
2589         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2590                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.ASSISTANT)).thenReturn(true);
2591 
2592         // GIVEN should trigger active unlock
2593         keyguardIsVisible();
2594         keyguardNotGoingAway();
2595         statusBarShadeIsNotLocked();
2596         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2597 
2598         // WHEN the assistant is visible
2599         mKeyguardUpdateMonitor.setAssistantVisible(true);
2600 
2601         // THEN request unlock with keyguard dismissal
2602         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2603                 eq(true));
2604     }
2605 
2606     @Test
fingerprintFailure_requestActiveUnlock_dismissKeyguard()2607     public void fingerprintFailure_requestActiveUnlock_dismissKeyguard()
2608             throws RemoteException {
2609         // GIVEN shouldTriggerActiveUnlock
2610         bouncerFullyVisible();
2611         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2612 
2613         // GIVEN active unlock triggers on biometric failures
2614         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2615                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL))
2616                 .thenReturn(true);
2617 
2618         // WHEN fingerprint fails
2619         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback.onAuthenticationFailed();
2620 
2621         // ALWAYS request unlock with a keyguard dismissal
2622         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2623                 eq(true));
2624     }
2625 
2626     @Test
faceNonBypassFailure_requestActiveUnlock_doesNotDismissKeyguard()2627     public void faceNonBypassFailure_requestActiveUnlock_doesNotDismissKeyguard()
2628             throws RemoteException {
2629         // GIVEN shouldTriggerActiveUnlock
2630         when(mAuthController.isUdfpsFingerDown()).thenReturn(false);
2631         keyguardIsVisible();
2632         keyguardNotGoingAway();
2633         statusBarShadeIsNotLocked();
2634         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2635 
2636         // GIVEN active unlock triggers on biometric failures
2637         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2638                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL))
2639                 .thenReturn(true);
2640 
2641         // WHEN face fails & bypass is not allowed
2642         lockscreenBypassIsNotAllowed();
2643         mKeyguardUpdateMonitor.mFaceAuthenticationCallback.onAuthenticationFailed();
2644 
2645         // THEN request unlock with NO keyguard dismissal
2646         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2647                 eq(false));
2648     }
2649 
2650     @Test
faceBypassFailure_requestActiveUnlock_dismissKeyguard()2651     public void faceBypassFailure_requestActiveUnlock_dismissKeyguard()
2652             throws RemoteException {
2653         // GIVEN shouldTriggerActiveUnlock
2654         when(mAuthController.isUdfpsFingerDown()).thenReturn(false);
2655         keyguardIsVisible();
2656         keyguardNotGoingAway();
2657         statusBarShadeIsNotLocked();
2658         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2659 
2660         // GIVEN active unlock triggers on biometric failures
2661         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2662                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL))
2663                 .thenReturn(true);
2664 
2665         // WHEN face fails & bypass is not allowed
2666         lockscreenBypassIsAllowed();
2667         mKeyguardUpdateMonitor.mFaceAuthenticationCallback.onAuthenticationFailed();
2668 
2669         // THEN request unlock with a keyguard dismissal
2670         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2671                 eq(true));
2672     }
2673 
2674     @Test
faceNonBypassFailure_requestActiveUnlock_dismissKeyguard()2675     public void faceNonBypassFailure_requestActiveUnlock_dismissKeyguard()
2676             throws RemoteException {
2677         // GIVEN shouldTriggerActiveUnlock
2678         when(mAuthController.isUdfpsFingerDown()).thenReturn(false);
2679         lockscreenBypassIsNotAllowed();
2680         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2681 
2682         // GIVEN active unlock triggers on biometric failures
2683         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2684                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL))
2685                 .thenReturn(true);
2686 
2687         // WHEN face fails & on the bouncer
2688         bouncerFullyVisible();
2689         mKeyguardUpdateMonitor.mFaceAuthenticationCallback.onAuthenticationFailed();
2690 
2691         // THEN request unlock with a keyguard dismissal
2692         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2693                 eq(true));
2694     }
2695 
2696     @Test
testShouldListenForFace_withAuthSupportPostureConfig_returnsTrue()2697     public void testShouldListenForFace_withAuthSupportPostureConfig_returnsTrue()
2698             throws RemoteException {
2699         mKeyguardUpdateMonitor.mConfigFaceAuthSupportedPosture = DEVICE_POSTURE_CLOSED;
2700         keyguardNotGoingAway();
2701         bouncerFullyVisibleAndNotGoingToSleep();
2702         currentUserIsSystem();
2703         currentUserDoesNotHaveTrust();
2704         biometricsNotDisabledThroughDevicePolicyManager();
2705         biometricsEnabledForCurrentUser();
2706         userNotCurrentlySwitching();
2707         supportsFaceDetection();
2708 
2709         deviceInPostureStateOpened();
2710         mTestableLooper.processAllMessages();
2711         // Should not listen for face when posture state in DEVICE_POSTURE_OPENED
2712         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isFalse();
2713 
2714         deviceInPostureStateClosed();
2715         mTestableLooper.processAllMessages();
2716         // Should listen for face when posture state in DEVICE_POSTURE_CLOSED
2717         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2718     }
2719 
2720     @Test
testShouldListenForFace_withoutAuthSupportPostureConfig_returnsTrue()2721     public void testShouldListenForFace_withoutAuthSupportPostureConfig_returnsTrue()
2722             throws RemoteException {
2723         mKeyguardUpdateMonitor.mConfigFaceAuthSupportedPosture = DEVICE_POSTURE_UNKNOWN;
2724         keyguardNotGoingAway();
2725         bouncerFullyVisibleAndNotGoingToSleep();
2726         currentUserIsSystem();
2727         currentUserDoesNotHaveTrust();
2728         biometricsNotDisabledThroughDevicePolicyManager();
2729         biometricsEnabledForCurrentUser();
2730         userNotCurrentlySwitching();
2731         supportsFaceDetection();
2732 
2733         deviceInPostureStateClosed();
2734         mTestableLooper.processAllMessages();
2735         // Whether device in any posture state, always listen for face
2736         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2737 
2738         deviceInPostureStateOpened();
2739         mTestableLooper.processAllMessages();
2740         // Whether device in any posture state, always listen for face
2741         assertThat(mKeyguardUpdateMonitor.shouldListenForFace()).isTrue();
2742     }
2743 
2744     @Test
testBatteryChangedIntent_refreshBatteryInfo()2745     public void testBatteryChangedIntent_refreshBatteryInfo() {
2746         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(mContext, getBatteryIntent());
2747 
2748         BatteryStatus status = verifyRefreshBatteryInfo();
2749         assertThat(status.incompatibleCharger.get()).isFalse();
2750         assertThat(mKeyguardUpdateMonitor.mIncompatibleCharger).isFalse();
2751     }
2752 
2753     @Test
testUsbComplianceIntent_refreshBatteryInfo()2754     public void testUsbComplianceIntent_refreshBatteryInfo() {
2755         Context contextSpy = getSpyContext();
2756 
2757         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(
2758                 contextSpy, new Intent(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED));
2759 
2760         mTestableLooper.processAllMessages();
2761         assertThat(mKeyguardUpdateMonitor.mIncompatibleCharger).isFalse();
2762     }
2763 
2764     @Test
testUsbComplianceIntent_refreshBatteryInfoWithIncompatibleCharger()2765     public void testUsbComplianceIntent_refreshBatteryInfoWithIncompatibleCharger() {
2766         Context contextSpy = getSpyContext();
2767         setupIncompatibleCharging();
2768 
2769         mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(
2770                 contextSpy, new Intent(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED));
2771 
2772         mTestableLooper.processAllMessages();
2773         assertThat(mKeyguardUpdateMonitor.mIncompatibleCharger).isTrue();
2774     }
2775 
2776     @Test
unfoldWakeup_requestActiveUnlock_forceDismissKeyguard()2777     public void unfoldWakeup_requestActiveUnlock_forceDismissKeyguard()
2778             throws RemoteException {
2779         // GIVEN shouldTriggerActiveUnlock
2780         keyguardIsVisible();
2781         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2782 
2783         // GIVEN active unlock triggers on wakeup
2784         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2785                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE))
2786                 .thenReturn(true);
2787 
2788         // GIVEN an unfold should force dismiss the keyguard
2789         when(mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(
2790                 PowerManager.WAKE_REASON_UNFOLD_DEVICE)).thenReturn(true);
2791 
2792         // WHEN device wakes up from an unfold
2793         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_UNFOLD_DEVICE);
2794         mTestableLooper.processAllMessages();
2795 
2796         // THEN request unlock with a keyguard dismissal
2797         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2798                 eq(true));
2799     }
2800 
2801     @Test
unfoldWakeup_requestActiveUnlock_noDismissKeyguard()2802     public void unfoldWakeup_requestActiveUnlock_noDismissKeyguard()
2803             throws RemoteException {
2804         // GIVEN shouldTriggerActiveUnlock on wake from UNFOLD_DEVICE
2805         keyguardIsVisible();
2806         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2807 
2808         // GIVEN active unlock triggers on wakeup
2809         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2810                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE))
2811                 .thenReturn(true);
2812 
2813         // GIVEN an unfold should NOT force dismiss the keyguard
2814         when(mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(
2815                 PowerManager.WAKE_REASON_UNFOLD_DEVICE)).thenReturn(false);
2816 
2817         // WHEN device wakes up from an unfold
2818         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_UNFOLD_DEVICE);
2819         mTestableLooper.processAllMessages();
2820 
2821         // THEN request unlock WITHOUT a keyguard dismissal
2822         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2823                 eq(false));
2824     }
2825 
2826     @Test
unfoldFromPostureChange_requestActiveUnlock_forceDismissKeyguard()2827     public void unfoldFromPostureChange_requestActiveUnlock_forceDismissKeyguard()
2828             throws RemoteException {
2829         // GIVEN shouldTriggerActiveUnlock
2830         keyguardIsVisible();
2831         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2832 
2833         // GIVEN active unlock triggers on wakeup
2834         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2835                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE))
2836                 .thenReturn(true);
2837 
2838         // GIVEN an unfold should force dismiss the keyguard
2839         when(mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(
2840                 PowerManager.WAKE_REASON_UNFOLD_DEVICE)).thenReturn(true);
2841 
2842         // WHEN device posture changes to unfold
2843         deviceInPostureStateOpened();
2844         mTestableLooper.processAllMessages();
2845 
2846         // THEN request unlock with a keyguard dismissal
2847         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2848                 eq(true));
2849     }
2850 
2851 
2852     @Test
unfoldFromPostureChange_requestActiveUnlock_noDismissKeyguard()2853     public void unfoldFromPostureChange_requestActiveUnlock_noDismissKeyguard()
2854             throws RemoteException {
2855         // GIVEN shouldTriggerActiveUnlock on wake from UNFOLD_DEVICE
2856         keyguardIsVisible();
2857         when(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())).thenReturn(true);
2858 
2859         // GIVEN active unlock triggers on wakeup
2860         when(mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(
2861                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE))
2862                 .thenReturn(true);
2863 
2864         // GIVEN an unfold should NOT force dismiss the keyguard
2865         when(mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(
2866                 PowerManager.WAKE_REASON_UNFOLD_DEVICE)).thenReturn(false);
2867 
2868         // WHEN device posture changes to unfold
2869         deviceInPostureStateOpened();
2870         mTestableLooper.processAllMessages();
2871 
2872         // THEN request unlock WITHOUT a keyguard dismissal
2873         verify(mTrustManager).reportUserRequestedUnlock(eq(KeyguardUpdateMonitor.getCurrentUser()),
2874                 eq(false));
2875     }
2876 
2877     @Test
detectFingerprint_onTemporaryLockoutReset_authenticateFingerprint()2878     public void detectFingerprint_onTemporaryLockoutReset_authenticateFingerprint() {
2879         ArgumentCaptor<FingerprintManager.LockoutResetCallback> fpLockoutResetCallbackCaptor =
2880                 ArgumentCaptor.forClass(FingerprintManager.LockoutResetCallback.class);
2881         verify(mFingerprintManager).addLockoutResetCallback(fpLockoutResetCallbackCaptor.capture());
2882 
2883         // GIVEN device is locked out
2884         fingerprintErrorTemporaryLockOut();
2885 
2886         // GIVEN FP detection is running
2887         givenDetectFingerprintWithClearingFingerprintManagerInvocations();
2888         verifyFingerprintDetectCall();
2889         verifyFingerprintAuthenticateNeverCalled();
2890 
2891         // WHEN temporary lockout resets
2892         fpLockoutResetCallbackCaptor.getValue().onLockoutReset(0);
2893         mTestableLooper.processAllMessages();
2894 
2895         // THEN fingerprint detect state should cancel & then restart (for authenticate call)
2896         assertThat(mKeyguardUpdateMonitor.mFingerprintRunningState)
2897                 .isEqualTo(BIOMETRIC_STATE_CANCELLING_RESTARTING);
2898     }
2899 
2900     @Test
faceAuthenticateOptions_bouncerAuthenticateReason()2901     public void faceAuthenticateOptions_bouncerAuthenticateReason() {
2902         // GIVEN the bouncer is fully visible
2903         bouncerFullyVisible();
2904 
2905         // WHEN authenticate is called
2906         ArgumentCaptor<FaceAuthenticateOptions> captor =
2907                 ArgumentCaptor.forClass(FaceAuthenticateOptions.class);
2908         verify(mFaceManager).authenticate(any(), any(), any(), any(), captor.capture());
2909 
2910         // THEN the authenticate reason is attributed to the bouncer
2911         assertThat(captor.getValue().getAuthenticateReason())
2912                 .isEqualTo(AUTHENTICATE_REASON_PRIMARY_BOUNCER_SHOWN);
2913     }
2914 
2915     @Test
faceAuthenticateOptions_wakingUpAuthenticateReason_powerButtonWakeReason()2916     public void faceAuthenticateOptions_wakingUpAuthenticateReason_powerButtonWakeReason() {
2917         // GIVEN keyguard is visible
2918         keyguardIsVisible();
2919 
2920         // WHEN device wakes up from the power button
2921         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
2922         mTestableLooper.processAllMessages();
2923 
2924         // THEN face auth is triggered
2925         ArgumentCaptor<FaceAuthenticateOptions> captor =
2926                 ArgumentCaptor.forClass(FaceAuthenticateOptions.class);
2927         verify(mFaceManager).authenticate(any(), any(), any(), any(), captor.capture());
2928 
2929         // THEN the authenticate reason is attributed to the waking
2930         assertThat(captor.getValue().getAuthenticateReason())
2931                 .isEqualTo(AUTHENTICATE_REASON_STARTED_WAKING_UP);
2932 
2933         // THEN the wake reason is attributed to the power button
2934         assertThat(captor.getValue().getWakeReason())
2935                 .isEqualTo(PowerManager.WAKE_REASON_POWER_BUTTON);
2936     }
2937     @Test
testFingerprintSensorProperties()2938     public void testFingerprintSensorProperties() throws RemoteException {
2939         mFingerprintAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(
2940                 new ArrayList<>());
2941 
2942         assertThat(mKeyguardUpdateMonitor.isUnlockWithFingerprintPossible(
2943                 KeyguardUpdateMonitor.getCurrentUser())).isFalse();
2944 
2945         mFingerprintAuthenticatorsRegisteredCallback
2946                 .onAllAuthenticatorsRegistered(mFingerprintSensorProperties);
2947 
2948         verifyFingerprintAuthenticateCall();
2949         assertThat(mKeyguardUpdateMonitor.isUnlockWithFingerprintPossible(
2950                 KeyguardUpdateMonitor.getCurrentUser())).isTrue();
2951     }
2952     @Test
testFaceSensorProperties()2953     public void testFaceSensorProperties() throws RemoteException {
2954         mFaceAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(new ArrayList<>());
2955 
2956         assertThat(mKeyguardUpdateMonitor.isFaceAuthEnabledForUser(
2957                 KeyguardUpdateMonitor.getCurrentUser())).isFalse();
2958 
2959         mFaceAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(mFaceSensorProperties);
2960         biometricsEnabledForCurrentUser();
2961 
2962         verifyFaceAuthenticateNeverCalled();
2963         verifyFaceDetectNeverCalled();
2964         assertThat(mKeyguardUpdateMonitor.isFaceAuthEnabledForUser(
2965                 KeyguardUpdateMonitor.getCurrentUser())).isTrue();
2966     }
2967 
2968     @Test
testFingerprintListeningStateWhenOccluded()2969     public void testFingerprintListeningStateWhenOccluded() {
2970         when(mAuthController.isUdfpsSupported()).thenReturn(true);
2971 
2972         mKeyguardUpdateMonitor.setKeyguardShowing(false, false);
2973         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_BIOMETRIC);
2974         mKeyguardUpdateMonitor.setKeyguardShowing(false, true);
2975 
2976         verifyFingerprintAuthenticateNeverCalled();
2977 
2978         mKeyguardUpdateMonitor.setKeyguardShowing(true, true);
2979         mKeyguardUpdateMonitor.setAlternateBouncerShowing(true);
2980 
2981         verifyFingerprintAuthenticateCall();
2982     }
2983 
2984     @Test
onTrustChangedCallbacksCalledBeforeOnTrustGrantedForCurrentUserCallback()2985     public void onTrustChangedCallbacksCalledBeforeOnTrustGrantedForCurrentUserCallback() {
2986         // GIVEN device is interactive
2987         deviceIsInteractive();
2988 
2989         // GIVEN callback is registered
2990         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
2991         mKeyguardUpdateMonitor.registerCallback(callback);
2992 
2993         // WHEN onTrustChanged enabled=true
2994         mKeyguardUpdateMonitor.onTrustChanged(
2995                 true /* enabled */,
2996                 true /* newlyUnlocked */,
2997                 getCurrentUser() /* userId */,
2998                 TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD /* flags */,
2999                 null /* trustGrantedMessages */);
3000 
3001         // THEN onTrustChanged is called FIRST
3002         final InOrder inOrder = Mockito.inOrder(callback);
3003         inOrder.verify(callback).onTrustChanged(eq(getCurrentUser()));
3004 
3005         // AND THEN onTrustGrantedForCurrentUser callback called
3006         inOrder.verify(callback).onTrustGrantedForCurrentUser(
3007                 eq(true) /* dismissKeyguard */,
3008                 eq(true) /* newlyUnlocked */,
3009                 eq(new TrustGrantFlags(TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD)),
3010                 eq(null) /* message */
3011         );
3012     }
3013 
3014     @Test
testOnSimStateChanged_Unknown()3015     public void testOnSimStateChanged_Unknown() {
3016         KeyguardUpdateMonitorCallback keyguardUpdateMonitorCallback = spy(
3017                 KeyguardUpdateMonitorCallback.class);
3018         mKeyguardUpdateMonitor.registerCallback(keyguardUpdateMonitorCallback);
3019         mKeyguardUpdateMonitor.handleSimStateChange(-1, 0, TelephonyManager.SIM_STATE_UNKNOWN);
3020         verify(keyguardUpdateMonitorCallback).onSimStateChanged(-1, 0,
3021                 TelephonyManager.SIM_STATE_UNKNOWN);
3022     }
3023 
3024     @Test
testOnSimStateChanged_HandleSimStateNotReady()3025     public void testOnSimStateChanged_HandleSimStateNotReady() {
3026         KeyguardUpdateMonitorCallback keyguardUpdateMonitorCallback = spy(
3027                 KeyguardUpdateMonitorCallback.class);
3028         mKeyguardUpdateMonitor.registerCallback(keyguardUpdateMonitorCallback);
3029         mKeyguardUpdateMonitor.handleSimStateChange(-1, 0, TelephonyManager.SIM_STATE_NOT_READY);
3030         verify(keyguardUpdateMonitorCallback).onSimStateChanged(-1, 0,
3031                 TelephonyManager.SIM_STATE_NOT_READY);
3032     }
3033 
3034     @Test
onAuthEnrollmentChangesCallbacksAreNotified()3035     public void onAuthEnrollmentChangesCallbacksAreNotified() {
3036         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
3037         ArgumentCaptor<AuthController.Callback> authCallback = ArgumentCaptor.forClass(
3038                 AuthController.Callback.class);
3039         verify(mAuthController).addCallback(authCallback.capture());
3040 
3041         mKeyguardUpdateMonitor.registerCallback(callback);
3042 
3043         authCallback.getValue().onEnrollmentsChanged(TYPE_FINGERPRINT);
3044         mTestableLooper.processAllMessages();
3045         verify(callback).onBiometricEnrollmentStateChanged(BiometricSourceType.FINGERPRINT);
3046 
3047         authCallback.getValue().onEnrollmentsChanged(BiometricAuthenticator.TYPE_FACE);
3048         mTestableLooper.processAllMessages();
3049         verify(callback).onBiometricEnrollmentStateChanged(BiometricSourceType.FACE);
3050     }
3051 
3052     @Test
stopFaceAuthOnDisplayOffFlagNotEnabled_doNotRegisterForDisplayCallback()3053     public void stopFaceAuthOnDisplayOffFlagNotEnabled_doNotRegisterForDisplayCallback() {
3054         assertThat(mDisplayTracker.getDisplayCallbacks().size()).isEqualTo(0);
3055     }
3056 
3057     @Test
onDisplayOn_nothingHappens()3058     public void onDisplayOn_nothingHappens() throws RemoteException {
3059         // GIVEN
3060         keyguardIsVisible();
3061         enableStopFaceAuthOnDisplayOff();
3062 
3063         // WHEN the default display state changes to ON
3064         triggerDefaultDisplayStateChangeToOn();
3065 
3066         // THEN face auth is NOT started since we rely on STARTED_WAKING_UP to start face auth,
3067         // NOT the display on event
3068         verifyFaceAuthenticateNeverCalled();
3069         verifyFaceDetectNeverCalled();
3070     }
3071 
3072     @Test
onDisplayOff_stopFaceAuth()3073     public void onDisplayOff_stopFaceAuth() throws RemoteException {
3074         enableStopFaceAuthOnDisplayOff();
3075 
3076         // GIVEN device is listening for face
3077         mKeyguardUpdateMonitor.setKeyguardShowing(true, false);
3078         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
3079         mTestableLooper.processAllMessages();
3080         verifyFaceAuthenticateCall();
3081 
3082         final CancellationSignal faceCancel = spy(mKeyguardUpdateMonitor.mFaceCancelSignal);
3083         mKeyguardUpdateMonitor.mFaceCancelSignal = faceCancel;
3084         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
3085         mKeyguardUpdateMonitor.registerCallback(callback);
3086 
3087         // WHEN the default display state changes to OFF
3088         triggerDefaultDisplayStateChangeToOff();
3089 
3090         // THEN face listening is stopped.
3091         verify(faceCancel).cancel();
3092         verify(callback).onBiometricRunningStateChanged(
3093                 eq(false), eq(BiometricSourceType.FACE));
3094     }
3095 
3096     @Test
onDisplayOff_whileAsleep_doesNotStopFaceAuth()3097     public void onDisplayOff_whileAsleep_doesNotStopFaceAuth() throws RemoteException {
3098         enableStopFaceAuthOnDisplayOff();
3099         when(mWakefulness.getWakefulness()).thenReturn(WAKEFULNESS_ASLEEP);
3100 
3101         // GIVEN device is listening for face
3102         mKeyguardUpdateMonitor.setKeyguardShowing(true, false);
3103         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
3104         mTestableLooper.processAllMessages();
3105         verifyFaceAuthenticateCall();
3106 
3107         final CancellationSignal faceCancel = spy(mKeyguardUpdateMonitor.mFaceCancelSignal);
3108         mKeyguardUpdateMonitor.mFaceCancelSignal = faceCancel;
3109         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
3110         mKeyguardUpdateMonitor.registerCallback(callback);
3111 
3112         // WHEN the default display state changes to OFF
3113         triggerDefaultDisplayStateChangeToOff();
3114 
3115         // THEN face listening is NOT stopped.
3116         verify(faceCancel, never()).cancel();
3117         verify(callback, never()).onBiometricRunningStateChanged(
3118                 eq(false), eq(BiometricSourceType.FACE));
3119     }
3120 
3121     @Test
onDisplayOff_whileWaking_doesNotStopFaceAuth()3122     public void onDisplayOff_whileWaking_doesNotStopFaceAuth() throws RemoteException {
3123         enableStopFaceAuthOnDisplayOff();
3124         when(mWakefulness.getWakefulness()).thenReturn(WAKEFULNESS_WAKING);
3125 
3126         // GIVEN device is listening for face
3127         mKeyguardUpdateMonitor.setKeyguardShowing(true, false);
3128         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
3129         mTestableLooper.processAllMessages();
3130         verifyFaceAuthenticateCall();
3131 
3132         final CancellationSignal faceCancel = spy(mKeyguardUpdateMonitor.mFaceCancelSignal);
3133         mKeyguardUpdateMonitor.mFaceCancelSignal = faceCancel;
3134         KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
3135         mKeyguardUpdateMonitor.registerCallback(callback);
3136 
3137         // WHEN the default display state changes to OFF
3138         triggerDefaultDisplayStateChangeToOff();
3139 
3140         // THEN face listening is NOT stopped.
3141         verify(faceCancel, never()).cancel();
3142         verify(callback, never()).onBiometricRunningStateChanged(
3143                 eq(false), eq(BiometricSourceType.FACE));
3144     }
3145 
triggerDefaultDisplayStateChangeToOn()3146     private void triggerDefaultDisplayStateChangeToOn() {
3147         triggerDefaultDisplayStateChangeTo(true);
3148     }
3149 
triggerDefaultDisplayStateChangeToOff()3150     private void triggerDefaultDisplayStateChangeToOff() {
3151         triggerDefaultDisplayStateChangeTo(false);
3152     }
3153 
3154     /**
3155      * @param on true for Display.STATE_ON, else Display.STATE_OFF
3156      */
triggerDefaultDisplayStateChangeTo(boolean on)3157     private void triggerDefaultDisplayStateChangeTo(boolean on) {
3158         DisplayManagerGlobal displayManagerGlobal = mock(DisplayManagerGlobal.class);
3159         DisplayInfo displayInfoWithDisplayState = new DisplayInfo();
3160         displayInfoWithDisplayState.state = on ? Display.STATE_ON : Display.STATE_OFF;
3161         when(displayManagerGlobal.getDisplayInfo(mDisplayTracker.getDefaultDisplayId()))
3162                 .thenReturn(displayInfoWithDisplayState);
3163         mDisplayTracker.setAllDisplays(new Display[]{
3164                 new Display(
3165                         displayManagerGlobal,
3166                         mDisplayTracker.getDefaultDisplayId(),
3167                         displayInfoWithDisplayState,
3168                         DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS
3169                 )
3170         });
3171         mDisplayTracker.triggerOnDisplayChanged(mDisplayTracker.getDefaultDisplayId());
3172     }
3173 
verifyFingerprintAuthenticateNeverCalled()3174     private void verifyFingerprintAuthenticateNeverCalled() {
3175         verify(mFingerprintManager, never()).authenticate(any(), any(), any(), any(), any());
3176         verify(mFingerprintManager, never()).authenticate(any(), any(), any(), any(), anyInt(),
3177                 anyInt(), anyInt());
3178     }
3179 
verifyFingerprintAuthenticateCall()3180     private void verifyFingerprintAuthenticateCall() {
3181         verify(mFingerprintManager).authenticate(any(), any(), any(), any(), any());
3182     }
3183 
verifyFingerprintDetectNeverCalled()3184     private void verifyFingerprintDetectNeverCalled() {
3185         verify(mFingerprintManager, never()).detectFingerprint(any(), any(), any());
3186     }
3187 
verifyFingerprintDetectCall()3188     private void verifyFingerprintDetectCall() {
3189         verify(mFingerprintManager).detectFingerprint(any(), any(), any());
3190     }
3191 
verifyFaceAuthenticateNeverCalled()3192     private void verifyFaceAuthenticateNeverCalled() {
3193         verify(mFaceManager, never()).authenticate(any(), any(), any(), any(), any());
3194         verify(mFaceManager, never()).authenticate(any(), any(), any(), any(), anyInt());
3195     }
3196 
verifyFaceAuthenticateCall()3197     private void verifyFaceAuthenticateCall() {
3198         verify(mFaceManager).authenticate(any(), any(), any(), any(), any());
3199     }
3200 
verifyFaceDetectNeverCalled()3201     private void verifyFaceDetectNeverCalled() {
3202         verify(mFaceManager, never()).detectFace(any(), any(), any());
3203     }
3204 
verifyFaceDetectCall()3205     private void verifyFaceDetectCall() {
3206         verify(mFaceManager).detectFace(any(), any(), any());
3207     }
3208 
userDeviceLockDown()3209     private void userDeviceLockDown() {
3210         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
3211         when(mStrongAuthTracker.getStrongAuthForUser(mCurrentUserId))
3212                 .thenReturn(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
3213     }
3214 
supportsFaceDetection()3215     private void supportsFaceDetection() throws RemoteException {
3216         final boolean isClass3 = !mFaceSensorProperties.isEmpty()
3217                 && mFaceSensorProperties.get(0).sensorStrength == STRENGTH_STRONG;
3218         mFaceSensorProperties =
3219                 List.of(createFaceSensorProperties(/* supportsFaceDetection = */ true, isClass3));
3220         mFaceAuthenticatorsRegisteredCallback.onAllAuthenticatorsRegistered(mFaceSensorProperties);
3221     }
3222 
lockscreenBypassIsAllowed()3223     private void lockscreenBypassIsAllowed() {
3224         mockCanBypassLockscreen(true);
3225     }
3226 
mockCanBypassLockscreen(boolean canBypass)3227     private void mockCanBypassLockscreen(boolean canBypass) {
3228         // force update the isFaceEnrolled cache:
3229         mKeyguardUpdateMonitor.isFaceAuthEnabledForUser(getCurrentUser());
3230 
3231         mKeyguardUpdateMonitor.setKeyguardBypassController(mKeyguardBypassController);
3232         when(mKeyguardBypassController.canBypass()).thenReturn(canBypass);
3233     }
3234 
lockscreenBypassIsNotAllowed()3235     private void lockscreenBypassIsNotAllowed() {
3236         mockCanBypassLockscreen(false);
3237     }
3238 
cleanupKeyguardUpdateMonitor()3239     private void cleanupKeyguardUpdateMonitor() {
3240         if (mKeyguardUpdateMonitor != null) {
3241             mKeyguardUpdateMonitor.removeCallback(mTestCallback);
3242             mKeyguardUpdateMonitor.destroy();
3243             mKeyguardUpdateMonitor = null;
3244         }
3245     }
3246 
faceAuthLockOut()3247     private void faceAuthLockOut() {
3248         mKeyguardUpdateMonitor.mFaceAuthenticationCallback
3249                 .onAuthenticationError(FaceManager.FACE_ERROR_LOCKOUT_PERMANENT, "");
3250     }
3251 
statusBarShadeIsNotLocked()3252     private void statusBarShadeIsNotLocked() {
3253         mStatusBarStateListener.onStateChanged(StatusBarState.KEYGUARD);
3254     }
3255 
statusBarShadeIsLocked()3256     private void statusBarShadeIsLocked() {
3257         mStatusBarStateListener.onStateChanged(StatusBarState.SHADE_LOCKED);
3258     }
3259 
keyguardIsVisible()3260     private void keyguardIsVisible() {
3261         mKeyguardUpdateMonitor.setKeyguardShowing(true, false);
3262     }
3263 
triggerAuthInterrupt()3264     private void triggerAuthInterrupt() {
3265         mKeyguardUpdateMonitor.onAuthInterruptDetected(true);
3266     }
3267 
occludingAppRequestsFaceAuth()3268     private void occludingAppRequestsFaceAuth() {
3269         mKeyguardUpdateMonitor.requestFaceAuthOnOccludingApp(true);
3270     }
3271 
secureCameraLaunched()3272     private void secureCameraLaunched() {
3273         mKeyguardUpdateMonitor.onCameraLaunched();
3274     }
3275 
userCurrentlySwitching()3276     private void userCurrentlySwitching() {
3277         mKeyguardUpdateMonitor.setSwitchingUser(true);
3278     }
3279 
fingerprintErrorTemporaryLockOut()3280     private void fingerprintErrorTemporaryLockOut() {
3281         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
3282                 .onAuthenticationError(FINGERPRINT_ERROR_LOCKOUT, "Fingerprint locked out");
3283     }
3284 
deviceInPostureStateOpened()3285     private void deviceInPostureStateOpened() {
3286         mKeyguardUpdateMonitor.mPostureCallback.onPostureChanged(DEVICE_POSTURE_OPENED);
3287     }
3288 
deviceInPostureStateClosed()3289     private void deviceInPostureStateClosed() {
3290         mKeyguardUpdateMonitor.mPostureCallback.onPostureChanged(DEVICE_POSTURE_CLOSED);
3291     }
3292 
successfulFingerprintAuth()3293     private void successfulFingerprintAuth() {
3294         mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback
3295                 .onAuthenticationSucceeded(
3296                         new FingerprintManager.AuthenticationResult(null,
3297                                 null,
3298                                 mCurrentUserId,
3299                                 true));
3300     }
3301 
triggerSuccessfulFaceAuth()3302     private void triggerSuccessfulFaceAuth() {
3303         mKeyguardUpdateMonitor.requestFaceAuth(FaceAuthApiRequestReason.UDFPS_POINTER_DOWN);
3304         verify(mFaceManager).authenticate(any(),
3305                 any(),
3306                 mAuthenticationCallbackCaptor.capture(),
3307                 any(),
3308                 any());
3309         mAuthenticationCallbackCaptor.getValue()
3310                 .onAuthenticationSucceeded(
3311                         new FaceManager.AuthenticationResult(null, null, mCurrentUserId, false));
3312     }
3313 
currentUserIsSystem()3314     private void currentUserIsSystem() {
3315         when(mUserManager.isSystemUser()).thenReturn(true);
3316     }
3317 
biometricsNotDisabledThroughDevicePolicyManager()3318     private void biometricsNotDisabledThroughDevicePolicyManager() {
3319         when(mDevicePolicyManager.getKeyguardDisabledFeatures(null,
3320                 KeyguardUpdateMonitor.getCurrentUser())).thenReturn(0);
3321     }
3322 
biometricsEnabledForCurrentUser()3323     private void biometricsEnabledForCurrentUser() throws RemoteException {
3324         mBiometricEnabledOnKeyguardCallback.onChanged(true, KeyguardUpdateMonitor.getCurrentUser());
3325     }
3326 
biometricsDisabledForCurrentUser()3327     private void biometricsDisabledForCurrentUser() throws RemoteException {
3328         mBiometricEnabledOnKeyguardCallback.onChanged(
3329                 false,
3330                 KeyguardUpdateMonitor.getCurrentUser()
3331         );
3332     }
3333 
primaryAuthRequiredEncrypted()3334     private void primaryAuthRequiredEncrypted() {
3335         when(mStrongAuthTracker.getStrongAuthForUser(KeyguardUpdateMonitor.getCurrentUser()))
3336                 .thenReturn(STRONG_AUTH_REQUIRED_AFTER_BOOT);
3337         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
3338     }
3339 
primaryAuthRequiredForWeakBiometricOnly()3340     private void primaryAuthRequiredForWeakBiometricOnly() {
3341         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(eq(true))).thenReturn(true);
3342         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(eq(false))).thenReturn(false);
3343     }
3344 
primaryAuthNotRequiredByStrongAuthTracker()3345     private void primaryAuthNotRequiredByStrongAuthTracker() {
3346         when(mStrongAuthTracker.getStrongAuthForUser(KeyguardUpdateMonitor.getCurrentUser()))
3347                 .thenReturn(0);
3348         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(true);
3349     }
3350 
currentUserDoesNotHaveTrust()3351     private void currentUserDoesNotHaveTrust() {
3352         mKeyguardUpdateMonitor.onTrustChanged(
3353                 false,
3354                 false,
3355                 KeyguardUpdateMonitor.getCurrentUser(),
3356                 -1,
3357                 new ArrayList<>()
3358         );
3359     }
3360 
userNotCurrentlySwitching()3361     private void userNotCurrentlySwitching() {
3362         mKeyguardUpdateMonitor.setSwitchingUser(false);
3363     }
3364 
keyguardNotGoingAway()3365     private void keyguardNotGoingAway() {
3366         mKeyguardUpdateMonitor.setKeyguardGoingAway(false);
3367     }
3368 
bouncerFullyVisibleAndNotGoingToSleep()3369     private void bouncerFullyVisibleAndNotGoingToSleep() {
3370         bouncerFullyVisible();
3371         deviceNotGoingToSleep();
3372     }
3373 
deviceNotGoingToSleep()3374     private void deviceNotGoingToSleep() {
3375         mKeyguardUpdateMonitor.dispatchFinishedGoingToSleep(/* value doesn't matter */1);
3376     }
3377 
deviceGoingToSleep()3378     private void deviceGoingToSleep() {
3379         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(/* value doesn't matter */1);
3380     }
3381 
deviceIsInteractive()3382     private void deviceIsInteractive() {
3383         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
3384     }
3385 
bouncerFullyVisible()3386     private void bouncerFullyVisible() {
3387         setKeyguardBouncerVisibility(true);
3388     }
3389 
bouncerNotVisible()3390     private void bouncerNotVisible() {
3391         setKeyguardBouncerVisibility(false);
3392     }
3393 
setKeyguardBouncerVisibility(boolean isVisible)3394     private void setKeyguardBouncerVisibility(boolean isVisible) {
3395         mKeyguardUpdateMonitor.sendPrimaryBouncerChanged(isVisible, isVisible);
3396         mTestableLooper.processAllMessages();
3397     }
3398 
givenUdfpsSupported()3399     private void givenUdfpsSupported() {
3400         when(mAuthController.isUdfpsSupported()).thenReturn(true);
3401         Assert.assertTrue(mKeyguardUpdateMonitor.isUdfpsSupported());
3402     }
3403 
setBroadcastReceiverPendingResult(BroadcastReceiver receiver)3404     private void setBroadcastReceiverPendingResult(BroadcastReceiver receiver) {
3405         BroadcastReceiver.PendingResult pendingResult =
3406                 new BroadcastReceiver.PendingResult(Activity.RESULT_OK,
3407                         "resultData",
3408                         /* resultExtras= */ null,
3409                         BroadcastReceiver.PendingResult.TYPE_UNREGISTERED,
3410                         /* ordered= */ true,
3411                         /* sticky= */ false,
3412                         /* token= */ null,
3413                         UserHandle.myUserId(),
3414                         /* flags= */ 0);
3415         receiver.setPendingResult(pendingResult);
3416     }
3417 
givenDetectFingerprintWithClearingFingerprintManagerInvocations()3418     private void givenDetectFingerprintWithClearingFingerprintManagerInvocations() {
3419         // Clear invocations, since previous setup (e.g. registering BiometricManager callbacks)
3420         // will trigger updateBiometricListeningState();
3421         clearInvocations(mFingerprintManager);
3422         mKeyguardUpdateMonitor.resetBiometricListeningState();
3423 
3424         when(mStrongAuthTracker.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(false);
3425         mKeyguardUpdateMonitor.dispatchStartedGoingToSleep(0 /* why */);
3426         mTestableLooper.processAllMessages();
3427     }
3428 
givenDetectFace()3429     private void givenDetectFace() throws RemoteException {
3430         // GIVEN bypass is enabled, face detection is supported and primary auth is required
3431         lockscreenBypassIsAllowed();
3432         supportsFaceDetection();
3433         primaryAuthRequiredEncrypted();
3434         keyguardIsVisible();
3435         // fingerprint is NOT running, UDFPS is NOT supported
3436 
3437         // WHEN the device wakes up
3438         mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
3439         mTestableLooper.processAllMessages();
3440     }
3441 
enableStopFaceAuthOnDisplayOff()3442     private void enableStopFaceAuthOnDisplayOff() throws RemoteException {
3443         cleanupKeyguardUpdateMonitor();
3444         clearInvocations(mFaceManager);
3445         clearInvocations(mFingerprintManager);
3446         clearInvocations(mBiometricManager);
3447         clearInvocations(mStatusBarStateController);
3448         mFeatureFlags.set(STOP_FACE_AUTH_ON_DISPLAY_OFF, true);
3449         mKeyguardUpdateMonitor = new TestableKeyguardUpdateMonitor(mContext);
3450         setupBiometrics(mKeyguardUpdateMonitor);
3451         when(mWakefulness.getWakefulness()).thenReturn(WAKEFULNESS_AWAKE);
3452         assertThat(mDisplayTracker.getDisplayCallbacks().size()).isEqualTo(1);
3453     }
3454 
putPhoneInfo(Intent intent, Bundle data, Boolean simInited)3455     private Intent putPhoneInfo(Intent intent, Bundle data, Boolean simInited) {
3456         int subscription = simInited
3457                 ? 1/* mock subid=1 */ : SubscriptionManager.PLACEHOLDER_SUBSCRIPTION_ID_BASE;
3458         if (data != null) intent.putExtras(data);
3459 
3460         intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subscription);
3461         intent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0);
3462         return intent;
3463     }
3464 
verifyRefreshBatteryInfo()3465     private BatteryStatus verifyRefreshBatteryInfo() {
3466         mTestableLooper.processAllMessages();
3467         ArgumentCaptor<BatteryStatus> captor = ArgumentCaptor.forClass(BatteryStatus.class);
3468         verify(mTestCallback, atLeastOnce()).onRefreshBatteryInfo(captor.capture());
3469         List<BatteryStatus> batteryStatusList = captor.getAllValues();
3470         return batteryStatusList.get(batteryStatusList.size() - 1);
3471     }
3472 
setupIncompatibleCharging()3473     private void setupIncompatibleCharging() {
3474         final List<UsbPort> usbPorts = new ArrayList<>();
3475         usbPorts.add(mUsbPort);
3476         when(mUsbManager.getPorts()).thenReturn(usbPorts);
3477         when(mUsbPort.getStatus()).thenReturn(mUsbPortStatus);
3478         when(mUsbPort.supportsComplianceWarnings()).thenReturn(true);
3479         when(mUsbPortStatus.isConnected()).thenReturn(true);
3480         when(mUsbPortStatus.getComplianceWarnings()).thenReturn(new int[]{1});
3481     }
3482 
getSpyContext()3483     private Context getSpyContext() {
3484         mContext.addMockSystemService(UsbManager.class, mUsbManager);
3485         Context contextSpy = spy(mContext);
3486         doReturn(getBatteryIntent()).when(contextSpy).registerReceiver(eq(null),
3487                 any(IntentFilter.class));
3488         return contextSpy;
3489     }
3490 
getBatteryIntent()3491     private Intent getBatteryIntent() {
3492         return new Intent(Intent.ACTION_BATTERY_CHANGED).putExtra(
3493                 BatteryManager.EXTRA_CHARGING_STATUS,
3494                 BatteryManager.CHARGING_POLICY_ADAPTIVE_LONGLIFE);
3495     }
3496 
setTopStandardActivity(String pkgName)3497     private void setTopStandardActivity(String pkgName) throws RemoteException {
3498         final ActivityTaskManager.RootTaskInfo taskInfo = new ActivityTaskManager.RootTaskInfo();
3499         taskInfo.visible = true;
3500         taskInfo.topActivity = TextUtils.isEmpty(pkgName)
3501                 ? null : new ComponentName(pkgName, "testClass");
3502         when(mActivityTaskManager.getRootTaskInfo(anyInt(), eq(ACTIVITY_TYPE_STANDARD)))
3503                 .thenReturn(taskInfo);
3504     }
3505 
onTaskStackChanged()3506     private void onTaskStackChanged() {
3507         ArgumentCaptor<TaskStackChangeListener> taskStackChangeListenerCaptor =
3508                 ArgumentCaptor.forClass(TaskStackChangeListener.class);
3509         verify(mTaskStackChangeListeners).registerTaskStackListener(
3510                 taskStackChangeListenerCaptor.capture());
3511         taskStackChangeListenerCaptor.getValue().onTaskStackChangedBackground();
3512     }
3513 
3514     private class TestableKeyguardUpdateMonitor extends KeyguardUpdateMonitor {
3515         AtomicBoolean mSimStateChanged = new AtomicBoolean(false);
3516         AtomicInteger mCachedSimState = new AtomicInteger(-1);
3517 
TestableKeyguardUpdateMonitor(Context context)3518         protected TestableKeyguardUpdateMonitor(Context context) {
3519             super(context, mUserTracker,
3520                     TestableLooper.get(KeyguardUpdateMonitorTest.this).getLooper(),
3521                     mBroadcastDispatcher, mSecureSettings, mDumpManager,
3522                     mBackgroundExecutor, mMainExecutor,
3523                     mStatusBarStateController, mLockPatternUtils,
3524                     mAuthController, mTelephonyListenerManager,
3525                     mInteractionJankMonitor, mLatencyTracker, mActiveUnlockConfig,
3526                     mKeyguardUpdateMonitorLogger, mUiEventLogger, () -> mSessionTracker,
3527                     mTrustManager, mSubscriptionManager, mUserManager,
3528                     mDreamManager, mDevicePolicyManager, mSensorPrivacyManager, mTelephonyManager,
3529                     mPackageManager, mFaceManager, mFingerprintManager, mBiometricManager,
3530                     mFaceWakeUpTriggersConfig, mDevicePostureController,
3531                     Optional.of(mInteractiveToAuthProvider), mFeatureFlags,
3532                     mTaskStackChangeListeners, mActivityTaskManager, mDisplayTracker,
3533                     mWakefulness);
3534             setStrongAuthTracker(KeyguardUpdateMonitorTest.this.mStrongAuthTracker);
3535         }
3536 
hasSimStateJustChanged()3537         public boolean hasSimStateJustChanged() {
3538             return mSimStateChanged.getAndSet(false);
3539         }
3540 
getCachedSimState()3541         public int getCachedSimState() {
3542             return mCachedSimState.getAndSet(-1);
3543         }
3544 
3545         @Override
handleSimStateChange(int subId, int slotId, int state)3546         protected void handleSimStateChange(int subId, int slotId, int state) {
3547             mSimStateChanged.set(true);
3548             mCachedSimState.set(state);
3549             super.handleSimStateChange(subId, slotId, state);
3550         }
3551 
3552         @Override
getBiometricLockoutDelay()3553         protected int getBiometricLockoutDelay() {
3554             return 0;
3555         }
3556     }
3557 }
3558