diff options
72 files changed, 270 insertions, 8688 deletions
diff --git a/core/java/android/hardware/face/IFaceService.aidl b/core/java/android/hardware/face/IFaceService.aidl index 553d9f76bd01..5a0f3db81462 100644 --- a/core/java/android/hardware/face/IFaceService.aidl +++ b/core/java/android/hardware/face/IFaceService.aidl @@ -164,15 +164,9 @@ interface IFaceService { void getFeature(IBinder token, int userId, int feature, IFaceServiceReceiver receiver, String opPackageName); - // Registers all HIDL and AIDL sensors. Only HIDL sensor properties need to be provided, because - // AIDL sensor properties are retrieved directly from the available HALs. If no HIDL HALs exist, - // hidlSensors must be non-null and empty. See AuthService.java - @EnforcePermission("USE_BIOMETRIC_INTERNAL") - void registerAuthenticators(in List<FaceSensorPropertiesInternal> hidlSensors); - //Register all available face sensors. @EnforcePermission("USE_BIOMETRIC_INTERNAL") - void registerAuthenticatorsLegacy(in FaceSensorConfigurations faceSensorConfigurations); + void registerAuthenticators(in FaceSensorConfigurations faceSensorConfigurations); // Adds a callback which gets called when the service registers all of the face // authenticators. The callback is automatically removed after it's invoked. diff --git a/core/java/android/hardware/fingerprint/IFingerprintService.aidl b/core/java/android/hardware/fingerprint/IFingerprintService.aidl index 8b37c24527d7..6a96ac4afca7 100644 --- a/core/java/android/hardware/fingerprint/IFingerprintService.aidl +++ b/core/java/android/hardware/fingerprint/IFingerprintService.aidl @@ -177,13 +177,7 @@ interface IFingerprintService { //Register all available fingerprint sensors. @EnforcePermission("USE_BIOMETRIC_INTERNAL") - void registerAuthenticatorsLegacy(in FingerprintSensorConfigurations fingerprintSensorConfigurations); - - // Registers all HIDL and AIDL sensors. Only HIDL sensor properties need to be provided, because - // AIDL sensor properties are retrieved directly from the available HALs. If no HIDL HALs exist, - // hidlSensors must be non-null and empty. See AuthService.java - @EnforcePermission("USE_BIOMETRIC_INTERNAL") - void registerAuthenticators(in List<FingerprintSensorPropertiesInternal> hidlSensors); + void registerAuthenticators(in FingerprintSensorConfigurations fingerprintSensorConfigurations); // Adds a callback which gets called when the service registers all of the fingerprint // authenticators. The callback is automatically removed after it's invoked. diff --git a/services/core/java/com/android/server/biometrics/AuthService.java b/services/core/java/com/android/server/biometrics/AuthService.java index 7df63b1dab66..11cca66318d6 100644 --- a/services/core/java/com/android/server/biometrics/AuthService.java +++ b/services/core/java/com/android/server/biometrics/AuthService.java @@ -25,15 +25,12 @@ import static android.Manifest.permission.TEST_BIOMETRIC; import static android.Manifest.permission.USE_BIOMETRIC; import static android.Manifest.permission.USE_BIOMETRIC_INTERNAL; import static android.Manifest.permission.USE_FINGERPRINT; -import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FACE; -import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT; import static android.hardware.biometrics.BiometricAuthenticator.TYPE_IRIS; import static android.hardware.biometrics.BiometricAuthenticator.TYPE_NONE; import static android.hardware.biometrics.BiometricConstants.BIOMETRIC_ERROR_CANCELED; import static android.hardware.biometrics.BiometricManager.Authenticators; import android.annotation.NonNull; -import android.annotation.Nullable; import android.app.AppOpsManager; import android.content.Context; import android.content.pm.PackageManager; @@ -778,13 +775,7 @@ public class AuthService extends SystemService { hidlConfigs = null; } - if (com.android.server.biometrics.Flags.deHidl()) { - registerAuthenticators(); - } else { - // Registers HIDL and AIDL authenticators, but only HIDL configs need to be provided. - registerAuthenticators(hidlConfigs); - } - + registerAuthenticators(); mInjector.publishBinderService(this, mImpl); } @@ -874,7 +865,7 @@ public class AuthService extends SystemService { if (faceService != null) { try { - faceService.registerAuthenticatorsLegacy(mFaceSensorConfigurations); + faceService.registerAuthenticators(mFaceSensorConfigurations); } catch (RemoteException e) { Slog.e(TAG, "RemoteException when registering face authenticators", e); } @@ -912,8 +903,7 @@ public class AuthService extends SystemService { if (fingerprintService != null) { try { - fingerprintService.registerAuthenticatorsLegacy( - mFingerprintSensorConfigurations); + fingerprintService.registerAuthenticators(mFingerprintSensorConfigurations); } catch (RemoteException e) { Slog.e(TAG, "RemoteException when registering fingerprint authenticators", e); } @@ -948,78 +938,6 @@ public class AuthService extends SystemService { return configStrings; } - /** - * Registers HIDL and AIDL authenticators for all of the available modalities. - * - * @param hidlSensors Array of {@link SensorConfig} configuration for all of the HIDL sensors - * available on the device. This array may contain configuration for - * different modalities and different sensors of the same modality in - * arbitrary order. Can be null if no HIDL sensors exist on the device. - */ - private void registerAuthenticators(@Nullable SensorConfig[] hidlSensors) { - List<FingerprintSensorPropertiesInternal> hidlFingerprintSensors = new ArrayList<>(); - List<FaceSensorPropertiesInternal> hidlFaceSensors = new ArrayList<>(); - // Iris doesn't have IrisSensorPropertiesInternal, using SensorPropertiesInternal instead. - List<SensorPropertiesInternal> hidlIrisSensors = new ArrayList<>(); - - if (hidlSensors != null) { - for (SensorConfig sensor : hidlSensors) { - Slog.d(TAG, "Registering HIDL ID: " + sensor.id + " Modality: " + sensor.modality - + " Strength: " + sensor.strength); - switch (sensor.modality) { - case TYPE_FINGERPRINT: - hidlFingerprintSensors.add( - getHidlFingerprintSensorProps(sensor.id, sensor.strength)); - break; - - case TYPE_FACE: - hidlFaceSensors.add(getHidlFaceSensorProps(sensor.id, sensor.strength)); - break; - - case TYPE_IRIS: - hidlIrisSensors.add(getHidlIrisSensorProps(sensor.id, sensor.strength)); - break; - - default: - Slog.e(TAG, "Unknown modality: " + sensor.modality); - } - } - } - - final IFingerprintService fingerprintService = mInjector.getFingerprintService(); - if (fingerprintService != null) { - try { - fingerprintService.registerAuthenticators(hidlFingerprintSensors); - } catch (RemoteException e) { - Slog.e(TAG, "RemoteException when registering fingerprint authenticators", e); - } - } else if (hidlFingerprintSensors.size() > 0) { - Slog.e(TAG, "HIDL fingerprint configuration exists, but FingerprintService is null."); - } - - final IFaceService faceService = mInjector.getFaceService(); - if (faceService != null) { - try { - faceService.registerAuthenticators(hidlFaceSensors); - } catch (RemoteException e) { - Slog.e(TAG, "RemoteException when registering face authenticators", e); - } - } else if (hidlFaceSensors.size() > 0) { - Slog.e(TAG, "HIDL face configuration exists, but FaceService is null."); - } - - final IIrisService irisService = mInjector.getIrisService(); - if (irisService != null) { - try { - irisService.registerAuthenticators(hidlIrisSensors); - } catch (RemoteException e) { - Slog.e(TAG, "RemoteException when registering iris authenticators", e); - } - } else if (hidlIrisSensors.size() > 0) { - Slog.e(TAG, "HIDL iris configuration exists, but IrisService is null."); - } - } - private void checkInternalPermission() { getContext().enforceCallingOrSelfPermission(USE_BIOMETRIC_INTERNAL, "Must have USE_BIOMETRIC_INTERNAL permission"); diff --git a/services/core/java/com/android/server/biometrics/BiometricHandlerProvider.java b/services/core/java/com/android/server/biometrics/BiometricHandlerProvider.java index e57886127e63..91cabb5d331d 100644 --- a/services/core/java/com/android/server/biometrics/BiometricHandlerProvider.java +++ b/services/core/java/com/android/server/biometrics/BiometricHandlerProvider.java @@ -21,7 +21,6 @@ import static android.os.Process.THREAD_PRIORITY_DISPLAY; import android.os.Handler; import android.os.HandlerThread; -import android.os.Looper; /** * This class provides the handler to process biometric operations. @@ -76,11 +75,8 @@ public class BiometricHandlerProvider { } private Handler getNewHandler(String tag, int priority) { - if (Flags.deHidl()) { - HandlerThread handlerThread = new HandlerThread(tag, priority); - handlerThread.start(); - return new Handler(handlerThread.getLooper()); - } - return new Handler(Looper.getMainLooper()); + HandlerThread handlerThread = new HandlerThread(tag, priority); + handlerThread.start(); + return new Handler(handlerThread.getLooper()); } } diff --git a/services/core/java/com/android/server/biometrics/log/BiometricContext.java b/services/core/java/com/android/server/biometrics/log/BiometricContext.java index 7f04628ff6de..7a8e25b76944 100644 --- a/services/core/java/com/android/server/biometrics/log/BiometricContext.java +++ b/services/core/java/com/android/server/biometrics/log/BiometricContext.java @@ -81,22 +81,6 @@ public interface BiometricContext { boolean isHardwareIgnoringTouches(); /** - * Subscribe to context changes. - * - * Note that this method only notifies for properties that are visible to the HAL. - * - * @param context context that will be modified when changed - * @param consumer callback when the context is modified - * - * @deprecated instead use {@link BiometricContext#subscribe(OperationContextExt, Consumer, - * Consumer, AuthenticateOptions)} - * TODO (b/294161627): Delete this API once Flags.DE_HIDL is removed. - */ - @Deprecated - void subscribe(@NonNull OperationContextExt context, - @NonNull Consumer<OperationContext> consumer); - - /** * Subscribe to context changes and start the HAL operation. * * Note that this method only notifies for properties that are visible to the HAL. diff --git a/services/core/java/com/android/server/biometrics/log/BiometricContextProvider.java b/services/core/java/com/android/server/biometrics/log/BiometricContextProvider.java index d8dfa60bdb51..a17de3d57097 100644 --- a/services/core/java/com/android/server/biometrics/log/BiometricContextProvider.java +++ b/services/core/java/com/android/server/biometrics/log/BiometricContextProvider.java @@ -229,16 +229,6 @@ public final class BiometricContextProvider implements BiometricContext { @Override public void subscribe(@NonNull OperationContextExt context, - @NonNull Consumer<OperationContext> consumer) { - mSubscribers.put(context, consumer); - // TODO(b/294161627) Combine the getContext/subscribe APIs to avoid race - if (context.getDisplayState() != getDisplayState()) { - consumer.accept(context.update(this, context.isCrypto()).toAidlContext()); - } - } - - @Override - public void subscribe(@NonNull OperationContextExt context, @NonNull Consumer<OperationContext> startHalConsumer, @NonNull Consumer<OperationContext> updateContextConsumer, @Nullable AuthenticateOptions options) { diff --git a/services/core/java/com/android/server/biometrics/sensors/AuthenticationClient.java b/services/core/java/com/android/server/biometrics/sensors/AuthenticationClient.java index 4fa8741c867e..1e2451c2f916 100644 --- a/services/core/java/com/android/server/biometrics/sensors/AuthenticationClient.java +++ b/services/core/java/com/android/server/biometrics/sensors/AuthenticationClient.java @@ -35,7 +35,6 @@ import android.util.EventLog; import android.util.Slog; import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.Utils; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; @@ -117,24 +116,20 @@ public abstract class AuthenticationClient<T, O extends AuthenticateOptions> @LockoutTracker.LockoutMode public int handleFailedAttempt(int userId) { - if (Flags.deHidl()) { - if (mLockoutTracker != null) { - mLockoutTracker.addFailedAttemptForUser(getTargetUserId()); - } - @LockoutTracker.LockoutMode final int lockoutMode = - getLockoutTracker().getLockoutModeForUser(userId); - final PerformanceTracker performanceTracker = - PerformanceTracker.getInstanceForSensorId(getSensorId()); - if (lockoutMode == LockoutTracker.LOCKOUT_PERMANENT) { - performanceTracker.incrementPermanentLockoutForUser(userId); - } else if (lockoutMode == LockoutTracker.LOCKOUT_TIMED) { - performanceTracker.incrementTimedLockoutForUser(userId); - } - - return lockoutMode; - } else { - return LockoutTracker.LOCKOUT_NONE; + if (mLockoutTracker != null) { + mLockoutTracker.addFailedAttemptForUser(getTargetUserId()); + } + @LockoutTracker.LockoutMode final int lockoutMode = + getLockoutTracker().getLockoutModeForUser(userId); + final PerformanceTracker performanceTracker = + PerformanceTracker.getInstanceForSensorId(getSensorId()); + if (lockoutMode == LockoutTracker.LOCKOUT_PERMANENT) { + performanceTracker.incrementPermanentLockoutForUser(userId); + } else if (lockoutMode == LockoutTracker.LOCKOUT_TIMED) { + performanceTracker.incrementTimedLockoutForUser(userId); } + + return lockoutMode; } protected long getStartTimeMs() { diff --git a/services/core/java/com/android/server/biometrics/sensors/BiometricScheduler.java b/services/core/java/com/android/server/biometrics/sensors/BiometricScheduler.java index 89e08c165373..82d5d4d8141d 100644 --- a/services/core/java/com/android/server/biometrics/sensors/BiometricScheduler.java +++ b/services/core/java/com/android/server/biometrics/sensors/BiometricScheduler.java @@ -19,9 +19,9 @@ package com.android.server.biometrics.sensors; import static com.android.server.biometrics.sensors.BiometricSchedulerOperation.STATE_STARTED; import android.annotation.IntDef; -import android.annotation.MainThread; import android.annotation.NonNull; import android.annotation.Nullable; +import android.annotation.WorkerThread; import android.content.Context; import android.hardware.biometrics.IBiometricService; import android.hardware.fingerprint.FingerprintSensorPropertiesInternal; @@ -38,7 +38,6 @@ import com.android.internal.annotations.VisibleForTesting; import com.android.modules.expresslog.Counter; import com.android.server.biometrics.BiometricSchedulerProto; import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.sensors.fingerprint.GestureAvailabilityDispatcher; import java.io.PrintWriter; @@ -65,9 +64,8 @@ import java.util.function.Supplier; * @param <T> Hal instance for starting the user. * @param <U> Session associated with the current user id. * - * TODO: (b/304604965) Update thread annotation when FLAGS_DE_HIDL is removed. */ -@MainThread +@WorkerThread public class BiometricScheduler<T, U> { private static final String TAG = "BiometricScheduler"; @@ -176,7 +174,7 @@ public class BiometricScheduler<T, U> { Slog.w(TAG, "operation is already null or different (reset?): " + mCurrentOperation); } - startNextOperationIfIdle(); + checkCurrentUserAndStartNextOperation(); }); } } @@ -219,7 +217,7 @@ public class BiometricScheduler<T, U> { mRecentOperations.add(mCurrentOperation.getProtoEnum()); mCurrentOperation = null; mTotalOperationsHandled++; - startNextOperationIfIdle(); + checkCurrentUserAndStartNextOperation(); }); } }; @@ -304,15 +302,7 @@ public class BiometricScheduler<T, U> { return mInternalCallback; } - protected void startNextOperationIfIdle() { - if (Flags.deHidl()) { - startNextOperation(); - } else { - startNextOperationIfIdleLegacy(); - } - } - - protected void startNextOperation() { + protected void checkCurrentUserAndStartNextOperation() { if (mCurrentOperation != null) { Slog.v(TAG, "Not idle, current operation: " + mCurrentOperation); return; @@ -326,7 +316,7 @@ public class BiometricScheduler<T, U> { final int nextUserId = mPendingOperations.getFirst().getTargetUserId(); if (nextUserId == currentUserId || mPendingOperations.getFirst().isStartUserOperation()) { - startNextOperationIfIdleLegacy(); + startNextOperationIfIdle(); } else if (currentUserId == UserHandle.USER_NULL && mUserSwitchProvider != null) { final BaseClientMonitor startClient = mUserSwitchProvider.getStartUserClient(nextUserId); @@ -357,7 +347,7 @@ public class BiometricScheduler<T, U> { } } - protected void startNextOperationIfIdleLegacy() { + protected void startNextOperationIfIdle() { if (mCurrentOperation != null) { Slog.v(TAG, "Not idle, current operation: " + mCurrentOperation); return; @@ -422,7 +412,7 @@ public class BiometricScheduler<T, U> { // run these. A single request from the manager layer to the service layer may // actually be multiple operations (i.e. updateActiveUser + authenticate). mCurrentOperation = null; - startNextOperationIfIdle(); + checkCurrentUserAndStartNextOperation(); } } else { try { @@ -459,7 +449,7 @@ public class BiometricScheduler<T, U> { } else { Slog.e(TAG, "[Unable To Start] Prepared client: " + mCurrentOperation); mCurrentOperation = null; - startNextOperationIfIdle(); + checkCurrentUserAndStartNextOperation(); } } @@ -504,7 +494,7 @@ public class BiometricScheduler<T, U> { Slog.d(TAG, "[Cancelling Interruptable]: " + mCurrentOperation); mCurrentOperation.cancel(mHandler, mInternalCallback); } else { - startNextOperationIfIdle(); + checkCurrentUserAndStartNextOperation(); } } diff --git a/services/core/java/com/android/server/biometrics/sensors/UserAwareBiometricScheduler.java b/services/core/java/com/android/server/biometrics/sensors/UserAwareBiometricScheduler.java deleted file mode 100644 index 7ca10e3f9c98..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/UserAwareBiometricScheduler.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors; - -import static com.android.server.biometrics.sensors.BiometricSchedulerOperation.STATE_STARTED; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.content.Context; -import android.hardware.biometrics.IBiometricService; -import android.os.Handler; -import android.os.Looper; -import android.os.ServiceManager; -import android.os.UserHandle; -import android.util.Slog; - -import com.android.internal.annotations.VisibleForTesting; -import com.android.server.biometrics.sensors.fingerprint.GestureAvailabilityDispatcher; - -/** - * A user-aware scheduler that requests user-switches based on scheduled operation's targetUserId. - * TODO (b/304604965): Remove class when Flags.FLAG_DE_HIDL is removed. - * - * @param <T> Hal instance for starting the user. - * @param <U> Session associated with the current user id. - */ -public class UserAwareBiometricScheduler<T, U> extends BiometricScheduler<T, U> { - - private static final String TAG = "UaBiometricScheduler"; - - /** - * Interface to retrieve the owner's notion of the current userId. Note that even though - * the scheduler can determine this based on its history of processed clients, we should still - * query the owner since it may be cleared due to things like HAL death, etc. - */ - public interface CurrentUserRetriever { - int getCurrentUserId(); - } - - public interface UserSwitchCallback { - @NonNull StopUserClient<?> getStopUserClient(int userId); - @NonNull StartUserClient<?, ?> getStartUserClient(int newUserId); - } - - @NonNull private final CurrentUserRetriever mCurrentUserRetriever; - @NonNull private final UserSwitchCallback mUserSwitchCallback; - @Nullable private StopUserClient<?> mStopUserClient; - - private class ClientFinishedCallback implements ClientMonitorCallback { - @NonNull private final BaseClientMonitor mOwner; - - ClientFinishedCallback(@NonNull BaseClientMonitor owner) { - mOwner = owner; - } - - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, boolean success) { - mHandler.post(() -> { - Slog.d(TAG, "[Client finished] " + clientMonitor + ", success: " + success); - - // Set mStopUserClient to null when StopUserClient fails. Otherwise it's possible - // for that the queue will wait indefinitely until the field is cleared. - if (clientMonitor instanceof StopUserClient<?>) { - if (!success) { - Slog.w(TAG, "StopUserClient failed(), is the HAL stuck? " - + "Clearing mStopUserClient"); - } - mStopUserClient = null; - } - if (mCurrentOperation != null && mCurrentOperation.isFor(mOwner)) { - mCurrentOperation = null; - } else { - // can happen if the hal dies and is usually okay - // do not unset the current operation that may be newer - Slog.w(TAG, "operation is already null or different (reset?): " - + mCurrentOperation); - } - startNextOperationIfIdle(); - }); - } - } - - @VisibleForTesting - public UserAwareBiometricScheduler(@NonNull String tag, - @NonNull Handler handler, - @SensorType int sensorType, - @Nullable GestureAvailabilityDispatcher gestureAvailabilityDispatcher, - @NonNull IBiometricService biometricService, - @NonNull CurrentUserRetriever currentUserRetriever, - @NonNull UserSwitchCallback userSwitchCallback) { - super(handler, sensorType, gestureAvailabilityDispatcher, biometricService, - LOG_NUM_RECENT_OPERATIONS); - - mCurrentUserRetriever = currentUserRetriever; - mUserSwitchCallback = userSwitchCallback; - } - - public UserAwareBiometricScheduler(@NonNull String tag, - @SensorType int sensorType, - @Nullable GestureAvailabilityDispatcher gestureAvailabilityDispatcher, - @NonNull CurrentUserRetriever currentUserRetriever, - @NonNull UserSwitchCallback userSwitchCallback) { - this(tag, new Handler(Looper.getMainLooper()), sensorType, gestureAvailabilityDispatcher, - IBiometricService.Stub.asInterface( - ServiceManager.getService(Context.BIOMETRIC_SERVICE)), - currentUserRetriever, userSwitchCallback); - } - - @Override - protected void startNextOperationIfIdle() { - if (mCurrentOperation != null) { - Slog.v(TAG, "Not idle, current operation: " + mCurrentOperation); - return; - } - if (mPendingOperations.isEmpty()) { - Slog.d(TAG, "No operations, returning to idle"); - return; - } - - final int currentUserId = mCurrentUserRetriever.getCurrentUserId(); - final int nextUserId = mPendingOperations.getFirst().getTargetUserId(); - - if (nextUserId == currentUserId || mPendingOperations.getFirst().isStartUserOperation()) { - super.startNextOperationIfIdle(); - } else if (currentUserId == UserHandle.USER_NULL) { - final BaseClientMonitor startClient = - mUserSwitchCallback.getStartUserClient(nextUserId); - final ClientFinishedCallback finishedCallback = - new ClientFinishedCallback(startClient); - - Slog.d(TAG, "[Starting User] " + startClient); - mCurrentOperation = new BiometricSchedulerOperation( - startClient, finishedCallback, STATE_STARTED); - startClient.start(finishedCallback); - } else { - if (mStopUserClient != null) { - Slog.d(TAG, "[Waiting for StopUser] " + mStopUserClient); - } else { - mStopUserClient = mUserSwitchCallback - .getStopUserClient(currentUserId); - final ClientFinishedCallback finishedCallback = - new ClientFinishedCallback(mStopUserClient); - - Slog.d(TAG, "[Stopping User] current: " + currentUserId - + ", next: " + nextUserId + ". " + mStopUserClient); - mCurrentOperation = new BiometricSchedulerOperation( - mStopUserClient, finishedCallback, STATE_STARTED); - mStopUserClient.start(finishedCallback); - } - } - } - - @Override - public void onUserStopped() { - if (mStopUserClient == null) { - Slog.e(TAG, "Unexpected onUserStopped"); - return; - } - - Slog.d(TAG, "[OnUserStopped]: " + mStopUserClient); - mStopUserClient.onUserStopped(); - mStopUserClient = null; - } - - @VisibleForTesting - @Nullable public StopUserClient<?> getStopUserClient() { - return mStopUserClient; - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/FaceService.java b/services/core/java/com/android/server/biometrics/sensors/face/FaceService.java index a946af88da18..bd6d59391e4a 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/FaceService.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/FaceService.java @@ -72,9 +72,6 @@ import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; import com.android.server.biometrics.sensors.LockoutResetDispatcher; import com.android.server.biometrics.sensors.LockoutTracker; import com.android.server.biometrics.sensors.face.aidl.FaceProvider; -import com.android.server.biometrics.sensors.face.hidl.Face10; - -import com.google.android.collect.Lists; import java.io.FileDescriptor; import java.io.PrintWriter; @@ -664,60 +661,11 @@ public class FaceService extends SystemService { provider.second.scheduleGetFeature(provider.first, token, userId, feature, new ClientMonitorCallbackConverter(receiver), opPackageName); } - @NonNull - private List<ServiceProvider> getHidlProviders( - @NonNull List<FaceSensorPropertiesInternal> hidlSensors) { - final List<ServiceProvider> providers = new ArrayList<>(); - - for (FaceSensorPropertiesInternal hidlSensor : hidlSensors) { - providers.add( - Face10.newInstance(getContext(), mBiometricStateCallback, - mAuthenticationStateListeners, hidlSensor, - mLockoutResetDispatcher)); - } - - return providers; - } - - @NonNull - private List<ServiceProvider> getAidlProviders(@NonNull List<String> instances) { - final List<ServiceProvider> providers = new ArrayList<>(); - - for (String instance : instances) { - final FaceProvider provider = mFaceProvider.apply(instance); - Slog.i(TAG, "Adding AIDL provider: " + instance); - providers.add(provider); - } - - return providers; - } @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL) public void registerAuthenticators( - @NonNull List<FaceSensorPropertiesInternal> hidlSensors) { - super.registerAuthenticators_enforcePermission(); - - mRegistry.registerAll(() -> { - List<String> aidlSensors = new ArrayList<>(); - final String[] instances = mAidlInstanceNameSupplier.get(); - if (instances != null) { - aidlSensors.addAll(Lists.newArrayList(instances)); - } - - final Pair<List<FaceSensorPropertiesInternal>, List<String>> - filteredInstances = filterAvailableHalInstances(hidlSensors, aidlSensors); - - final List<ServiceProvider> providers = new ArrayList<>(); - providers.addAll(getHidlProviders(filteredInstances.first)); - providers.addAll(getAidlProviders(filteredInstances.second)); - return providers; - }); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL) - public void registerAuthenticatorsLegacy( FaceSensorConfigurations faceSensorConfigurations) { - super.registerAuthenticatorsLegacy_enforcePermission(); + super.registerAuthenticators_enforcePermission(); if (!faceSensorConfigurations.hasSensorConfigurations()) { Slog.d(TAG, "No face sensors to register."); @@ -771,40 +719,6 @@ public class FaceService extends SystemService { .getSensorPropForInstance(finalSensorInstance)); } - private Pair<List<FaceSensorPropertiesInternal>, List<String>> - filterAvailableHalInstances( - @NonNull List<FaceSensorPropertiesInternal> hidlInstances, - @NonNull List<String> aidlInstances) { - if ((hidlInstances.size() + aidlInstances.size()) <= 1) { - return new Pair(hidlInstances, aidlInstances); - } - - if (Flags.faceVhalFeature()) { - Slog.i(TAG, "Face VHAL feature is on"); - } else { - Slog.i(TAG, "Face VHAL feature is off"); - } - - final int virtualAt = aidlInstances.indexOf("virtual"); - if (Flags.faceVhalFeature() && Utils.isFaceVirtualEnabled(getContext())) { - if (virtualAt != -1) { - //only virtual instance should be returned - Slog.i(TAG, "virtual hal is used"); - return new Pair(new ArrayList<>(), List.of(aidlInstances.get(virtualAt))); - } else { - Slog.e(TAG, "Could not find virtual interface while it is enabled"); - return new Pair(hidlInstances, aidlInstances); - } - } else { - //remove virtual instance - aidlInstances = new ArrayList<>(aidlInstances); - if (virtualAt != -1) { - aidlInstances.remove(virtualAt); - } - return new Pair(hidlInstances, aidlInstances); - } - } - @Override public void addAuthenticatorsRegisteredCallback( IFaceAuthenticatorsRegisteredCallback callback) { @@ -883,17 +797,13 @@ public class FaceService extends SystemService { return null; }; - if (Flags.deHidl()) { - mFaceProviderFunction = faceProviderFunction != null ? faceProviderFunction : - ((filteredSensorProps, resetLockoutRequiresChallenge) -> new FaceProvider( - getContext(), mBiometricStateCallback, mAuthenticationStateListeners, - filteredSensorProps.second, - filteredSensorProps.first, mLockoutResetDispatcher, - BiometricContext.getInstance(getContext()), - resetLockoutRequiresChallenge)); - } else { - mFaceProviderFunction = ((filteredSensorProps, resetLockoutRequiresChallenge) -> null); - } + mFaceProviderFunction = faceProviderFunction != null ? faceProviderFunction : + ((filteredSensorProps, resetLockoutRequiresChallenge) -> new FaceProvider( + getContext(), mBiometricStateCallback, mAuthenticationStateListeners, + filteredSensorProps.second, + filteredSensorProps.first, mLockoutResetDispatcher, + BiometricContext.getInstance(getContext()), + resetLockoutRequiresChallenge)); } @Override diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/AidlResponseHandler.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/AidlResponseHandler.java index 098be2120e03..cf677d541fb2 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/AidlResponseHandler.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/AidlResponseHandler.java @@ -27,7 +27,6 @@ import android.hardware.face.Face; import android.hardware.keymaster.HardwareAuthToken; import android.util.Slog; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.HardwareAuthTokenUtils; import com.android.server.biometrics.Utils; import com.android.server.biometrics.sensors.AcquisitionClient; @@ -53,16 +52,6 @@ public class AidlResponseHandler extends ISessionCallback.Stub { /** * Interface to send results to the AidlResponseHandler's owner. */ - public interface HardwareUnavailableCallback { - /** - * Invoked when the HAL sends ERROR_HW_UNAVAILABLE. - */ - void onHardwareUnavailable(); - } - - /** - * Interface to send results to the AidlResponseHandler's owner. - */ public interface AidlResponseHandlerCallback { /** * Invoked when enrollment is successful. @@ -90,8 +79,6 @@ public class AidlResponseHandler extends ISessionCallback.Stub { @NonNull private final AuthSessionCoordinator mAuthSessionCoordinator; @NonNull - private final HardwareUnavailableCallback mHardwareUnavailableCallback; - @NonNull private final AidlResponseHandlerCallback mAidlResponseHandlerCallback; public AidlResponseHandler(@NonNull Context context, @@ -99,24 +86,6 @@ public class AidlResponseHandler extends ISessionCallback.Stub { @NonNull LockoutTracker lockoutTracker, @NonNull LockoutResetDispatcher lockoutResetDispatcher, @NonNull AuthSessionCoordinator authSessionCoordinator, - @NonNull HardwareUnavailableCallback hardwareUnavailableCallback) { - this(context, scheduler, sensorId, userId, lockoutTracker, lockoutResetDispatcher, - authSessionCoordinator, hardwareUnavailableCallback, - new AidlResponseHandlerCallback() { - @Override - public void onEnrollSuccess() {} - - @Override - public void onHardwareUnavailable() {} - }); - } - - public AidlResponseHandler(@NonNull Context context, - @NonNull BiometricScheduler scheduler, int sensorId, int userId, - @NonNull LockoutTracker lockoutTracker, - @NonNull LockoutResetDispatcher lockoutResetDispatcher, - @NonNull AuthSessionCoordinator authSessionCoordinator, - @NonNull HardwareUnavailableCallback hardwareUnavailableCallback, @NonNull AidlResponseHandlerCallback aidlResponseHandlerCallback) { mContext = context; mScheduler = scheduler; @@ -125,7 +94,6 @@ public class AidlResponseHandler extends ISessionCallback.Stub { mLockoutTracker = lockoutTracker; mLockoutResetDispatcher = lockoutResetDispatcher; mAuthSessionCoordinator = authSessionCoordinator; - mHardwareUnavailableCallback = hardwareUnavailableCallback; mAidlResponseHandlerCallback = aidlResponseHandlerCallback; } @@ -185,11 +153,7 @@ public class AidlResponseHandler extends ISessionCallback.Stub { handleResponse(ErrorConsumer.class, (c) -> { c.onError(error, vendorCode); if (error == Error.HW_UNAVAILABLE) { - if (Flags.deHidl()) { - mAidlResponseHandlerCallback.onHardwareUnavailable(); - } else { - mHardwareUnavailableCallback.onHardwareUnavailable(); - } + mAidlResponseHandlerCallback.onHardwareUnavailable(); } }); } diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceAuthenticationClient.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceAuthenticationClient.java index 415d2942be5c..c43c7d97846a 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceAuthenticationClient.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceAuthenticationClient.java @@ -20,7 +20,6 @@ import static android.adaptiveauth.Flags.reportBiometricAuthAttempts; import android.annotation.NonNull; import android.annotation.Nullable; -import android.app.NotificationManager; import android.content.Context; import android.content.res.Resources; import android.hardware.SensorPrivacyManager; @@ -39,7 +38,6 @@ import android.util.Slog; import com.android.internal.R; import com.android.internal.annotations.VisibleForTesting; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.Utils; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; @@ -70,8 +68,6 @@ public class FaceAuthenticationClient private final UsageStats mUsageStats; @NonNull private final AuthSessionCoordinator mAuthSessionCoordinator; - @Nullable - private final NotificationManager mNotificationManager; private final int[] mBiometricPromptIgnoreList; private final int[] mBiometricPromptIgnoreListVendor; private final int[] mKeyguardIgnoreList; @@ -123,7 +119,6 @@ public class FaceAuthenticationClient biometricStrength); setRequestId(requestId); mUsageStats = usageStats; - mNotificationManager = context.getSystemService(NotificationManager.class); mSensorPrivacyManager = sensorPrivacyManager; mAuthSessionCoordinator = biometricContext.getAuthSessionCoordinator(); mAuthenticationStateListeners = authenticationStateListeners; @@ -163,11 +158,7 @@ public class FaceAuthenticationClient 0 /* vendorCode */); mCallback.onClientFinished(this, false /* success */); } else { - if (Flags.deHidl()) { - startAuthenticate(); - } else { - mCancellationSignal = doAuthenticate(); - } + doAuthenticate(); } } catch (RemoteException e) { Slog.e(TAG, "Remote exception when requesting auth", e); @@ -176,27 +167,7 @@ public class FaceAuthenticationClient } } - private ICancellationSignal doAuthenticate() throws RemoteException { - final AidlSession session = getFreshDaemon(); - - if (session.hasContextMethods()) { - final OperationContextExt opContext = getOperationContext(); - final ICancellationSignal cancel = session.getSession().authenticateWithContext( - mOperationId, opContext.toAidlContext(getOptions())); - getBiometricContext().subscribe(opContext, ctx -> { - try { - session.getSession().onContextChanged(ctx); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to notify context changed", e); - } - }); - return cancel; - } else { - return session.getSession().authenticate(mOperationId); - } - } - - private void startAuthenticate() throws RemoteException { + private void doAuthenticate() throws RemoteException { final AidlSession session = getFreshDaemon(); if (session.hasContextMethods()) { diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceDetectClient.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceDetectClient.java index 5ddddda4e201..dcd948968fe8 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceDetectClient.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceDetectClient.java @@ -29,7 +29,6 @@ import android.util.Slog; import com.android.internal.annotations.VisibleForTesting; import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.OperationContextExt; @@ -112,38 +111,14 @@ public class FaceDetectClient extends AcquisitionClient<AidlSession> implements } try { - if (Flags.deHidl()) { - startDetect(); - } else { - mCancellationSignal = doDetectInteraction(); - } + doDetectInteraction(); } catch (RemoteException e) { Slog.e(TAG, "Remote exception when requesting face detect", e); mCallback.onClientFinished(this, false /* success */); } } - private ICancellationSignal doDetectInteraction() throws RemoteException { - final AidlSession session = getFreshDaemon(); - - if (session.hasContextMethods()) { - final OperationContextExt opContext = getOperationContext(); - final ICancellationSignal cancel = session.getSession().detectInteractionWithContext( - opContext.toAidlContext(mOptions)); - getBiometricContext().subscribe(opContext, ctx -> { - try { - session.getSession().onContextChanged(ctx); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to notify context changed", e); - } - }); - return cancel; - } else { - return session.getSession().detectInteraction(); - } - } - - private void startDetect() throws RemoteException { + private void doDetectInteraction() throws RemoteException { final AidlSession session = getFreshDaemon(); if (session.hasContextMethods()) { diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClient.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClient.java index 781e3f491ec8..73e8ecea639e 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClient.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClient.java @@ -36,7 +36,6 @@ import android.util.Slog; import android.view.Surface; import com.android.internal.R; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.HardwareAuthTokenUtils; import com.android.server.biometrics.Utils; import com.android.server.biometrics.log.BiometricContext; @@ -193,11 +192,7 @@ public class FaceEnrollClient extends EnrollClient<AidlSession> { features[i] = featureList.get(i); } - if (Flags.deHidl()) { - startEnroll(features); - } else { - mCancellationSignal = doEnroll(features); - } + doEnroll(features); } catch (RemoteException | IllegalArgumentException e) { Slog.e(TAG, "Exception when requesting enroll", e); onError(BiometricFaceConstants.FACE_ERROR_UNABLE_TO_PROCESS, 0 /* vendorCode */); @@ -205,43 +200,7 @@ public class FaceEnrollClient extends EnrollClient<AidlSession> { } } - private ICancellationSignal doEnroll(byte[] features) throws RemoteException { - final AidlSession session = getFreshDaemon(); - final HardwareAuthToken hat = - HardwareAuthTokenUtils.toHardwareAuthToken(mHardwareAuthToken); - - if (session.hasContextMethods()) { - final OperationContextExt opContext = getOperationContext(); - ICancellationSignal cancel; - if (session.supportsFaceEnrollOptions()) { - FaceEnrollOptions options = new FaceEnrollOptions(); - options.hardwareAuthToken = hat; - options.enrollmentType = EnrollmentType.DEFAULT; - options.features = features; - options.nativeHandlePreview = null; - options.context = opContext.toAidlContext(); - options.surfacePreview = mPreviewSurface; - cancel = session.getSession().enrollWithOptions(options); - } else { - cancel = session.getSession().enrollWithContext( - hat, EnrollmentType.DEFAULT, features, mHwPreviewHandle, - opContext.toAidlContext()); - } - getBiometricContext().subscribe(opContext, ctx -> { - try { - session.getSession().onContextChanged(ctx); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to notify context changed", e); - } - }); - return cancel; - } else { - return session.getSession().enroll(hat, EnrollmentType.DEFAULT, features, - mHwPreviewHandle); - } - } - - private void startEnroll(byte[] features) throws RemoteException { + private void doEnroll(byte[] features) throws RemoteException { final AidlSession session = getFreshDaemon(); final HardwareAuthToken hat = HardwareAuthTokenUtils.toHardwareAuthToken(mHardwareAuthToken); diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java index 11db18359f23..75b4fd3973e2 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java @@ -27,11 +27,9 @@ import android.content.pm.UserInfo; import android.hardware.biometrics.BiometricAuthenticator; import android.hardware.biometrics.BiometricFaceConstants; import android.hardware.biometrics.BiometricsProtoEnums; -import android.hardware.biometrics.ComponentInfoInternal; import android.hardware.biometrics.IInvalidationCallback; import android.hardware.biometrics.ITestSession; import android.hardware.biometrics.ITestSessionCallback; -import android.hardware.biometrics.common.ComponentInfo; import android.hardware.biometrics.face.IFace; import android.hardware.biometrics.face.SensorProps; import android.hardware.face.Face; @@ -43,7 +41,6 @@ import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; -import android.os.Looper; import android.os.RemoteException; import android.os.ServiceManager; import android.os.UserHandle; @@ -56,7 +53,6 @@ import com.android.internal.annotations.VisibleForTesting; import com.android.server.biometrics.AuthenticationStatsBroadcastReceiver; import com.android.server.biometrics.AuthenticationStatsCollector; import com.android.server.biometrics.BiometricHandlerProvider; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.Utils; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; @@ -193,11 +189,7 @@ public class FaceProvider implements IBinder.DeathRecipient, ServiceProvider { mAuthenticationStateListeners = authenticationStateListeners; mHalInstanceName = halInstanceName; mFaceSensors = new SensorList<>(ActivityManager.getService()); - if (Flags.deHidl()) { - mHandler = biometricHandlerProvider.getFaceHandler(); - } else { - mHandler = new Handler(Looper.getMainLooper()); - } + mHandler = biometricHandlerProvider.getFaceHandler(); mUsageStats = new UsageStats(context); mLockoutResetDispatcher = lockoutResetDispatcher; mActivityTaskManager = ActivityTaskManager.getInstance(); @@ -223,50 +215,15 @@ public class FaceProvider implements IBinder.DeathRecipient, ServiceProvider { } private void initSensors(boolean resetLockoutRequiresChallenge, SensorProps[] props) { - if (Flags.deHidl()) { - if (resetLockoutRequiresChallenge) { - Slog.d(getTag(), "Adding HIDL configs"); - for (SensorProps prop : props) { - addHidlSensors(prop, resetLockoutRequiresChallenge); - } - } else { - Slog.d(getTag(), "Adding AIDL configs"); - for (SensorProps prop : props) { - addAidlSensors(prop, resetLockoutRequiresChallenge); - } + if (resetLockoutRequiresChallenge) { + Slog.d(getTag(), "Adding HIDL configs"); + for (SensorProps prop : props) { + addHidlSensors(prop, resetLockoutRequiresChallenge); } } else { + Slog.d(getTag(), "Adding AIDL configs"); for (SensorProps prop : props) { - final int sensorId = prop.commonProps.sensorId; - - final List<ComponentInfoInternal> componentInfo = new ArrayList<>(); - if (prop.commonProps.componentInfo != null) { - for (ComponentInfo info : prop.commonProps.componentInfo) { - componentInfo.add(new ComponentInfoInternal(info.componentId, - info.hardwareVersion, info.firmwareVersion, info.serialNumber, - info.softwareVersion)); - } - } - - final FaceSensorPropertiesInternal internalProp = new FaceSensorPropertiesInternal( - prop.commonProps.sensorId, prop.commonProps.sensorStrength, - prop.commonProps.maxEnrollmentsPerUser, componentInfo, prop.sensorType, - prop.supportsDetectInteraction, prop.halControlsPreview, - false /* resetLockoutRequiresChallenge */); - final Sensor sensor = new Sensor(this, - mContext, mHandler, internalProp, - mBiometricContext); - sensor.init(mLockoutResetDispatcher, this); - final int userId = sensor.getLazySession().get() == null ? UserHandle.USER_NULL : - sensor.getLazySession().get().getUserId(); - mFaceSensors.addSensor(sensorId, sensor, userId, - new SynchronousUserSwitchObserver() { - @Override - public void onUserSwitching(int newUserId) { - scheduleInternalCleanup(sensorId, newUserId, null /* callback */); - } - }); - Slog.d(getTag(), "Added: " + internalProp); + addAidlSensors(prop, resetLockoutRequiresChallenge); } } } @@ -477,12 +434,7 @@ public class FaceProvider implements IBinder.DeathRecipient, ServiceProvider { @Override public int getLockoutModeForUser(int sensorId, int userId) { - if (Flags.deHidl()) { - return mFaceSensors.get(sensorId).getLockoutModeForUser(userId); - } else { - return mBiometricContext.getAuthSessionCoordinator().getLockoutStateFor(userId, - Utils.getCurrentStrength(sensorId)); - } + return mFaceSensors.get(sensorId).getLockoutModeForUser(userId); } @Override @@ -492,11 +444,7 @@ public class FaceProvider implements IBinder.DeathRecipient, ServiceProvider { @Override public boolean isHardwareDetected(int sensorId) { - if (Flags.deHidl()) { - return mFaceSensors.get(sensorId).isHardwareDetected(mHalInstanceName); - } else { - return hasHalInstance(); - } + return mFaceSensors.get(sensorId).isHardwareDetected(mHalInstanceName); } @Override @@ -549,23 +497,7 @@ public class FaceProvider implements IBinder.DeathRecipient, ServiceProvider { BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), mBiometricContext, maxTemplatesPerUser, debugConsent, options); - if (Flags.deHidl()) { - scheduleForSensor(sensorId, client, mBiometricStateCallback); - } else { - scheduleForSensor(sensorId, client, new ClientMonitorCompositeCallback( - mBiometricStateCallback, new ClientMonitorCallback() { - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - ClientMonitorCallback.super.onClientFinished(clientMonitor, - success); - if (success) { - scheduleLoadAuthenticatorIdsForUser(sensorId, userId); - scheduleInvalidationRequest(sensorId, userId); - } - } - })); - } + scheduleForSensor(sensorId, client, mBiometricStateCallback); }); return id; } @@ -614,12 +546,8 @@ public class FaceProvider implements IBinder.DeathRecipient, ServiceProvider { final int sensorId = options.getSensorId(); final boolean isStrongBiometric = Utils.isStrongBiometric(sensorId); mFaceSensors.get(sensorId).scheduleFaceUpdateActiveUserClient(userId); - final LockoutTracker lockoutTracker; - if (Flags.deHidl()) { - lockoutTracker = mFaceSensors.get(sensorId).getLockoutTracker(true /* forAuth */); - } else { - lockoutTracker = null; - } + final LockoutTracker lockoutTracker = mFaceSensors.get(sensorId).getLockoutTracker( + true /* forAuth */); final FaceAuthenticationClient client = new FaceAuthenticationClient( mContext, mFaceSensors.get(sensorId).getLazySession(), token, requestId, callback, operationId, restricted, options, cookie, @@ -634,29 +562,18 @@ public class FaceProvider implements IBinder.DeathRecipient, ServiceProvider { @Override public void onClientStarted( BaseClientMonitor clientMonitor) { - if (Flags.deHidl()) { - mBiometricHandlerProvider.getBiometricCallbackHandler().post(() -> - mAuthSessionCoordinator.authStartedFor(userId, sensorId, - requestId)); - } else { - mAuthSessionCoordinator.authStartedFor(userId, sensorId, requestId); - } + mBiometricHandlerProvider.getBiometricCallbackHandler().post(() -> + mAuthSessionCoordinator.authStartedFor(userId, sensorId, requestId)); } @Override public void onClientFinished( BaseClientMonitor clientMonitor, boolean success) { - if (Flags.deHidl()) { - mBiometricHandlerProvider.getBiometricCallbackHandler().post(() -> - mAuthSessionCoordinator.authEndedFor(userId, - Utils.getCurrentStrength(sensorId), sensorId, requestId, - client.wasAuthSuccessful())); - } else { - mAuthSessionCoordinator.authEndedFor(userId, - Utils.getCurrentStrength(sensorId), - sensorId, requestId, client.wasAuthSuccessful()); - } + mBiometricHandlerProvider.getBiometricCallbackHandler().post(() -> + mAuthSessionCoordinator.authEndedFor(userId, + Utils.getCurrentStrength(sensorId), sensorId, requestId, + client.wasAuthSuccessful())); } }); }); diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/Sensor.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/Sensor.java index 635e79a31a96..6b99493f131b 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/Sensor.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/Sensor.java @@ -42,7 +42,6 @@ import android.util.proto.ProtoOutputStream; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.FrameworkStatsLog; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.SensorServiceStateProto; import com.android.server.biometrics.SensorStateProto; import com.android.server.biometrics.UserStateProto; @@ -57,7 +56,6 @@ import com.android.server.biometrics.sensors.LockoutResetDispatcher; import com.android.server.biometrics.sensors.LockoutTracker; import com.android.server.biometrics.sensors.StartUserClient; import com.android.server.biometrics.sensors.StopUserClient; -import com.android.server.biometrics.sensors.UserAwareBiometricScheduler; import com.android.server.biometrics.sensors.UserSwitchProvider; import com.android.server.biometrics.sensors.face.FaceUtils; @@ -89,7 +87,6 @@ public class Sensor { @Nullable AidlSession mCurrentSession; @NonNull BiometricContext mBiometricContext; - Sensor(@NonNull FaceProvider provider, @NonNull Context context, @NonNull Handler handler, @NonNull FaceSensorPropertiesInternal sensorProperties, @NonNull BiometricContext biometricContext) { @@ -116,11 +113,7 @@ public class Sensor { */ public void init(@NonNull LockoutResetDispatcher lockoutResetDispatcher, @NonNull FaceProvider provider) { - if (Flags.deHidl()) { - setScheduler(getBiometricSchedulerForInit(lockoutResetDispatcher, provider)); - } else { - setScheduler(getUserAwareBiometricSchedulerForInit(lockoutResetDispatcher, provider)); - } + setScheduler(getBiometricSchedulerForInit(lockoutResetDispatcher, provider)); mLazySession = () -> mCurrentSession != null ? mCurrentSession : null; mLockoutTracker = new LockoutCache(); } @@ -149,8 +142,7 @@ public class Sensor { final AidlResponseHandler resultController = new AidlResponseHandler( mContext, mScheduler, sensorId, newUserId, mLockoutTracker, lockoutResetDispatcher, - mBiometricContext.getAuthSessionCoordinator(), () -> { - }, + mBiometricContext.getAuthSessionCoordinator(), new AidlResponseHandler.AidlResponseHandlerCallback() { @Override public void onEnrollSuccess() { @@ -173,40 +165,6 @@ public class Sensor { }); } - private UserAwareBiometricScheduler<IFace, ISession> getUserAwareBiometricSchedulerForInit( - LockoutResetDispatcher lockoutResetDispatcher, - FaceProvider provider) { - return new UserAwareBiometricScheduler<>(TAG, - BiometricScheduler.SENSOR_TYPE_FACE, null /* gestureAvailabilityDispatcher */, - () -> mCurrentSession != null ? mCurrentSession.getUserId() : UserHandle.USER_NULL, - new UserAwareBiometricScheduler.UserSwitchCallback() { - @NonNull - @Override - public StopUserClient<ISession> getStopUserClient(int userId) { - return new FaceStopUserClient(mContext, - () -> mLazySession.get().getSession(), mToken, userId, - mSensorProperties.sensorId, BiometricLogger.ofUnknown(mContext), - mBiometricContext, () -> mCurrentSession = null); - } - - @NonNull - @Override - public StartUserClient<IFace, ISession> getStartUserClient(int newUserId) { - final int sensorId = mSensorProperties.sensorId; - final AidlResponseHandler resultController = new AidlResponseHandler( - mContext, mScheduler, sensorId, newUserId, - mLockoutTracker, lockoutResetDispatcher, - mBiometricContext.getAuthSessionCoordinator(), () -> { - Slog.e(TAG, "Face sensor hardware unavailable."); - mCurrentSession = null; - }); - - return Sensor.this.getStartUserClient(resultController, sensorId, - newUserId, provider); - } - }); - } - private FaceStartUserClient getStartUserClient(@NonNull AidlResponseHandler resultController, int sensorId, int newUserId, @NonNull FaceProvider provider) { final StartUserClient.UserStartedCallback<ISession> userStartedCallback = diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/BiometricTestSessionImpl.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/BiometricTestSessionImpl.java deleted file mode 100644 index 0e2367a599a5..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/BiometricTestSessionImpl.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.ITestSession; -import android.hardware.biometrics.ITestSessionCallback; -import android.hardware.face.Face; -import android.hardware.face.FaceAuthenticationFrame; -import android.hardware.face.FaceEnrollFrame; -import android.hardware.face.FaceEnrollOptions; -import android.hardware.face.IFaceServiceReceiver; -import android.os.Binder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.sensors.BaseClientMonitor; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.face.FaceUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Random; -import java.util.Set; - -public class BiometricTestSessionImpl extends ITestSession.Stub { - private static final String TAG = "BiometricTestSessionImpl"; - - @NonNull private final Context mContext; - private final int mSensorId; - @NonNull private final ITestSessionCallback mCallback; - @NonNull private final Face10 mFace10; - @NonNull private final Face10.HalResultController mHalResultController; - @NonNull private final Set<Integer> mEnrollmentIds; - @NonNull private final Random mRandom; - - - private final IFaceServiceReceiver mReceiver = new IFaceServiceReceiver.Stub() { - @Override - public void onEnrollResult(Face face, int remaining) { - - } - - @Override - public void onAcquired(int acquiredInfo, int vendorCode) { - - } - - @Override - public void onAuthenticationSucceeded(Face face, int userId, boolean isStrongBiometric) { - - } - - @Override - public void onFaceDetected(int sensorId, int userId, boolean isStrongBiometric) { - - } - - @Override - public void onAuthenticationFailed() { - - } - - @Override - public void onError(int error, int vendorCode) { - - } - - @Override - public void onRemoved(Face face, int remaining) { - - } - - @Override - public void onFeatureSet(boolean success, int feature) { - - } - - @Override - public void onFeatureGet(boolean success, int[] features, boolean[] featureState) { - - } - - @Override - public void onChallengeGenerated(int sensorId, int userId, long challenge) { - - } - - @Override - public void onAuthenticationFrame(FaceAuthenticationFrame frame) { - - } - - @Override - public void onEnrollmentFrame(FaceEnrollFrame frame) { - - } - }; - - BiometricTestSessionImpl(@NonNull Context context, int sensorId, - @NonNull ITestSessionCallback callback, - @NonNull Face10 face10, - @NonNull Face10.HalResultController halResultController) { - mContext = context; - mSensorId = sensorId; - mCallback = callback; - mFace10 = face10; - mHalResultController = halResultController; - mEnrollmentIds = new HashSet<>(); - mRandom = new Random(); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void setTestHalEnabled(boolean enabled) { - - super.setTestHalEnabled_enforcePermission(); - - mFace10.setTestHalEnabled(enabled); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void startEnroll(int userId) { - - super.startEnroll_enforcePermission(); - - mFace10.scheduleEnroll(mSensorId, new Binder(), new byte[69], userId, mReceiver, - mContext.getOpPackageName(), new int[0] /* disabledFeatures */, - null /* previewSurface */, false /* debugConsent */, - (new FaceEnrollOptions.Builder()).build()); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void finishEnroll(int userId) { - - super.finishEnroll_enforcePermission(); - - int nextRandomId = mRandom.nextInt(); - while (mEnrollmentIds.contains(nextRandomId)) { - nextRandomId = mRandom.nextInt(); - } - - mEnrollmentIds.add(nextRandomId); - mHalResultController.onEnrollResult(0 /* deviceId */, - nextRandomId /* faceId */, userId, 0); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void acceptAuthentication(int userId) { - - // Fake authentication with any of the existing fingers - super.acceptAuthentication_enforcePermission(); - - List<Face> faces = FaceUtils.getLegacyInstance(mSensorId) - .getBiometricsForUser(mContext, userId); - if (faces.isEmpty()) { - Slog.w(TAG, "No faces, returning"); - return; - } - final int fid = faces.get(0).getBiometricId(); - final ArrayList<Byte> hat = new ArrayList<>(Collections.nCopies(69, (byte) 0)); - mHalResultController.onAuthenticated(0 /* deviceId */, fid, userId, hat); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void rejectAuthentication(int userId) { - - super.rejectAuthentication_enforcePermission(); - - mHalResultController.onAuthenticated(0 /* deviceId */, 0 /* faceId */, userId, null); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void notifyAcquired(int userId, int acquireInfo) { - - super.notifyAcquired_enforcePermission(); - - mHalResultController.onAcquired(0 /* deviceId */, userId, acquireInfo, 0 /* vendorCode */); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void notifyError(int userId, int errorCode) { - - super.notifyError_enforcePermission(); - - mHalResultController.onError(0 /* deviceId */, userId, errorCode, 0 /* vendorCode */); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void cleanupInternalState(int userId) { - - super.cleanupInternalState_enforcePermission(); - - mFace10.scheduleInternalCleanup(mSensorId, userId, new ClientMonitorCallback() { - @Override - public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { - try { - mCallback.onCleanupStarted(clientMonitor.getTargetUserId()); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception", e); - } - } - - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - try { - mCallback.onCleanupFinished(clientMonitor.getTargetUserId()); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception", e); - } - } - }); - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/Face10.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/Face10.java deleted file mode 100644 index 306ddfa1e083..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/Face10.java +++ /dev/null @@ -1,1342 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.app.ActivityManager; -import android.app.SynchronousUserSwitchObserver; -import android.app.UserSwitchObserver; -import android.content.Context; -import android.content.pm.UserInfo; -import android.hardware.biometrics.BiometricConstants; -import android.hardware.biometrics.BiometricFaceConstants; -import android.hardware.biometrics.BiometricsProtoEnums; -import android.hardware.biometrics.ITestSession; -import android.hardware.biometrics.ITestSessionCallback; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.biometrics.face.V1_0.IBiometricsFaceClientCallback; -import android.hardware.face.Face; -import android.hardware.face.FaceAuthenticateOptions; -import android.hardware.face.FaceEnrollOptions; -import android.hardware.face.FaceSensorPropertiesInternal; -import android.hardware.face.IFaceServiceReceiver; -import android.os.Binder; -import android.os.Build; -import android.os.Handler; -import android.os.IBinder; -import android.os.IHwBinder; -import android.os.Looper; -import android.os.NativeHandle; -import android.os.RemoteException; -import android.os.SystemProperties; -import android.os.UserHandle; -import android.os.UserManager; -import android.provider.Settings; -import android.util.Slog; -import android.util.proto.ProtoOutputStream; -import android.view.Surface; - -import com.android.internal.annotations.VisibleForTesting; -import com.android.internal.util.FrameworkStatsLog; -import com.android.server.biometrics.AuthenticationStatsBroadcastReceiver; -import com.android.server.biometrics.AuthenticationStatsCollector; -import com.android.server.biometrics.Flags; -import com.android.server.biometrics.SensorServiceStateProto; -import com.android.server.biometrics.SensorStateProto; -import com.android.server.biometrics.UserStateProto; -import com.android.server.biometrics.Utils; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.AcquisitionClient; -import com.android.server.biometrics.sensors.AuthSessionCoordinator; -import com.android.server.biometrics.sensors.AuthenticationConsumer; -import com.android.server.biometrics.sensors.AuthenticationStateListeners; -import com.android.server.biometrics.sensors.BaseClientMonitor; -import com.android.server.biometrics.sensors.BiometricScheduler; -import com.android.server.biometrics.sensors.BiometricStateCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.ClientMonitorCompositeCallback; -import com.android.server.biometrics.sensors.EnumerateConsumer; -import com.android.server.biometrics.sensors.ErrorConsumer; -import com.android.server.biometrics.sensors.LockoutResetDispatcher; -import com.android.server.biometrics.sensors.LockoutTracker; -import com.android.server.biometrics.sensors.PerformanceTracker; -import com.android.server.biometrics.sensors.RemovalConsumer; -import com.android.server.biometrics.sensors.face.FaceUtils; -import com.android.server.biometrics.sensors.face.LockoutHalImpl; -import com.android.server.biometrics.sensors.face.ServiceProvider; -import com.android.server.biometrics.sensors.face.UsageStats; -import com.android.server.biometrics.sensors.face.aidl.AidlResponseHandler; -import com.android.server.biometrics.sensors.face.aidl.AidlSession; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.FileDescriptor; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.time.Clock; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Supplier; - -/** - * Supports a single instance of the {@link android.hardware.biometrics.face.V1_0} or its extended - * minor versions. - */ -public class Face10 implements IHwBinder.DeathRecipient, ServiceProvider { - - private static final String TAG = "Face10"; - - private static final int ENROLL_TIMEOUT_SEC = 75; - private static final int GENERATE_CHALLENGE_REUSE_INTERVAL_MILLIS = 60 * 1000; - private static final int GENERATE_CHALLENGE_COUNTER_TTL_MILLIS = - FaceGenerateChallengeClient.CHALLENGE_TIMEOUT_SEC * 1000; - @VisibleForTesting - public static Clock sSystemClock = Clock.systemUTC(); - - private boolean mTestHalEnabled; - - @NonNull private final FaceSensorPropertiesInternal mSensorProperties; - @NonNull private final BiometricStateCallback mBiometricStateCallback; - @NonNull - private final AuthenticationStateListeners mAuthenticationStateListeners; - @NonNull private final Context mContext; - @NonNull private final BiometricScheduler<IBiometricsFace, AidlSession> mScheduler; - @NonNull private final Handler mHandler; - @NonNull private final Supplier<IBiometricsFace> mLazyDaemon; - @NonNull private final LockoutHalImpl mLockoutTracker; - @NonNull private final UsageStats mUsageStats; - @NonNull private final Map<Integer, Long> mAuthenticatorIds; - @Nullable private IBiometricsFace mDaemon; - @NonNull private final HalResultController mHalResultController; - @NonNull private final BiometricContext mBiometricContext; - @Nullable private AuthenticationStatsCollector mAuthenticationStatsCollector; - // for requests that do not use biometric prompt - @NonNull private final AtomicLong mRequestCounter = new AtomicLong(0); - private int mCurrentUserId = UserHandle.USER_NULL; - private final int mSensorId; - private final List<Long> mGeneratedChallengeCount = new ArrayList<>(); - private final LockoutResetDispatcher mLockoutResetDispatcher; - private FaceGenerateChallengeClient mGeneratedChallengeCache = null; - private AidlSession mSession; - - private final UserSwitchObserver mUserSwitchObserver = new SynchronousUserSwitchObserver() { - @Override - public void onUserSwitching(int newUserId) { - scheduleInternalCleanup(newUserId, null /* callback */); - scheduleGetFeature(mSensorId, new Binder(), newUserId, - BiometricFaceConstants.FEATURE_REQUIRE_ATTENTION, - null, mContext.getOpPackageName()); - } - }; - - public static class HalResultController extends IBiometricsFaceClientCallback.Stub { - /** - * Interface to sends results to the HalResultController's owner. - */ - public interface Callback { - /** - * Invoked when the HAL sends ERROR_HW_UNAVAILABLE. - */ - void onHardwareUnavailable(); - } - - private final int mSensorId; - @NonNull private final Context mContext; - @NonNull private final Handler mHandler; - @NonNull private final BiometricScheduler<IBiometricsFace, AidlSession> mScheduler; - @Nullable private Callback mCallback; - @NonNull private final LockoutHalImpl mLockoutTracker; - @NonNull private final LockoutResetDispatcher mLockoutResetDispatcher; - - - HalResultController(int sensorId, @NonNull Context context, @NonNull Handler handler, - @NonNull BiometricScheduler<IBiometricsFace, AidlSession> scheduler, - @NonNull LockoutHalImpl lockoutTracker, - @NonNull LockoutResetDispatcher lockoutResetDispatcher) { - mSensorId = sensorId; - mContext = context; - mHandler = handler; - mScheduler = scheduler; - mLockoutTracker = lockoutTracker; - mLockoutResetDispatcher = lockoutResetDispatcher; - } - - public void setCallback(@Nullable Callback callback) { - mCallback = callback; - } - - @Override - public void onEnrollResult(long deviceId, int faceId, int userId, int remaining) { - mHandler.post(() -> { - final CharSequence name = FaceUtils.getLegacyInstance(mSensorId) - .getUniqueName(mContext, userId); - final Face face = new Face(name, faceId, deviceId); - - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof FaceEnrollClient)) { - Slog.e(TAG, "onEnrollResult for non-enroll client: " - + Utils.getClientName(client)); - return; - } - - final FaceEnrollClient enrollClient = (FaceEnrollClient) client; - enrollClient.onEnrollResult(face, remaining); - }); - } - - @Override - public void onAuthenticated(long deviceId, int faceId, int userId, - ArrayList<Byte> token) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof AuthenticationConsumer)) { - Slog.e(TAG, "onAuthenticated for non-authentication consumer: " - + Utils.getClientName(client)); - return; - } - - final AuthenticationConsumer authenticationConsumer = - (AuthenticationConsumer) client; - final boolean authenticated = faceId != 0; - final Face face = new Face("", faceId, deviceId); - authenticationConsumer.onAuthenticated(face, authenticated, token); - }); - } - - @Override - public void onAcquired(long deviceId, int userId, int acquiredInfo, - int vendorCode) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof AcquisitionClient)) { - Slog.e(TAG, "onAcquired for non-acquire client: " - + Utils.getClientName(client)); - return; - } - - final AcquisitionClient<?> acquisitionClient = - (AcquisitionClient<?>) client; - acquisitionClient.onAcquired(acquiredInfo, vendorCode); - }); - } - - @Override - public void onError(long deviceId, int userId, int error, int vendorCode) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - Slog.d(TAG, "handleError" - + ", client: " + (client != null ? client.getOwnerString() : null) - + ", error: " + error - + ", vendorCode: " + vendorCode); - if (!(client instanceof ErrorConsumer)) { - Slog.e(TAG, "onError for non-error consumer: " + Utils.getClientName( - client)); - return; - } - - final ErrorConsumer errorConsumer = (ErrorConsumer) client; - errorConsumer.onError(error, vendorCode); - - if (error == BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE) { - Slog.e(TAG, "Got ERROR_HW_UNAVAILABLE"); - if (mCallback != null) { - mCallback.onHardwareUnavailable(); - } - } - }); - } - - @Override - public void onRemoved(long deviceId, ArrayList<Integer> removed, int userId) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof RemovalConsumer)) { - Slog.e(TAG, "onRemoved for non-removal consumer: " - + Utils.getClientName(client)); - return; - } - - final RemovalConsumer removalConsumer = (RemovalConsumer) client; - - if (!removed.isEmpty()) { - // Convert to old fingerprint-like behavior, where remove() receives - // one removal at a time. This way, remove can share some more common code. - for (int i = 0; i < removed.size(); i++) { - final int id = removed.get(i); - final Face face = new Face("", id, deviceId); - final int remaining = removed.size() - i - 1; - Slog.d(TAG, "Removed, faceId: " + id + ", remaining: " + remaining); - removalConsumer.onRemoved(face, remaining); - } - } else { - removalConsumer.onRemoved(null, 0 /* remaining */); - } - - Settings.Secure.putIntForUser(mContext.getContentResolver(), - Settings.Secure.FACE_UNLOCK_RE_ENROLL, 0, UserHandle.USER_CURRENT); - }); - } - - @Override - public void onEnumerate(long deviceId, ArrayList<Integer> faceIds, int userId) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof EnumerateConsumer)) { - Slog.e(TAG, "onEnumerate for non-enumerate consumer: " - + Utils.getClientName(client)); - return; - } - - final EnumerateConsumer enumerateConsumer = (EnumerateConsumer) client; - - if (!faceIds.isEmpty()) { - // Convert to old fingerprint-like behavior, where enumerate() receives one - // template at a time. This way, enumerate can share some more common code. - for (int i = 0; i < faceIds.size(); i++) { - final Face face = new Face("", faceIds.get(i), deviceId); - enumerateConsumer.onEnumerationResult(face, faceIds.size() - i - 1); - } - } else { - // For face, the HIDL contract is to receive an empty list when there are no - // templates enrolled. Send a null identifier since we don't consume them - // anywhere, and send remaining == 0 so this code can be shared with Face@1.1 - enumerateConsumer.onEnumerationResult(null /* identifier */, 0); - } - }); - } - - @Override - public void onLockoutChanged(long duration) { - mHandler.post(() -> { - Slog.d(TAG, "onLockoutChanged: " + duration); - final @LockoutTracker.LockoutMode int lockoutMode; - if (duration == 0) { - lockoutMode = LockoutTracker.LOCKOUT_NONE; - } else if (duration == -1 || duration == Long.MAX_VALUE) { - lockoutMode = LockoutTracker.LOCKOUT_PERMANENT; - } else { - lockoutMode = LockoutTracker.LOCKOUT_TIMED; - } - - mLockoutTracker.setCurrentUserLockoutMode(lockoutMode); - - if (duration == 0) { - mLockoutResetDispatcher.notifyLockoutResetCallbacks(mSensorId); - } - }); - } - } - - @VisibleForTesting - Face10(@NonNull Context context, - @NonNull BiometricStateCallback biometricStateCallback, - @NonNull AuthenticationStateListeners authenticationStateListeners, - @NonNull FaceSensorPropertiesInternal sensorProps, - @NonNull LockoutResetDispatcher lockoutResetDispatcher, - @NonNull Handler handler, - @NonNull BiometricScheduler<IBiometricsFace, AidlSession> scheduler, - @NonNull BiometricContext biometricContext) { - mSensorProperties = sensorProps; - mContext = context; - mBiometricStateCallback = biometricStateCallback; - mAuthenticationStateListeners = authenticationStateListeners; - mSensorId = sensorProps.sensorId; - mScheduler = scheduler; - mHandler = handler; - mBiometricContext = biometricContext; - mUsageStats = new UsageStats(context); - mAuthenticatorIds = new HashMap<>(); - mLazyDaemon = Face10.this::getDaemon; - mLockoutTracker = new LockoutHalImpl(); - mHalResultController = new HalResultController(sensorProps.sensorId, context, mHandler, - mScheduler, mLockoutTracker, lockoutResetDispatcher); - mLockoutResetDispatcher = lockoutResetDispatcher; - mHalResultController.setCallback(() -> { - mDaemon = null; - mCurrentUserId = UserHandle.USER_NULL; - }); - - AuthenticationStatsBroadcastReceiver mBroadcastReceiver = - new AuthenticationStatsBroadcastReceiver( - mContext, - BiometricsProtoEnums.MODALITY_FACE, - (AuthenticationStatsCollector collector) -> { - Slog.d(TAG, "Initializing AuthenticationStatsCollector"); - mAuthenticationStatsCollector = collector; - }); - - try { - ActivityManager.getService().registerUserSwitchObserver(mUserSwitchObserver, TAG); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to register user switch observer"); - } - } - - public static Face10 newInstance(@NonNull Context context, - @NonNull BiometricStateCallback biometricStateCallback, - @NonNull AuthenticationStateListeners authenticationStateListeners, - @NonNull FaceSensorPropertiesInternal sensorProps, - @NonNull LockoutResetDispatcher lockoutResetDispatcher) { - final Handler handler = new Handler(Looper.getMainLooper()); - return new Face10(context, biometricStateCallback, authenticationStateListeners, - sensorProps, lockoutResetDispatcher, handler, new BiometricScheduler<>( - BiometricScheduler.SENSOR_TYPE_FACE, - null /* gestureAvailabilityTracker */), - BiometricContext.getInstance(context)); - } - - @Override - public void serviceDied(long cookie) { - Slog.e(TAG, "HAL died"); - mHandler.post(() -> { - PerformanceTracker.getInstanceForSensorId(mSensorId) - .incrementHALDeathCount(); - mDaemon = null; - mCurrentUserId = UserHandle.USER_NULL; - - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (client instanceof ErrorConsumer) { - Slog.e(TAG, "Sending ERROR_HW_UNAVAILABLE for client: " + client); - final ErrorConsumer errorConsumer = (ErrorConsumer) client; - errorConsumer.onError(BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE, - 0 /* vendorCode */); - - FrameworkStatsLog.write(FrameworkStatsLog.BIOMETRIC_SYSTEM_HEALTH_ISSUE_DETECTED, - BiometricsProtoEnums.MODALITY_FACE, - BiometricsProtoEnums.ISSUE_HAL_DEATH, - -1 /* sensorId */); - } - - mScheduler.recordCrashState(); - mScheduler.reset(); - }); - } - - public int getCurrentUserId() { - return mCurrentUserId; - } - - synchronized AidlSession getSession() { - if (mDaemon != null && mSession != null) { - return mSession; - } else { - return mSession = new AidlSession(mContext, this::getDaemon, mCurrentUserId, - new AidlResponseHandler(mContext, mScheduler, mSensorId, - mCurrentUserId, mLockoutTracker, mLockoutResetDispatcher, - new AuthSessionCoordinator(), () -> { - mDaemon = null; - mCurrentUserId = UserHandle.USER_NULL; - })); - } - } - - private synchronized IBiometricsFace getDaemon() { - if (mTestHalEnabled) { - final TestHal testHal = new TestHal(mContext, mSensorId); - testHal.setCallback(mHalResultController); - return testHal; - } - - if (mDaemon != null) { - return mDaemon; - } - - Slog.d(TAG, "Daemon was null, reconnecting, current operation: " - + mScheduler.getCurrentClient()); - - try { - mDaemon = IBiometricsFace.getService(); - } catch (java.util.NoSuchElementException e) { - // Service doesn't exist or cannot be opened. - Slog.w(TAG, "NoSuchElementException", e); - } catch (RemoteException e) { - Slog.e(TAG, "Failed to get face HAL", e); - } - - if (mDaemon == null) { - Slog.w(TAG, "Face HAL not available"); - return null; - } - - mDaemon.asBinder().linkToDeath(this, 0 /* flags */); - - // HAL ID for these HIDL versions are only used to determine if callbacks have been - // successfully set. - long halId = 0; - try { - halId = mDaemon.setCallback(mHalResultController).value; - } catch (RemoteException e) { - Slog.e(TAG, "Failed to set callback for face HAL", e); - mDaemon = null; - } - - Slog.d(TAG, "Face HAL ready, HAL ID: " + halId); - if (halId != 0) { - scheduleLoadAuthenticatorIds(); - scheduleInternalCleanup(ActivityManager.getCurrentUser(), null /* callback */); - scheduleGetFeature(mSensorId, new Binder(), - ActivityManager.getCurrentUser(), - BiometricFaceConstants.FEATURE_REQUIRE_ATTENTION, null, - mContext.getOpPackageName()); - } else { - Slog.e(TAG, "Unable to set callback"); - mDaemon = null; - } - - return mDaemon; - } - - @Override - public boolean containsSensor(int sensorId) { - return mSensorId == sensorId; - } - - @Override - @NonNull - public List<FaceSensorPropertiesInternal> getSensorProperties() { - final List<FaceSensorPropertiesInternal> properties = new ArrayList<>(); - properties.add(mSensorProperties); - return properties; - } - - @NonNull - @Override - public FaceSensorPropertiesInternal getSensorProperties(int sensorId) { - return mSensorProperties; - } - - @Override - @NonNull - public List<Face> getEnrolledFaces(int sensorId, int userId) { - return FaceUtils.getLegacyInstance(mSensorId).getBiometricsForUser(mContext, userId); - } - - @Override - public boolean hasEnrollments(int sensorId, int userId) { - return !getEnrolledFaces(sensorId, userId).isEmpty(); - } - - @Override - @LockoutTracker.LockoutMode - public int getLockoutModeForUser(int sensorId, int userId) { - return mLockoutTracker.getLockoutModeForUser(userId); - } - - @Override - public long getAuthenticatorId(int sensorId, int userId) { - return mAuthenticatorIds.getOrDefault(userId, 0L); - } - - @Override - public boolean isHardwareDetected(int sensorId) { - return getDaemon() != null; - } - - private boolean isGeneratedChallengeCacheValid() { - return mGeneratedChallengeCache != null - && sSystemClock.millis() - mGeneratedChallengeCache.getCreatedAt() - < GENERATE_CHALLENGE_REUSE_INTERVAL_MILLIS; - } - - private void incrementChallengeCount() { - mGeneratedChallengeCount.add(0, sSystemClock.millis()); - } - - private int decrementChallengeCount() { - final long now = sSystemClock.millis(); - // ignore values that are old in case generate/revoke calls are not matched - // this doesn't ensure revoke if calls are mismatched but it keeps the list from growing - mGeneratedChallengeCount.removeIf(x -> now - x > GENERATE_CHALLENGE_COUNTER_TTL_MILLIS); - if (!mGeneratedChallengeCount.isEmpty()) { - mGeneratedChallengeCount.remove(0); - } - return mGeneratedChallengeCount.size(); - } - - /** - * {@link IBiometricsFace} only supports a single in-flight challenge but there are cases where - * two callers both need challenges (e.g. resetLockout right before enrollment). - */ - @Override - public void scheduleGenerateChallenge(int sensorId, int userId, @NonNull IBinder token, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - - if (Flags.deHidl()) { - scheduleGenerateChallengeAidl(userId, token, receiver, opPackageName); - } else { - scheduleGenerateChallengeHidl(userId, token, receiver, opPackageName); - } - }); - } - - private void scheduleGenerateChallengeAidl(int userId, @NonNull IBinder token, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName) { - final com.android.server.biometrics.sensors.face.aidl.FaceGenerateChallengeClient client = - new com.android.server.biometrics.sensors.face.aidl.FaceGenerateChallengeClient( - mContext, this::getSession, token, - new ClientMonitorCallbackConverter(receiver), userId, opPackageName, - mSensorId, createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { - if (client != clientMonitor) { - Slog.e(TAG, - "scheduleGenerateChallenge onClientStarted, mismatched client." - + " Expecting: " + client + ", received: " - + clientMonitor); - } - } - }); - } - - private void scheduleGenerateChallengeHidl(int userId, @NonNull IBinder token, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName) { - incrementChallengeCount(); - if (isGeneratedChallengeCacheValid()) { - Slog.d(TAG, "Current challenge is cached and will be reused"); - mGeneratedChallengeCache.reuseResult(receiver); - return; - } - - final FaceGenerateChallengeClient client = new FaceGenerateChallengeClient(mContext, - mLazyDaemon, token, new ClientMonitorCallbackConverter(receiver), userId, - opPackageName, mSensorId, createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, sSystemClock.millis()); - mGeneratedChallengeCache = client; - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { - if (client != clientMonitor) { - Slog.e(TAG, - "scheduleGenerateChallenge onClientStarted, mismatched client." - + " Expecting: " + client + ", received: " - + clientMonitor); - } - } - }); - } - - @Override - public void scheduleRevokeChallenge(int sensorId, int userId, @NonNull IBinder token, - @NonNull String opPackageName, long challenge) { - mHandler.post(() -> { - if (Flags.deHidl()) { - scheduleRevokeChallengeAidl(userId, token, opPackageName); - } else { - scheduleRevokeChallengeHidl(userId, token, opPackageName); - } - }); - } - - private void scheduleRevokeChallengeAidl(int userId, @NonNull IBinder token, - @NonNull String opPackageName) { - final com.android.server.biometrics.sensors.face.aidl.FaceRevokeChallengeClient - client = - new com.android.server.biometrics.sensors.face.aidl.FaceRevokeChallengeClient( - mContext, this::getSession, token, userId, opPackageName, mSensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), mBiometricContext, 0L); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - if (client != clientMonitor) { - Slog.e(TAG, - "scheduleRevokeChallenge, mismatched client." + "Expecting: " - + client + ", received: " + clientMonitor); - } - } - }); - } - - private void scheduleRevokeChallengeHidl(int userId, @NonNull IBinder token, - @NonNull String opPackageName) { - final boolean shouldRevoke = decrementChallengeCount() == 0; - if (!shouldRevoke) { - Slog.w(TAG, "scheduleRevokeChallenge skipped - challenge still in use: " - + mGeneratedChallengeCount); - return; - } - - Slog.d(TAG, "scheduleRevokeChallenge executing - no active clients"); - mGeneratedChallengeCache = null; - final FaceRevokeChallengeClient client = new FaceRevokeChallengeClient(mContext, - mLazyDaemon, token, userId, opPackageName, mSensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - if (client != clientMonitor) { - Slog.e(TAG, - "scheduleRevokeChallenge, mismatched client." + "Expecting: " - + client + ", received: " + clientMonitor); - } - } - }); - } - - @Override - public long scheduleEnroll(int sensorId, @NonNull IBinder token, - @NonNull byte[] hardwareAuthToken, int userId, @NonNull IFaceServiceReceiver receiver, - @NonNull String opPackageName, @NonNull int[] disabledFeatures, - @Nullable Surface previewSurface, boolean debugConsent, - @NonNull FaceEnrollOptions options) { - final long id = mRequestCounter.incrementAndGet(); - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - if (Flags.deHidl()) { - scheduleEnrollAidl(token, hardwareAuthToken, userId, receiver, - opPackageName, disabledFeatures, previewSurface, id, options); - } else { - scheduleEnrollHidl(token, hardwareAuthToken, userId, receiver, - opPackageName, disabledFeatures, previewSurface, id, options); - } - }); - return id; - } - - private void scheduleEnrollAidl(@NonNull IBinder token, - @NonNull byte[] hardwareAuthToken, int userId, @NonNull IFaceServiceReceiver receiver, - @NonNull String opPackageName, @NonNull int[] disabledFeatures, - @Nullable Surface previewSurface, long id, - @NonNull FaceEnrollOptions options) { - final com.android.server.biometrics.sensors.face.aidl.FaceEnrollClient client = - new com.android.server.biometrics.sensors.face.aidl.FaceEnrollClient( - mContext, this::getSession, token, - new ClientMonitorCallbackConverter(receiver), userId, - hardwareAuthToken, opPackageName, id, - FaceUtils.getLegacyInstance(mSensorId), disabledFeatures, - ENROLL_TIMEOUT_SEC, previewSurface, mSensorId, - createLogger(BiometricsProtoEnums.ACTION_ENROLL, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), mBiometricContext, - mContext.getResources().getInteger( - com.android.internal.R.integer.config_faceMaxTemplatesPerUser), - false, options); - - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { - mBiometricStateCallback.onClientStarted(clientMonitor); - } - - @Override - public void onBiometricAction(int action) { - mBiometricStateCallback.onBiometricAction(action); - } - - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - mBiometricStateCallback.onClientFinished(clientMonitor, success); - if (success) { - // Update authenticatorIds - scheduleUpdateActiveUserWithoutHandler(client.getTargetUserId()); - } - } - }); - } - - private void scheduleEnrollHidl(@NonNull IBinder token, - @NonNull byte[] hardwareAuthToken, int userId, @NonNull IFaceServiceReceiver receiver, - @NonNull String opPackageName, @NonNull int[] disabledFeatures, - @Nullable Surface previewSurface, long id, FaceEnrollOptions options) { - final FaceEnrollClient client = new FaceEnrollClient(mContext, mLazyDaemon, token, - new ClientMonitorCallbackConverter(receiver), userId, hardwareAuthToken, - opPackageName, id, FaceUtils.getLegacyInstance(mSensorId), disabledFeatures, - ENROLL_TIMEOUT_SEC, previewSurface, mSensorId, - createLogger(BiometricsProtoEnums.ACTION_ENROLL, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, options); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { - mBiometricStateCallback.onClientStarted(clientMonitor); - } - - @Override - public void onBiometricAction(int action) { - mBiometricStateCallback.onBiometricAction(action); - } - - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - mBiometricStateCallback.onClientFinished(clientMonitor, success); - if (success) { - // Update authenticatorIds - scheduleUpdateActiveUserWithoutHandler(client.getTargetUserId()); - } - } - }); - } - - @Override - public void cancelEnrollment(int sensorId, @NonNull IBinder token, long requestId) { - mHandler.post(() -> mScheduler.cancelEnrollment(token, requestId)); - } - - @Override - public long scheduleFaceDetect(@NonNull IBinder token, - @NonNull ClientMonitorCallbackConverter callback, - @NonNull FaceAuthenticateOptions options, int statsClient) { - throw new IllegalStateException("Face detect not supported by IBiometricsFace@1.0. Did you" - + "forget to check the supportsFaceDetection flag?"); - } - - @Override - public void cancelFaceDetect(int sensorId, @NonNull IBinder token, long requestId) { - throw new IllegalStateException("Face detect not supported by IBiometricsFace@1.0. Did you" - + "forget to check the supportsFaceDetection flag?"); - } - - @Override - public void scheduleAuthenticate(@NonNull IBinder token, long operationId, - int cookie, @NonNull ClientMonitorCallbackConverter receiver, - @NonNull FaceAuthenticateOptions options, long requestId, boolean restricted, - int statsClient, boolean allowBackgroundAuthentication) { - mHandler.post(() -> { - final int userId = options.getUserId(); - scheduleUpdateActiveUserWithoutHandler(userId); - - final boolean isStrongBiometric = Utils.isStrongBiometric(mSensorId); - if (Flags.deHidl()) { - scheduleAuthenticateAidl(token, operationId, cookie, receiver, options, requestId, - restricted, statsClient, allowBackgroundAuthentication, isStrongBiometric); - } else { - scheduleAuthenticateHidl(token, operationId, cookie, receiver, options, requestId, - restricted, statsClient, allowBackgroundAuthentication, isStrongBiometric); - } - }); - } - - private void scheduleAuthenticateAidl(@NonNull IBinder token, long operationId, - int cookie, @NonNull ClientMonitorCallbackConverter receiver, - @NonNull FaceAuthenticateOptions options, long requestId, boolean restricted, - int statsClient, boolean allowBackgroundAuthentication, boolean isStrongBiometric) { - final com.android.server.biometrics.sensors.face.aidl.FaceAuthenticationClient - client = - new com.android.server.biometrics.sensors.face.aidl.FaceAuthenticationClient( - mContext, this::getSession, token, requestId, receiver, operationId, - restricted, options, cookie, false /* requireConfirmation */, - createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient, - mAuthenticationStatsCollector), mBiometricContext, - isStrongBiometric, mUsageStats, mLockoutTracker, - allowBackgroundAuthentication, Utils.getCurrentStrength(mSensorId), - mAuthenticationStateListeners); - mScheduler.scheduleClientMonitor(client); - } - - private void scheduleAuthenticateHidl(@NonNull IBinder token, long operationId, - int cookie, @NonNull ClientMonitorCallbackConverter receiver, - @NonNull FaceAuthenticateOptions options, long requestId, boolean restricted, - int statsClient, boolean allowBackgroundAuthentication, boolean isStrongBiometric) { - final FaceAuthenticationClient client = new FaceAuthenticationClient(mContext, - mLazyDaemon, token, requestId, receiver, operationId, restricted, options, - cookie, false /* requireConfirmation */, - createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient, - mAuthenticationStatsCollector), mBiometricContext, - isStrongBiometric, mLockoutTracker, mUsageStats, - allowBackgroundAuthentication, Utils.getCurrentStrength(mSensorId), - mAuthenticationStateListeners); - mScheduler.scheduleClientMonitor(client); - } - - @Override - public long scheduleAuthenticate(@NonNull IBinder token, long operationId, - int cookie, @NonNull ClientMonitorCallbackConverter receiver, - @NonNull FaceAuthenticateOptions options, boolean restricted, int statsClient, - boolean allowBackgroundAuthentication) { - final long id = mRequestCounter.incrementAndGet(); - - scheduleAuthenticate(token, operationId, cookie, receiver, - options, id, restricted, statsClient, allowBackgroundAuthentication); - - return id; - } - - @Override - public void cancelAuthentication(int sensorId, @NonNull IBinder token, long requestId) { - mHandler.post(() -> mScheduler.cancelAuthenticationOrDetection(token, requestId)); - } - - @Override - public void scheduleRemove(int sensorId, @NonNull IBinder token, int faceId, int userId, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - - if (Flags.deHidl()) { - scheduleRemoveAidl(token, userId, receiver, opPackageName, faceId); - } else { - scheduleRemoveHidl(token, userId, receiver, opPackageName, faceId); - } - }); - } - - @Override - public void scheduleRemoveAll(int sensorId, @NonNull IBinder token, int userId, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - - // For IBiometricsFace@1.0, remove(0) means remove all enrollments - if (Flags.deHidl()) { - scheduleRemoveAidl(token, userId, receiver, opPackageName, 0); - } else { - scheduleRemoveHidl(token, userId, receiver, opPackageName, 0); - } - }); - } - - private void scheduleRemoveAidl(@NonNull IBinder token, int userId, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName, int faceId) { - final com.android.server.biometrics.sensors.face.aidl.FaceRemovalClient client = - new com.android.server.biometrics.sensors.face.aidl.FaceRemovalClient( - mContext, this::getSession, token, - new ClientMonitorCallbackConverter(receiver), new int[]{faceId}, userId, - opPackageName, FaceUtils.getLegacyInstance(mSensorId), mSensorId, - createLogger(BiometricsProtoEnums.ACTION_REMOVE, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), mBiometricContext, - mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, mBiometricStateCallback); - } - - private void scheduleRemoveHidl(@NonNull IBinder token, int userId, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName, int faceId) { - final FaceRemovalClient client = new FaceRemovalClient(mContext, mLazyDaemon, token, - new ClientMonitorCallbackConverter(receiver), faceId, userId, - opPackageName, FaceUtils.getLegacyInstance(mSensorId), mSensorId, - createLogger(BiometricsProtoEnums.ACTION_REMOVE, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, mBiometricStateCallback); - } - - @Override - public void scheduleResetLockout(int sensorId, int userId, @NonNull byte[] hardwareAuthToken) { - mHandler.post(() -> { - if (getEnrolledFaces(sensorId, userId).isEmpty()) { - Slog.w(TAG, "Ignoring lockout reset, no templates enrolled for user: " + userId); - return; - } - - scheduleUpdateActiveUserWithoutHandler(userId); - if (Flags.deHidl()) { - scheduleResetLockoutAidl(userId, hardwareAuthToken); - } else { - scheduleResetLockoutHidl(userId, hardwareAuthToken); - } - }); - } - - private void scheduleResetLockoutAidl(int userId, - @NonNull byte[] hardwareAuthToken) { - final com.android.server.biometrics.sensors.face.aidl.FaceResetLockoutClient client = - new com.android.server.biometrics.sensors.face.aidl.FaceResetLockoutClient( - mContext, this::getSession, userId, mContext.getOpPackageName(), - mSensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext, hardwareAuthToken, mLockoutTracker, - mLockoutResetDispatcher, mSensorProperties.sensorStrength); - mScheduler.scheduleClientMonitor(client); - } - - private void scheduleResetLockoutHidl(int userId, - @NonNull byte[] hardwareAuthToken) { - final FaceResetLockoutClient client = new FaceResetLockoutClient(mContext, - mLazyDaemon, - userId, mContext.getOpPackageName(), mSensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, hardwareAuthToken); - mScheduler.scheduleClientMonitor(client); - } - - @Override - public void scheduleSetFeature(int sensorId, @NonNull IBinder token, int userId, int feature, - boolean enabled, @NonNull byte[] hardwareAuthToken, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - if (Flags.deHidl()) { - scheduleSetFeatureAidl(sensorId, token, userId, feature, enabled, hardwareAuthToken, - receiver, opPackageName); - } else { - scheduleSetFeatureHidl(sensorId, token, userId, feature, enabled, hardwareAuthToken, - receiver, opPackageName); - } - }); - } - - private void scheduleSetFeatureHidl(int sensorId, @NonNull IBinder token, int userId, - int feature, boolean enabled, @NonNull byte[] hardwareAuthToken, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName) { - final List<Face> faces = getEnrolledFaces(sensorId, userId); - if (faces.isEmpty()) { - Slog.w(TAG, "Ignoring setFeature, no templates enrolled for user: " + userId); - return; - } - final int faceId = faces.get(0).getBiometricId(); - final FaceSetFeatureClient client = new FaceSetFeatureClient(mContext, mLazyDaemon, - token, new ClientMonitorCallbackConverter(receiver), userId, opPackageName, - mSensorId, BiometricLogger.ofUnknown(mContext), mBiometricContext, feature, - enabled, hardwareAuthToken, faceId); - mScheduler.scheduleClientMonitor(client); - } - - private void scheduleSetFeatureAidl(int sensorId, @NonNull IBinder token, int userId, - int feature, boolean enabled, @NonNull byte[] hardwareAuthToken, - @NonNull IFaceServiceReceiver receiver, @NonNull String opPackageName) { - final com.android.server.biometrics.sensors.face.aidl.FaceSetFeatureClient client = - new com.android.server.biometrics.sensors.face.aidl.FaceSetFeatureClient( - mContext, this::getSession, token, - new ClientMonitorCallbackConverter(receiver), userId, opPackageName, - mSensorId, BiometricLogger.ofUnknown(mContext), mBiometricContext, - feature, enabled, hardwareAuthToken); - mScheduler.scheduleClientMonitor(client); - } - - - @Override - public void scheduleGetFeature(int sensorId, @NonNull IBinder token, int userId, int feature, - @Nullable ClientMonitorCallbackConverter listener, @NonNull String opPackageName) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - - if (Flags.deHidl()) { - scheduleGetFeatureAidl(token, userId, feature, listener, - opPackageName); - } else { - scheduleGetFeatureHidl(sensorId, token, userId, feature, listener, - opPackageName); - } - }); - } - - private void scheduleGetFeatureHidl(int sensorId, @NonNull IBinder token, int userId, - int feature, @Nullable ClientMonitorCallbackConverter listener, - @NonNull String opPackageName) { - final List<Face> faces = getEnrolledFaces(sensorId, userId); - if (faces.isEmpty()) { - Slog.w(TAG, "Ignoring getFeature, no templates enrolled for user: " + userId); - return; - } - - final int faceId = faces.get(0).getBiometricId(); - final FaceGetFeatureClient client = new FaceGetFeatureClient(mContext, mLazyDaemon, - token, listener, userId, opPackageName, mSensorId, - BiometricLogger.ofUnknown(mContext), mBiometricContext, feature, faceId); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - if (success - && feature == BiometricFaceConstants.FEATURE_REQUIRE_ATTENTION) { - final int settingsValue = client.getValue() ? 1 : 0; - Slog.d(TAG, - "Updating attention value for user: " + userId + " to value: " - + settingsValue); - Settings.Secure.putIntForUser(mContext.getContentResolver(), - Settings.Secure.FACE_UNLOCK_ATTENTION_REQUIRED, settingsValue, - userId); - } - } - }); - } - - private void scheduleGetFeatureAidl(@NonNull IBinder token, int userId, - int feature, @Nullable ClientMonitorCallbackConverter listener, - @NonNull String opPackageName) { - final com.android.server.biometrics.sensors.face.aidl.FaceGetFeatureClient client = - new com.android.server.biometrics.sensors.face.aidl.FaceGetFeatureClient( - mContext, this::getSession, token, listener, userId, opPackageName, - mSensorId, BiometricLogger.ofUnknown(mContext), mBiometricContext, - feature); - mScheduler.scheduleClientMonitor(client); - } - - private void scheduleInternalCleanup(int userId, - @Nullable ClientMonitorCallback callback) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - if (Flags.deHidl()) { - scheduleInternalCleanupAidl(userId, callback); - } else { - scheduleInternalCleanupHidl(userId, callback); - } - }); - } - - private void scheduleInternalCleanupHidl(int userId, - @Nullable ClientMonitorCallback callback) { - final FaceInternalCleanupClient client = new FaceInternalCleanupClient(mContext, - mLazyDaemon, userId, mContext.getOpPackageName(), mSensorId, - createLogger(BiometricsProtoEnums.ACTION_ENUMERATE, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, FaceUtils.getLegacyInstance(mSensorId), - mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, - new ClientMonitorCompositeCallback(callback, mBiometricStateCallback)); - } - - private void scheduleInternalCleanupAidl(int userId, - @Nullable ClientMonitorCallback callback) { - final com.android.server.biometrics.sensors.face.aidl.FaceInternalCleanupClient - client = - new com.android.server.biometrics.sensors.face.aidl.FaceInternalCleanupClient( - mContext, this::getSession, userId, mContext.getOpPackageName(), - mSensorId, createLogger(BiometricsProtoEnums.ACTION_ENUMERATE, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, FaceUtils.getLegacyInstance(mSensorId), - mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, - new ClientMonitorCompositeCallback(callback, mBiometricStateCallback)); - } - - @Override - public void scheduleInternalCleanup(int sensorId, int userId, - @Nullable ClientMonitorCallback callback) { - scheduleInternalCleanup(userId, mBiometricStateCallback); - } - - @Override - public void scheduleInternalCleanup(int sensorId, int userId, - @Nullable ClientMonitorCallback callback, boolean favorHalEnrollments) { - scheduleInternalCleanup(userId, callback); - } - - @Override - public void startPreparedClient(int sensorId, int cookie) { - mHandler.post(() -> { - mScheduler.startPreparedClient(cookie); - }); - } - - @Override - public void dumpProtoState(int sensorId, ProtoOutputStream proto, - boolean clearSchedulerBuffer) { - final long sensorToken = proto.start(SensorServiceStateProto.SENSOR_STATES); - - proto.write(SensorStateProto.SENSOR_ID, mSensorProperties.sensorId); - proto.write(SensorStateProto.MODALITY, SensorStateProto.FACE); - proto.write(SensorStateProto.CURRENT_STRENGTH, - Utils.getCurrentStrength(mSensorProperties.sensorId)); - proto.write(SensorStateProto.SCHEDULER, mScheduler.dumpProtoState(clearSchedulerBuffer)); - - for (UserInfo user : UserManager.get(mContext).getUsers()) { - final int userId = user.getUserHandle().getIdentifier(); - - final long userToken = proto.start(SensorStateProto.USER_STATES); - proto.write(UserStateProto.USER_ID, userId); - proto.write(UserStateProto.NUM_ENROLLED, FaceUtils.getLegacyInstance(mSensorId) - .getBiometricsForUser(mContext, userId).size()); - proto.end(userToken); - } - - proto.write(SensorStateProto.RESET_LOCKOUT_REQUIRES_HARDWARE_AUTH_TOKEN, - mSensorProperties.resetLockoutRequiresHardwareAuthToken); - proto.write(SensorStateProto.RESET_LOCKOUT_REQUIRES_CHALLENGE, - mSensorProperties.resetLockoutRequiresChallenge); - - proto.end(sensorToken); - } - - @Override - public void dumpProtoMetrics(int sensorId, FileDescriptor fd) { - } - - @Override - public void dumpInternal(int sensorId, PrintWriter pw) { - PerformanceTracker performanceTracker = - PerformanceTracker.getInstanceForSensorId(mSensorId); - - JSONObject dump = new JSONObject(); - try { - dump.put("service", TAG); - - JSONArray sets = new JSONArray(); - for (UserInfo user : UserManager.get(mContext).getUsers()) { - final int userId = user.getUserHandle().getIdentifier(); - final int c = FaceUtils.getLegacyInstance(mSensorId) - .getBiometricsForUser(mContext, userId).size(); - JSONObject set = new JSONObject(); - set.put("id", userId); - set.put("count", c); - set.put("accept", performanceTracker.getAcceptForUser(userId)); - set.put("reject", performanceTracker.getRejectForUser(userId)); - set.put("acquire", performanceTracker.getAcquireForUser(userId)); - set.put("lockout", performanceTracker.getTimedLockoutForUser(userId)); - set.put("permanentLockout", performanceTracker.getPermanentLockoutForUser(userId)); - // cryptoStats measures statistics about secure face transactions - // (e.g. to unlock password storage, make secure purchases, etc.) - set.put("acceptCrypto", performanceTracker.getAcceptCryptoForUser(userId)); - set.put("rejectCrypto", performanceTracker.getRejectCryptoForUser(userId)); - set.put("acquireCrypto", performanceTracker.getAcquireCryptoForUser(userId)); - sets.put(set); - } - - dump.put("prints", sets); - } catch (JSONException e) { - Slog.e(TAG, "dump formatting failure", e); - } - pw.println(dump); - pw.println("HAL deaths since last reboot: " + performanceTracker.getHALDeathCount()); - - mScheduler.dump(pw); - mUsageStats.print(pw); - } - - private void scheduleLoadAuthenticatorIds() { - // Note that this can be performed on the scheduler (as opposed to being done immediately - // when the HAL is (re)loaded, since - // 1) If this is truly the first time it's being performed (e.g. system has just started), - // this will be run very early and way before any applications need to generate keys. - // 2) If this is being performed to refresh the authenticatorIds (e.g. HAL crashed and has - // just been reloaded), the framework already has a cache of the authenticatorIds. This - // is safe because authenticatorIds only change when A) new template has been enrolled, - // or B) all templates are removed. - mHandler.post(() -> { - for (UserInfo user : UserManager.get(mContext).getAliveUsers()) { - final int targetUserId = user.id; - if (!mAuthenticatorIds.containsKey(targetUserId)) { - scheduleUpdateActiveUserWithoutHandler(targetUserId); - } - } - }); - } - - /** - * Schedules the {@link FaceUpdateActiveUserClient} without posting the work onto the handler. - * Many/most APIs are user-specific. However, the HAL requires explicit "setActiveUser" - * invocation prior to authenticate/enroll/etc. Thus, internally we usually want to schedule - * this operation on the same lambda/runnable as those operations so that the ordering is - * correct. - */ - private void scheduleUpdateActiveUserWithoutHandler(int targetUserId) { - final boolean hasEnrolled = !getEnrolledFaces(mSensorId, targetUserId).isEmpty(); - final FaceUpdateActiveUserClient client = new FaceUpdateActiveUserClient(mContext, - mLazyDaemon, targetUserId, mContext.getOpPackageName(), mSensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, hasEnrolled, mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - if (success) { - if (mCurrentUserId != targetUserId) { - // Create new session with updated user ID - mSession = null; - } - mCurrentUserId = targetUserId; - } else { - Slog.w(TAG, "Failed to change user, still: " + mCurrentUserId); - } - } - }); - } - - private BiometricLogger createLogger(int statsAction, int statsClient, - AuthenticationStatsCollector authenticationStatsCollector) { - return new BiometricLogger(mContext, BiometricsProtoEnums.MODALITY_FACE, - statsAction, statsClient, authenticationStatsCollector); - } - - /** - * Sends a debug message to the HAL with the provided FileDescriptor and arguments. - */ - public void dumpHal(int sensorId, @NonNull FileDescriptor fd, @NonNull String[] args) { - // WARNING: CDD restricts image data from leaving TEE unencrypted on - // production devices: - // [C-1-10] MUST not allow unencrypted access to identifiable biometric - // data or any data derived from it (such as embeddings) to the - // Application Processor outside the context of the TEE. - // As such, this API should only be enabled for testing purposes on - // engineering and userdebug builds. All modules in the software stack - // MUST enforce final build products do NOT have this functionality. - // Additionally, the following check MUST NOT be removed. - if (!(Build.IS_ENG || Build.IS_USERDEBUG)) { - return; - } - - // Additionally, this flag allows turning off face for a device - // (either permanently through the build or on an individual device). - if (SystemProperties.getBoolean("ro.face.disable_debug_data", false) - || SystemProperties.getBoolean("persist.face.disable_debug_data", false)) { - return; - } - - // The debug method takes two file descriptors. The first is for text - // output, which we will drop. The second is for binary data, which - // will be the protobuf data. - final IBiometricsFace daemon = getDaemon(); - if (daemon != null) { - FileOutputStream devnull = null; - try { - devnull = new FileOutputStream("/dev/null"); - final NativeHandle handle = new NativeHandle( - new FileDescriptor[]{devnull.getFD(), fd}, - new int[0], false); - daemon.debug(handle, new ArrayList<String>(Arrays.asList(args))); - } catch (IOException | RemoteException ex) { - Slog.d(TAG, "error while reading face debugging data", ex); - } finally { - if (devnull != null) { - try { - devnull.close(); - } catch (IOException ex) { - } - } - } - } - } - - void setTestHalEnabled(boolean enabled) { - mTestHalEnabled = enabled; - } - - @NonNull - @Override - public ITestSession createTestSession(int sensorId, @NonNull ITestSessionCallback callback, - @NonNull String opPackageName) { - return new BiometricTestSessionImpl(mContext, mSensorId, callback, - this, mHalResultController); - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceAuthenticationClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceAuthenticationClient.java deleted file mode 100644 index e44b26399549..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceAuthenticationClient.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import static android.adaptiveauth.Flags.reportBiometricAuthAttempts; - -import android.annotation.NonNull; -import android.content.Context; -import android.content.res.Resources; -import android.hardware.SensorPrivacyManager; -import android.hardware.biometrics.BiometricAuthenticator; -import android.hardware.biometrics.BiometricConstants; -import android.hardware.biometrics.BiometricFaceConstants; -import android.hardware.biometrics.BiometricManager.Authenticators; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.face.FaceAuthenticateOptions; -import android.hardware.face.FaceManager; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.internal.R; -import com.android.server.biometrics.Utils; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.AuthenticationClient; -import com.android.server.biometrics.sensors.AuthenticationStateListeners; -import com.android.server.biometrics.sensors.BiometricNotificationUtils; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.ClientMonitorCompositeCallback; -import com.android.server.biometrics.sensors.LockoutTracker; -import com.android.server.biometrics.sensors.PerformanceTracker; -import com.android.server.biometrics.sensors.face.UsageStats; - -import java.util.ArrayList; -import java.util.function.Supplier; - -/** - * Face-specific authentication client supporting the {@link android.hardware.biometrics.face.V1_0} - * HIDL interface. - */ -class FaceAuthenticationClient - extends AuthenticationClient<IBiometricsFace, FaceAuthenticateOptions> { - - private static final String TAG = "FaceAuthenticationClient"; - - private final UsageStats mUsageStats; - - private final int[] mBiometricPromptIgnoreList; - private final int[] mBiometricPromptIgnoreListVendor; - private final int[] mKeyguardIgnoreList; - private final int[] mKeyguardIgnoreListVendor; - - private int mLastAcquire; - private SensorPrivacyManager mSensorPrivacyManager; - @NonNull - private final AuthenticationStateListeners mAuthenticationStateListeners; - - FaceAuthenticationClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFace> lazyDaemon, - @NonNull IBinder token, long requestId, - @NonNull ClientMonitorCallbackConverter listener, long operationId, - boolean restricted, @NonNull FaceAuthenticateOptions options, int cookie, - boolean requireConfirmation, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - boolean isStrongBiometric, @NonNull LockoutTracker lockoutTracker, - @NonNull UsageStats usageStats, boolean allowBackgroundAuthentication, - @Authenticators.Types int sensorStrength, - @NonNull AuthenticationStateListeners authenticationStateListeners) { - super(context, lazyDaemon, token, listener, operationId, restricted, - options, cookie, requireConfirmation, logger, biometricContext, - isStrongBiometric, null /* taskStackListener */, - lockoutTracker, allowBackgroundAuthentication, false /* shouldVibrate */, - sensorStrength); - setRequestId(requestId); - mUsageStats = usageStats; - mSensorPrivacyManager = context.getSystemService(SensorPrivacyManager.class); - mAuthenticationStateListeners = authenticationStateListeners; - - final Resources resources = getContext().getResources(); - mBiometricPromptIgnoreList = resources.getIntArray( - R.array.config_face_acquire_biometricprompt_ignorelist); - mBiometricPromptIgnoreListVendor = resources.getIntArray( - R.array.config_face_acquire_vendor_biometricprompt_ignorelist); - mKeyguardIgnoreList = resources.getIntArray( - R.array.config_face_acquire_keyguard_ignorelist); - mKeyguardIgnoreListVendor = resources.getIntArray( - R.array.config_face_acquire_vendor_keyguard_ignorelist); - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - mState = STATE_STARTED; - } - - @NonNull - @Override - protected ClientMonitorCallback wrapCallbackForStart(@NonNull ClientMonitorCallback callback) { - return new ClientMonitorCompositeCallback( - getLogger().getAmbientLightProbe(true /* startWithClient */), callback); - } - - @Override - protected void startHalOperation() { - - if (mSensorPrivacyManager != null - && mSensorPrivacyManager - .isSensorPrivacyEnabled(SensorPrivacyManager.TOGGLE_TYPE_SOFTWARE, - SensorPrivacyManager.Sensors.CAMERA)) { - onError(BiometricFaceConstants.FACE_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - return; - } - - try { - getFreshDaemon().authenticate(mOperationId); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting auth", e); - onError(BiometricFaceConstants.FACE_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - protected void stopHalOperation() { - try { - getFreshDaemon().cancel(); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting cancel", e); - onError(BiometricFaceConstants.FACE_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - public boolean wasUserDetected() { - // Do not provide haptic feedback if the user was not detected, and an error (usually - // ERROR_TIMEOUT) is received. - return mLastAcquire != FaceManager.FACE_ACQUIRED_NOT_DETECTED - && mLastAcquire != FaceManager.FACE_ACQUIRED_SENSOR_DIRTY; - } - - @Override - protected void handleLifecycleAfterAuth(boolean authenticated) { - // For face, the authentication lifecycle ends either when - // 1) Authenticated == true - // 2) Error occurred - // 3) Authenticated == false - mCallback.onClientFinished(this, true /* success */); - } - - @Override - public @LockoutTracker.LockoutMode int handleFailedAttempt(int userId) { - @LockoutTracker.LockoutMode final int lockoutMode = - getLockoutTracker().getLockoutModeForUser(userId); - final PerformanceTracker performanceTracker = - PerformanceTracker.getInstanceForSensorId(getSensorId()); - if (lockoutMode == LockoutTracker.LOCKOUT_PERMANENT) { - performanceTracker.incrementPermanentLockoutForUser(userId); - } else if (lockoutMode == LockoutTracker.LOCKOUT_TIMED) { - performanceTracker.incrementTimedLockoutForUser(userId); - } - - return lockoutMode; - } - - @Override - public void onAuthenticated(BiometricAuthenticator.Identifier identifier, - boolean authenticated, ArrayList<Byte> token) { - super.onAuthenticated(identifier, authenticated, token); - - mState = STATE_STOPPED; - mUsageStats.addEvent(new UsageStats.AuthenticationEvent( - getStartTimeMs(), - System.currentTimeMillis() - getStartTimeMs() /* latency */, - authenticated, - 0 /* error */, - 0 /* vendorError */, - getTargetUserId())); - - if (reportBiometricAuthAttempts()) { - if (authenticated) { - mAuthenticationStateListeners.onAuthenticationSucceeded(getRequestReason(), - getTargetUserId()); - } else { - mAuthenticationStateListeners.onAuthenticationFailed(getRequestReason(), - getTargetUserId()); - } - } - } - - @Override - public void onError(@BiometricConstants.Errors int error, int vendorCode) { - mUsageStats.addEvent(new UsageStats.AuthenticationEvent( - getStartTimeMs(), - System.currentTimeMillis() - getStartTimeMs() /* latency */, - false /* authenticated */, - error, - vendorCode, - getTargetUserId())); - - super.onError(error, vendorCode); - } - - private int[] getAcquireIgnorelist() { - return isBiometricPrompt() ? mBiometricPromptIgnoreList : mKeyguardIgnoreList; - } - - private int[] getAcquireVendorIgnorelist() { - return isBiometricPrompt() ? mBiometricPromptIgnoreListVendor : mKeyguardIgnoreListVendor; - } - - private boolean shouldSend(int acquireInfo, int vendorCode) { - if (acquireInfo == FaceManager.FACE_ACQUIRED_VENDOR) { - return !Utils.listContains(getAcquireVendorIgnorelist(), vendorCode); - } else { - return !Utils.listContains(getAcquireIgnorelist(), acquireInfo); - } - } - - @Override - public void onAcquired(int acquireInfo, int vendorCode) { - mLastAcquire = acquireInfo; - - if (acquireInfo == FaceManager.FACE_ACQUIRED_RECALIBRATE) { - BiometricNotificationUtils.showReEnrollmentNotification(getContext()); - } - @LockoutTracker.LockoutMode final int lockoutMode = - getLockoutTracker().getLockoutModeForUser(getTargetUserId()); - if (lockoutMode == LockoutTracker.LOCKOUT_NONE) { - PerformanceTracker pt = PerformanceTracker.getInstanceForSensorId(getSensorId()); - pt.incrementAcquireForUser(getTargetUserId(), isCryptoOperation()); - } - - final boolean shouldSend = shouldSend(acquireInfo, vendorCode); - onAcquiredInternal(acquireInfo, vendorCode, shouldSend); - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceEnrollClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceEnrollClient.java deleted file mode 100644 index 815cf9180130..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceEnrollClient.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.content.Context; -import android.hardware.biometrics.BiometricFaceConstants; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.biometrics.face.V1_0.Status; -import android.hardware.face.Face; -import android.hardware.face.FaceEnrollOptions; -import android.hardware.face.FaceManager; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; -import android.view.Surface; - -import com.android.internal.R; -import com.android.server.biometrics.Utils; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.BiometricNotificationUtils; -import com.android.server.biometrics.sensors.BiometricUtils; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.ClientMonitorCompositeCallback; -import com.android.server.biometrics.sensors.EnrollClient; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.function.Supplier; - -/** - * Face-specific enroll client supporting the {@link android.hardware.biometrics.face.V1_0} HIDL - * interface. - */ -public class FaceEnrollClient extends EnrollClient<IBiometricsFace> { - - private static final String TAG = "FaceEnrollClient"; - - @NonNull private final int[] mDisabledFeatures; - @NonNull private final int[] mEnrollIgnoreList; - @NonNull private final int[] mEnrollIgnoreListVendor; - - FaceEnrollClient(@NonNull Context context, @NonNull Supplier<IBiometricsFace> lazyDaemon, - @NonNull IBinder token, @NonNull ClientMonitorCallbackConverter listener, int userId, - @NonNull byte[] hardwareAuthToken, @NonNull String owner, long requestId, - @NonNull BiometricUtils<Face> utils, @NonNull int[] disabledFeatures, int timeoutSec, - @Nullable Surface previewSurface, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - @NonNull FaceEnrollOptions options) { - super(context, lazyDaemon, token, listener, userId, hardwareAuthToken, owner, utils, - timeoutSec, sensorId, false /* shouldVibrate */, logger, biometricContext, - BiometricFaceConstants.reasonToMetric(options.getEnrollReason())); - setRequestId(requestId); - mDisabledFeatures = Arrays.copyOf(disabledFeatures, disabledFeatures.length); - mEnrollIgnoreList = getContext().getResources() - .getIntArray(R.array.config_face_acquire_enroll_ignorelist); - mEnrollIgnoreListVendor = getContext().getResources() - .getIntArray(R.array.config_face_acquire_vendor_enroll_ignorelist); - - Slog.w(TAG, "EnrollOptions " - + FaceEnrollOptions.enrollReasonToString(options.getEnrollReason())); - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - - BiometricNotificationUtils.cancelFaceEnrollNotification(getContext()); - BiometricNotificationUtils.cancelFaceReEnrollNotification(getContext()); - } - - @NonNull - @Override - protected ClientMonitorCallback wrapCallbackForStart(@NonNull ClientMonitorCallback callback) { - return new ClientMonitorCompositeCallback( - getLogger().getAmbientLightProbe(true /* startWithClient */), callback); - } - - @Override - protected boolean hasReachedEnrollmentLimit() { - final int limit = getContext().getResources().getInteger( - com.android.internal.R.integer.config_faceMaxTemplatesPerUser); - final int enrolled = mBiometricUtils.getBiometricsForUser(getContext(), getTargetUserId()) - .size(); - if (enrolled >= limit) { - Slog.w(TAG, "Too many faces registered, user: " + getTargetUserId()); - return true; - } - return false; - } - - @Override - public void onAcquired(int acquireInfo, int vendorCode) { - final boolean shouldSend; - if (acquireInfo == FaceManager.FACE_ACQUIRED_VENDOR) { - shouldSend = !Utils.listContains(mEnrollIgnoreListVendor, vendorCode); - } else { - shouldSend = !Utils.listContains(mEnrollIgnoreList, acquireInfo); - } - onAcquiredInternal(acquireInfo, vendorCode, shouldSend); - } - - @Override - protected void startHalOperation() { - final ArrayList<Byte> token = new ArrayList<>(); - for (byte b : mHardwareAuthToken) { - token.add(b); - } - final ArrayList<Integer> disabledFeatures = new ArrayList<>(); - for (int disabledFeature : mDisabledFeatures) { - disabledFeatures.add(disabledFeature); - } - - try { - final int status = getFreshDaemon().enroll(token, mTimeoutSec, disabledFeatures); - - if (status != Status.OK) { - onError(BiometricFaceConstants.FACE_ERROR_UNABLE_TO_PROCESS, 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - } - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting enroll", e); - onError(BiometricFaceConstants.FACE_ERROR_UNABLE_TO_PROCESS, 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - protected void stopHalOperation() { - try { - getFreshDaemon().cancel(); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting cancel", e); - onError(BiometricFaceConstants.FACE_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceGenerateChallengeClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceGenerateChallengeClient.java deleted file mode 100644 index 97838a70cbd1..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceGenerateChallengeClient.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.face.IFaceServiceReceiver; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.internal.util.Preconditions; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.GenerateChallengeClient; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -/** - * Face-specific generateChallenge client supporting the - * {@link android.hardware.biometrics.face.V1_0} HIDL interface. - */ -public class FaceGenerateChallengeClient extends GenerateChallengeClient<IBiometricsFace> { - - private static final String TAG = "FaceGenerateChallengeClient"; - static final int CHALLENGE_TIMEOUT_SEC = 600; // 10 minutes - private static final ClientMonitorCallback EMPTY_CALLBACK = new ClientMonitorCallback() { - }; - - private final long mCreatedAt; - private List<IFaceServiceReceiver> mWaiting; - private Long mChallengeResult; - - FaceGenerateChallengeClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFace> lazyDaemon, @NonNull IBinder token, - @NonNull ClientMonitorCallbackConverter listener, int userId, @NonNull String owner, - int sensorId, @NonNull BiometricLogger logger, - @NonNull BiometricContext biometricContext, long now) { - super(context, lazyDaemon, token, listener, userId, owner, sensorId, logger, - biometricContext); - mCreatedAt = now; - mWaiting = new ArrayList<>(); - } - - @Override - protected void startHalOperation() { - mChallengeResult = null; - try { - mChallengeResult = getFreshDaemon().generateChallenge(CHALLENGE_TIMEOUT_SEC).value; - // send the result to the original caller via mCallback and any waiting callers - // that called reuseResult - sendChallengeResult(getListener(), mCallback); - for (IFaceServiceReceiver receiver : mWaiting) { - sendChallengeResult(new ClientMonitorCallbackConverter(receiver), EMPTY_CALLBACK); - } - } catch (RemoteException e) { - Slog.e(TAG, "generateChallenge failed", e); - mCallback.onClientFinished(this, false /* success */); - } finally { - mWaiting = null; - } - } - - /** @return An arbitrary time value for caching provided to the constructor. */ - public long getCreatedAt() { - return mCreatedAt; - } - - /** - * Reuse the result of this operation when it is available. The receiver will be notified - * immediately if a challenge has already been generated. - * - * @param receiver receiver to be notified of challenge result - */ - public void reuseResult(@NonNull IFaceServiceReceiver receiver) { - if (mWaiting != null) { - mWaiting.add(receiver); - } else { - sendChallengeResult(new ClientMonitorCallbackConverter(receiver), EMPTY_CALLBACK); - } - } - - private void sendChallengeResult(@NonNull ClientMonitorCallbackConverter receiver, - @NonNull ClientMonitorCallback ownerCallback) { - Preconditions.checkState(mChallengeResult != null, "result not available"); - try { - receiver.onChallengeGenerated(getSensorId(), getTargetUserId(), mChallengeResult); - ownerCallback.onClientFinished(this, true /* success */); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception", e); - ownerCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceGetFeatureClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceGetFeatureClient.java deleted file mode 100644 index 47aaeec81978..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceGetFeatureClient.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.biometrics.face.V1_0.OptionalBool; -import android.hardware.biometrics.face.V1_0.Status; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.HalClientMonitor; - -import java.util.function.Supplier; - -/** - * Face-specific getFeature client supporting the {@link android.hardware.biometrics.face.V1_0} - * HIDL interface. - */ -public class FaceGetFeatureClient extends HalClientMonitor<IBiometricsFace> { - - private static final String TAG = "FaceGetFeatureClient"; - - private final int mFeature; - private final int mFaceId; - private boolean mValue; - - FaceGetFeatureClient(@NonNull Context context, @NonNull Supplier<IBiometricsFace> lazyDaemon, - @NonNull IBinder token, @Nullable ClientMonitorCallbackConverter listener, int userId, - @NonNull String owner, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - int feature, int faceId) { - super(context, lazyDaemon, token, listener, userId, owner, 0 /* cookie */, sensorId, - logger, biometricContext); - mFeature = feature; - mFaceId = faceId; - } - - @Override - public void unableToStart() { - try { - getListener().onFeatureGet(false /* success */, new int[0], new boolean[0]); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to send error", e); - } - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - startHalOperation(); - } - - @Override - protected void startHalOperation() { - try { - final OptionalBool result = getFreshDaemon().getFeature(mFeature, mFaceId); - int[] features = new int[1]; - boolean[] featureState = new boolean[1]; - features[0] = mFeature; - featureState[0] = result.value; - mValue = result.value; - - getListener().onFeatureGet(result.status == Status.OK, features, featureState); - mCallback.onClientFinished(this, true /* success */); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to getFeature", e); - mCallback.onClientFinished(this, false /* success */); - } - } - - boolean getValue() { - return mValue; - } - - @Override - public int getProtoEnum() { - return BiometricsProto.CM_GET_FEATURE; - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceInternalCleanupClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceInternalCleanupClient.java deleted file mode 100644 index 89a17c6b570e..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceInternalCleanupClient.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.face.Face; -import android.os.IBinder; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.BiometricUtils; -import com.android.server.biometrics.sensors.InternalCleanupClient; -import com.android.server.biometrics.sensors.InternalEnumerateClient; -import com.android.server.biometrics.sensors.RemovalClient; - -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -/** - * Face-specific internal cleanup client supporting the - * {@link android.hardware.biometrics.face.V1_0} HIDL interface. - */ -class FaceInternalCleanupClient extends InternalCleanupClient<Face, IBiometricsFace> { - - FaceInternalCleanupClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFace> lazyDaemon, int userId, @NonNull String owner, - int sensorId, @NonNull BiometricLogger logger, - @NonNull BiometricContext biometricContext, - @NonNull BiometricUtils<Face> utils, @NonNull Map<Integer, Long> authenticatorIds) { - super(context, lazyDaemon, userId, owner, sensorId, logger, biometricContext, - utils, authenticatorIds); - } - - @Override - protected InternalEnumerateClient<IBiometricsFace> getEnumerateClient(Context context, - Supplier<IBiometricsFace> lazyDaemon, IBinder token, int userId, String owner, - List<Face> enrolledList, BiometricUtils<Face> utils, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext) { - return new FaceInternalEnumerateClient(context, lazyDaemon, token, userId, owner, - enrolledList, utils, sensorId, logger, biometricContext); - } - - @Override - protected RemovalClient<Face, IBiometricsFace> getRemovalClient(Context context, - Supplier<IBiometricsFace> lazyDaemon, IBinder token, - int biometricId, int userId, String owner, BiometricUtils<Face> utils, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - Map<Integer, Long> authenticatorIds) { - // Internal remove does not need to send results to anyone. Cleanup (enumerate + remove) - // is all done internally. - return new FaceRemovalClient(context, lazyDaemon, token, - null /* ClientMonitorCallbackConverter */, biometricId, userId, owner, utils, - sensorId, logger, biometricContext, authenticatorIds); - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceInternalEnumerateClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceInternalEnumerateClient.java deleted file mode 100644 index 250dd7e0cdef..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceInternalEnumerateClient.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.face.Face; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.BiometricUtils; -import com.android.server.biometrics.sensors.InternalEnumerateClient; - -import java.util.List; -import java.util.function.Supplier; - -/** - * Face-specific internal enumerate client supporting the - * {@link android.hardware.biometrics.face.V1_0} HIDL interface. - */ -class FaceInternalEnumerateClient extends InternalEnumerateClient<IBiometricsFace> { - private static final String TAG = "FaceInternalEnumerateClient"; - - FaceInternalEnumerateClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFace> lazyDaemon, @NonNull IBinder token, int userId, - @NonNull String owner, @NonNull List<Face> enrolledList, - @NonNull BiometricUtils<Face> utils, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext) { - super(context, lazyDaemon, token, userId, owner, enrolledList, utils, sensorId, - logger, biometricContext); - } - - @Override - protected void startHalOperation() { - try { - getFreshDaemon().enumerate(); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting enumerate", e); - mCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceRemovalClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceRemovalClient.java deleted file mode 100644 index 0ee7a354d5a4..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceRemovalClient.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.face.Face; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.BiometricUtils; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.RemovalClient; - -import java.util.Map; -import java.util.function.Supplier; - -/** - * Face-specific removal client supporting the {@link android.hardware.biometrics.face.V1_0} - * HIDL interface. - */ -class FaceRemovalClient extends RemovalClient<Face, IBiometricsFace> { - private static final String TAG = "FaceRemovalClient"; - - private final int mBiometricId; - - FaceRemovalClient(@NonNull Context context, @NonNull Supplier<IBiometricsFace> lazyDaemon, - @NonNull IBinder token, @NonNull ClientMonitorCallbackConverter listener, - int biometricId, int userId, @NonNull String owner, @NonNull BiometricUtils<Face> utils, - int sensorId, @NonNull BiometricLogger logger, - @NonNull BiometricContext biometricContext, - @NonNull Map<Integer, Long> authenticatorIds) { - super(context, lazyDaemon, token, listener, userId, owner, utils, sensorId, logger, - biometricContext, authenticatorIds); - mBiometricId = biometricId; - } - - @Override - protected void startHalOperation() { - try { - getFreshDaemon().remove(mBiometricId); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting remove", e); - mCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceResetLockoutClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceResetLockoutClient.java deleted file mode 100644 index f29b9e823109..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceResetLockoutClient.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.HalClientMonitor; - -import java.util.ArrayList; -import java.util.function.Supplier; - -/** - * Face-specific resetLockout client supporting the {@link android.hardware.biometrics.face.V1_0} - * HIDL interface. - */ -public class FaceResetLockoutClient extends HalClientMonitor<IBiometricsFace> { - - private static final String TAG = "FaceResetLockoutClient"; - - private final ArrayList<Byte> mHardwareAuthToken; - - FaceResetLockoutClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFace> lazyDaemon, int userId, String owner, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - @NonNull byte[] hardwareAuthToken) { - super(context, lazyDaemon, null /* token */, null /* listener */, userId, owner, - 0 /* cookie */, sensorId, logger, biometricContext); - - mHardwareAuthToken = new ArrayList<>(); - for (byte b : hardwareAuthToken) { - mHardwareAuthToken.add(b); - } - } - - @Override - public void unableToStart() { - // Nothing to do here - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - startHalOperation(); - } - - public boolean interruptsPrecedingClients() { - return true; - } - - @Override - protected void startHalOperation() { - try { - getFreshDaemon().resetLockout(mHardwareAuthToken); - mCallback.onClientFinished(this, true /* success */); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to reset lockout", e); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - public int getProtoEnum() { - return BiometricsProto.CM_RESET_LOCKOUT; - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceRevokeChallengeClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceRevokeChallengeClient.java deleted file mode 100644 index b7b0dc046633..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceRevokeChallengeClient.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.RevokeChallengeClient; - -import java.util.function.Supplier; - -/** - * Face-specific revokeChallenge client supporting the {@link android.hardware.biometrics.face.V1_0} - * HIDL interface. - */ -public class FaceRevokeChallengeClient extends RevokeChallengeClient<IBiometricsFace> { - - private static final String TAG = "FaceRevokeChallengeClient"; - - FaceRevokeChallengeClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFace> lazyDaemon, @NonNull IBinder token, - int userId, @NonNull String owner, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext) { - super(context, lazyDaemon, token, userId, owner, sensorId, logger, biometricContext); - } - - @Override - protected void startHalOperation() { - try { - getFreshDaemon().revokeChallenge(); - mCallback.onClientFinished(this, true /* success */); - } catch (RemoteException e) { - Slog.e(TAG, "revokeChallenge failed", e); - mCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceSetFeatureClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceSetFeatureClient.java deleted file mode 100644 index 3c82f9c73700..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceSetFeatureClient.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.biometrics.face.V1_0.Status; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.HalClientMonitor; - -import java.util.ArrayList; -import java.util.function.Supplier; - -/** - * Face-specific setFeature client supporting the {@link android.hardware.biometrics.face.V1_0} - * HIDL interface. - */ -public class FaceSetFeatureClient extends HalClientMonitor<IBiometricsFace> { - - private static final String TAG = "FaceSetFeatureClient"; - - private final int mFeature; - private final boolean mEnabled; - private final ArrayList<Byte> mHardwareAuthToken; - private final int mFaceId; - - FaceSetFeatureClient(@NonNull Context context, @NonNull Supplier<IBiometricsFace> lazyDaemon, - @NonNull IBinder token, @NonNull ClientMonitorCallbackConverter listener, int userId, - @NonNull String owner, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - int feature, boolean enabled, byte[] hardwareAuthToken, int faceId) { - super(context, lazyDaemon, token, listener, userId, owner, 0 /* cookie */, sensorId, - logger, biometricContext); - mFeature = feature; - mEnabled = enabled; - mFaceId = faceId; - - mHardwareAuthToken = new ArrayList<>(); - for (byte b : hardwareAuthToken) { - mHardwareAuthToken.add(b); - } - } - - @Override - public void unableToStart() { - try { - getListener().onFeatureSet(false /* success */, mFeature); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to send error", e); - } - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - - startHalOperation(); - } - - @Override - protected void startHalOperation() { - try { - final int result = getFreshDaemon() - .setFeature(mFeature, mEnabled, mHardwareAuthToken, mFaceId); - getListener().onFeatureSet(result == Status.OK, mFeature); - mCallback.onClientFinished(this, true /* success */); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to set feature: " + mFeature + " to enabled: " + mEnabled, e); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - public int getProtoEnum() { - return BiometricsProto.CM_SET_FEATURE; - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSensorAdapter.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSensorAdapter.java index a004cae4ae26..9a4c29d7e978 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSensorAdapter.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSensorAdapter.java @@ -173,9 +173,14 @@ public class HidlToAidlSensorAdapter extends Sensor implements IHwBinder.DeathRe } private AidlResponseHandler getAidlResponseHandler() { - return new AidlResponseHandler(getContext(), getScheduler(), getSensorProperties().sensorId, - mCurrentUserId, mLockoutTracker, mLockoutResetDispatcher, - mAuthSessionCoordinator, () -> {}, mAidlResponseHandlerCallback); + return new AidlResponseHandler(getContext(), + getScheduler(), + getSensorProperties().sensorId, + mCurrentUserId, + mLockoutTracker, + mLockoutResetDispatcher, + mAuthSessionCoordinator, + mAidlResponseHandlerCallback); } private IBiometricsFace getIBiometricsFace() { diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSessionAdapter.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSessionAdapter.java index fa953615a1d6..45d0cfec9fb2 100644 --- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSessionAdapter.java +++ b/services/core/java/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSessionAdapter.java @@ -53,7 +53,7 @@ public class HidlToAidlSessionAdapter implements ISession { private static final String TAG = "HidlToAidlSessionAdapter"; - private static final int CHALLENGE_TIMEOUT_SEC = 600; + @VisibleForTesting static final int CHALLENGE_TIMEOUT_SEC = 600; @DurationMillisLong private static final int GENERATE_CHALLENGE_REUSE_INTERVAL_MILLIS = 60 * 1000; @DurationMillisLong diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/FingerprintService.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/FingerprintService.java index d762914a90c7..deda93c77f8a 100644 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/FingerprintService.java +++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/FingerprintService.java @@ -72,7 +72,6 @@ import android.os.ServiceManager; import android.os.ShellCallback; import android.os.UserHandle; import android.os.UserManager; -import android.provider.Settings; import android.util.EventLog; import android.util.Pair; import android.util.Slog; @@ -83,7 +82,6 @@ import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.DumpUtils; import com.android.internal.widget.LockPatternUtils; import com.android.server.SystemService; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.Utils; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.sensors.AuthenticationStateListeners; @@ -94,12 +92,8 @@ import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; import com.android.server.biometrics.sensors.LockoutResetDispatcher; import com.android.server.biometrics.sensors.LockoutTracker; import com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintProvider; -import com.android.server.biometrics.sensors.fingerprint.hidl.Fingerprint21; -import com.android.server.biometrics.sensors.fingerprint.hidl.Fingerprint21UdfpsMock; import com.android.server.companion.virtual.VirtualDeviceManagerInternal; -import com.google.android.collect.Lists; - import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; @@ -886,9 +880,9 @@ public class FingerprintService extends SystemService { @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL) @Override // Binder call - public void registerAuthenticatorsLegacy( + public void registerAuthenticators( @NonNull FingerprintSensorConfigurations fingerprintSensorConfigurations) { - super.registerAuthenticatorsLegacy_enforcePermission(); + super.registerAuthenticators_enforcePermission(); if (!fingerprintSensorConfigurations.hasSensorConfigurations()) { Slog.d(TAG, "No fingerprint sensors available."); return; @@ -897,30 +891,6 @@ public class FingerprintService extends SystemService { } @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL) - @Override // Binder call - public void registerAuthenticators( - @NonNull List<FingerprintSensorPropertiesInternal> hidlSensors) { - super.registerAuthenticators_enforcePermission(); - - mRegistry.registerAll(() -> { - List<String> aidlSensors = new ArrayList<>(); - final String[] instances = mAidlInstanceNameSupplier.get(); - if (instances != null) { - aidlSensors.addAll(Lists.newArrayList(instances)); - } - - final Pair<List<FingerprintSensorPropertiesInternal>, List<String>> - filteredInstances = filterAvailableHalInstances(hidlSensors, aidlSensors); - - final List<ServiceProvider> providers = new ArrayList<>(); - providers.addAll(getHidlProviders(filteredInstances.first)); - providers.addAll(getAidlProviders(filteredInstances.second)); - - return providers; - }); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL) @Override public void addAuthenticatorsRegisteredCallback( IFingerprintAuthenticatorsRegisteredCallback callback) { @@ -1086,22 +1056,15 @@ public class FingerprintService extends SystemService { return null; }; - if (Flags.deHidl()) { - mFingerprintProviderFunction = fingerprintProviderFunction == null - ? (filteredSensorProps, resetLockoutRequiresHardwareAuthToken) -> - new FingerprintProvider( - getContext(), mBiometricStateCallback, - mAuthenticationStateListeners, - filteredSensorProps.second, - filteredSensorProps.first, mLockoutResetDispatcher, - mGestureAvailabilityDispatcher, - mBiometricContext, - resetLockoutRequiresHardwareAuthToken) - : fingerprintProviderFunction; - } else { - mFingerprintProviderFunction = - (filteredSensorProps, resetLockoutRequiresHardwareAuthToken) -> null; - } + mFingerprintProviderFunction = fingerprintProviderFunction != null + ? fingerprintProviderFunction : + (filteredSensorProps, resetLockoutRequiresHardwareAuthToken) -> + new FingerprintProvider(getContext(), mBiometricStateCallback, + mAuthenticationStateListeners, filteredSensorProps.second, + filteredSensorProps.first, mLockoutResetDispatcher, + mGestureAvailabilityDispatcher, mBiometricContext, + resetLockoutRequiresHardwareAuthToken); + mHandler = new Handler(Looper.getMainLooper()); mRegistry = new FingerprintServiceRegistry(mServiceWrapper, biometricServiceSupplier); mRegistry.addAllRegisteredCallback(new IFingerprintAuthenticatorsRegisteredCallback.Stub() { @@ -1160,74 +1123,6 @@ public class FingerprintService extends SystemService { .getSensorPropForInstance(finalSensorInstance)); } - private Pair<List<FingerprintSensorPropertiesInternal>, List<String>> - filterAvailableHalInstances( - @NonNull List<FingerprintSensorPropertiesInternal> hidlInstances, - @NonNull List<String> aidlInstances) { - if ((hidlInstances.size() + aidlInstances.size()) <= 1) { - return new Pair(hidlInstances, aidlInstances); - } - - final int virtualAt = aidlInstances.indexOf("virtual"); - if (Utils.isFingerprintVirtualEnabled(getContext())) { - if (virtualAt != -1) { - //only virtual instance should be returned - Slog.i(TAG, "virtual hal is used"); - return new Pair(new ArrayList<>(), List.of(aidlInstances.get(virtualAt))); - } else { - Slog.e(TAG, "Could not find virtual interface while it is enabled"); - return new Pair(hidlInstances, aidlInstances); - } - } else { - //remove virtual instance - aidlInstances = new ArrayList<>(aidlInstances); - if (virtualAt != -1) { - aidlInstances.remove(virtualAt); - } - return new Pair(hidlInstances, aidlInstances); - } - } - - @NonNull - private List<ServiceProvider> getHidlProviders( - @NonNull List<FingerprintSensorPropertiesInternal> hidlSensors) { - final List<ServiceProvider> providers = new ArrayList<>(); - - for (FingerprintSensorPropertiesInternal hidlSensor : hidlSensors) { - final Fingerprint21 fingerprint21; - if ((Build.IS_USERDEBUG || Build.IS_ENG) - && getContext().getResources().getBoolean(R.bool.allow_test_udfps) - && Settings.Secure.getIntForUser(getContext().getContentResolver(), - Fingerprint21UdfpsMock.CONFIG_ENABLE_TEST_UDFPS, 0 /* default */, - UserHandle.USER_CURRENT) != 0) { - fingerprint21 = Fingerprint21UdfpsMock.newInstance(getContext(), - mBiometricStateCallback, mAuthenticationStateListeners, - hidlSensor, mLockoutResetDispatcher, mGestureAvailabilityDispatcher, - BiometricContext.getInstance(getContext())); - } else { - fingerprint21 = Fingerprint21.newInstance(getContext(), - mBiometricStateCallback, mAuthenticationStateListeners, hidlSensor, - mHandler, mLockoutResetDispatcher, mGestureAvailabilityDispatcher); - } - providers.add(fingerprint21); - } - - return providers; - } - - @NonNull - private List<ServiceProvider> getAidlProviders(@NonNull List<String> instances) { - final List<ServiceProvider> providers = new ArrayList<>(); - - for (String instance : instances) { - final FingerprintProvider provider = mFingerprintProvider.apply(instance); - Slog.i(TAG, "Adding AIDL provider: " + instance); - providers.add(provider); - } - - return providers; - } - @Override public void onStart() { publishBinderService(Context.FINGERPRINT_SERVICE, mServiceWrapper); diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/AidlResponseHandler.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/AidlResponseHandler.java index bd21cf4002b0..6d1715f1d500 100644 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/AidlResponseHandler.java +++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/AidlResponseHandler.java @@ -25,7 +25,6 @@ import android.hardware.fingerprint.Fingerprint; import android.hardware.keymaster.HardwareAuthToken; import android.util.Slog; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.HardwareAuthTokenUtils; import com.android.server.biometrics.Utils; import com.android.server.biometrics.sensors.AcquisitionClient; @@ -53,16 +52,6 @@ public class AidlResponseHandler extends ISessionCallback.Stub { /** * Interface to send results to the AidlResponseHandler's owner. */ - public interface HardwareUnavailableCallback { - /** - * Invoked when the HAL sends ERROR_HW_UNAVAILABLE. - */ - void onHardwareUnavailable(); - } - - /** - * Interface to send results to the AidlResponseHandler's owner. - */ public interface AidlResponseHandlerCallback { /** * Invoked when enrollment is successful. @@ -90,8 +79,6 @@ public class AidlResponseHandler extends ISessionCallback.Stub { @NonNull private final AuthSessionCoordinator mAuthSessionCoordinator; @NonNull - private final HardwareUnavailableCallback mHardwareUnavailableCallback; - @NonNull private final AidlResponseHandlerCallback mAidlResponseHandlerCallback; public AidlResponseHandler(@NonNull Context context, @@ -99,24 +86,6 @@ public class AidlResponseHandler extends ISessionCallback.Stub { @NonNull LockoutTracker lockoutTracker, @NonNull LockoutResetDispatcher lockoutResetDispatcher, @NonNull AuthSessionCoordinator authSessionCoordinator, - @NonNull HardwareUnavailableCallback hardwareUnavailableCallback) { - this(context, scheduler, sensorId, userId, lockoutTracker, lockoutResetDispatcher, - authSessionCoordinator, hardwareUnavailableCallback, - new AidlResponseHandlerCallback() { - @Override - public void onEnrollSuccess() {} - - @Override - public void onHardwareUnavailable() {} - }); - } - - public AidlResponseHandler(@NonNull Context context, - @NonNull BiometricScheduler scheduler, int sensorId, int userId, - @NonNull LockoutTracker lockoutTracker, - @NonNull LockoutResetDispatcher lockoutResetDispatcher, - @NonNull AuthSessionCoordinator authSessionCoordinator, - @NonNull HardwareUnavailableCallback hardwareUnavailableCallback, @NonNull AidlResponseHandlerCallback aidlResponseHandlerCallback) { mContext = context; mScheduler = scheduler; @@ -125,7 +94,6 @@ public class AidlResponseHandler extends ISessionCallback.Stub { mLockoutTracker = lockoutTracker; mLockoutResetDispatcher = lockoutResetDispatcher; mAuthSessionCoordinator = authSessionCoordinator; - mHardwareUnavailableCallback = hardwareUnavailableCallback; mAidlResponseHandlerCallback = aidlResponseHandlerCallback; } @@ -171,11 +139,7 @@ public class AidlResponseHandler extends ISessionCallback.Stub { handleResponse(ErrorConsumer.class, (c) -> { c.onError(error, vendorCode); if (error == Error.HW_UNAVAILABLE) { - if (Flags.deHidl()) { - mAidlResponseHandlerCallback.onHardwareUnavailable(); - } else { - mHardwareUnavailableCallback.onHardwareUnavailable(); - } + mAidlResponseHandlerCallback.onHardwareUnavailable(); } }); } diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintAuthenticationClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintAuthenticationClient.java index 93d1b6e079ca..5edcbedbd52d 100644 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintAuthenticationClient.java +++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintAuthenticationClient.java @@ -31,23 +31,16 @@ import android.hardware.biometrics.BiometricFingerprintConstants.FingerprintAcqu import android.hardware.biometrics.BiometricManager.Authenticators; import android.hardware.biometrics.BiometricSourceType; import android.hardware.biometrics.common.ICancellationSignal; -import android.hardware.biometrics.common.OperationState; import android.hardware.biometrics.fingerprint.PointerContext; import android.hardware.fingerprint.FingerprintAuthenticateOptions; import android.hardware.fingerprint.FingerprintManager; import android.hardware.fingerprint.FingerprintSensorPropertiesInternal; import android.hardware.fingerprint.ISidefpsController; import android.hardware.fingerprint.IUdfpsOverlayController; -import android.os.Build; -import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; -import android.os.UserHandle; -import android.provider.Settings; import android.util.Slog; -import com.android.internal.R; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.CallbackWithProbe; @@ -67,7 +60,6 @@ import com.android.server.biometrics.sensors.SensorOverlays; import com.android.server.biometrics.sensors.fingerprint.PowerPressHandler; import com.android.server.biometrics.sensors.fingerprint.Udfps; -import java.time.Clock; import java.util.ArrayList; import java.util.function.Supplier; @@ -79,30 +71,17 @@ public class FingerprintAuthenticationClient extends AuthenticationClient<AidlSession, FingerprintAuthenticateOptions> implements Udfps, LockoutConsumer, PowerPressHandler { private static final String TAG = "FingerprintAuthenticationClient"; - private static final int MESSAGE_AUTH_SUCCESS = 2; - private static final int MESSAGE_FINGER_UP = 3; @NonNull private final SensorOverlays mSensorOverlays; @NonNull private final FingerprintSensorPropertiesInternal mSensorProps; @NonNull private final CallbackWithProbe<Probe> mALSProbeCallback; - private final Handler mHandler; - private final int mSkipWaitForPowerAcquireMessage; - private final int mSkipWaitForPowerVendorAcquireMessage; - private final long mFingerUpIgnoresPower = 500; private final AuthSessionCoordinator mAuthSessionCoordinator; @NonNull private final AuthenticationStateListeners mAuthenticationStateListeners; @Nullable private ICancellationSignal mCancellationSignal; private boolean mIsPointerDown; - private long mWaitForAuthKeyguard; - private long mWaitForAuthBp; - private long mIgnoreAuthFor; - private long mSideFpsLastAcquireStartTime; - private Runnable mAuthSuccessRunnable; - private final Clock mClock; - public FingerprintAuthenticationClient( @NonNull Context context, @@ -125,9 +104,7 @@ public class FingerprintAuthenticationClient @NonNull AuthenticationStateListeners authenticationStateListeners, boolean allowBackgroundAuthentication, @NonNull FingerprintSensorPropertiesInternal sensorProps, - @NonNull Handler handler, @Authenticators.Types int biometricStrength, - @NonNull Clock clock, @Nullable LockoutTracker lockoutTracker) { super( context, @@ -156,39 +133,7 @@ public class FingerprintAuthenticationClient mAuthenticationStateListeners = authenticationStateListeners; mSensorProps = sensorProps; mALSProbeCallback = getLogger().getAmbientLightProbe(false /* startWithClient */); - mHandler = handler; - - mWaitForAuthKeyguard = - context.getResources() - .getInteger(R.integer.config_sidefpsKeyguardPowerPressWindow); - mWaitForAuthBp = - context.getResources().getInteger(R.integer.config_sidefpsBpPowerPressWindow); - mIgnoreAuthFor = - context.getResources().getInteger(R.integer.config_sidefpsPostAuthDowntime); - - mSkipWaitForPowerAcquireMessage = - context.getResources().getInteger( - R.integer.config_sidefpsSkipWaitForPowerAcquireMessage); - mSkipWaitForPowerVendorAcquireMessage = - context.getResources().getInteger( - R.integer.config_sidefpsSkipWaitForPowerVendorAcquireMessage); mAuthSessionCoordinator = biometricContext.getAuthSessionCoordinator(); - mSideFpsLastAcquireStartTime = -1; - mClock = clock; - - if (mSensorProps.isAnySidefpsType()) { - if (Build.isDebuggable()) { - mWaitForAuthKeyguard = Settings.Secure.getIntForUser(context.getContentResolver(), - Settings.Secure.FINGERPRINT_SIDE_FPS_KG_POWER_WINDOW, - (int) mWaitForAuthKeyguard, UserHandle.USER_CURRENT); - mWaitForAuthBp = Settings.Secure.getIntForUser(context.getContentResolver(), - Settings.Secure.FINGERPRINT_SIDE_FPS_BP_POWER_WINDOW, (int) mWaitForAuthBp, - UserHandle.USER_CURRENT); - mIgnoreAuthFor = Settings.Secure.getIntForUser(context.getContentResolver(), - Settings.Secure.FINGERPRINT_SIDE_FPS_AUTH_DOWNTIME, (int) mIgnoreAuthFor, - UserHandle.USER_CURRENT); - } - } } @Override @@ -316,11 +261,7 @@ public class FingerprintAuthenticationClient } try { - if (Flags.deHidl()) { - startAuthentication(); - } else { - mCancellationSignal = doAuthenticate(); - } + doAuthenticate(); } catch (RemoteException e) { Slog.e(TAG, "Remote exception", e); onError( @@ -334,49 +275,7 @@ public class FingerprintAuthenticationClient } } - private ICancellationSignal doAuthenticate() throws RemoteException { - final AidlSession session = getFreshDaemon(); - - final OperationContextExt opContext = getOperationContext(); - final ICancellationSignal cancel; - if (session.hasContextMethods()) { - cancel = session.getSession().authenticateWithContext( - mOperationId, opContext.toAidlContext(getOptions())); - } else { - cancel = session.getSession().authenticate(mOperationId); - } - - getBiometricContext().subscribe(opContext, ctx -> { - if (session.hasContextMethods()) { - try { - session.getSession().onContextChanged(ctx); - // TODO(b/317414324): Deprecate setIgnoreDisplayTouches - if (ctx.operationState != null && ctx.operationState.getTag() - == OperationState.fingerprintOperationState) { - session.getSession().setIgnoreDisplayTouches( - ctx.operationState.getFingerprintOperationState().isHardwareIgnoringTouches); - } - } catch (RemoteException e) { - Slog.e(TAG, "Unable to notify context changed", e); - } - } - - // TODO(b/243836005): this should come via ctx - final boolean isAwake = getBiometricContext().isAwake(); - if (isAwake) { - mALSProbeCallback.getProbe().enable(); - } else { - mALSProbeCallback.getProbe().disable(); - } - }); - if (getBiometricContext().isAwake()) { - mALSProbeCallback.getProbe().enable(); - } - - return cancel; - } - - private void startAuthentication() { + private void doAuthenticate() throws RemoteException { final AidlSession session = getFreshDaemon(); final OperationContextExt opContext = getOperationContext(); diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintDetectClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintDetectClient.java index 8d2b46fe743d..1db2fad8ddf5 100644 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintDetectClient.java +++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintDetectClient.java @@ -23,7 +23,6 @@ import android.annotation.Nullable; import android.content.Context; import android.hardware.biometrics.BiometricRequestConstants; import android.hardware.biometrics.common.ICancellationSignal; -import android.hardware.biometrics.common.OperationState; import android.hardware.fingerprint.FingerprintAuthenticateOptions; import android.hardware.fingerprint.IUdfpsOverlayController; import android.os.IBinder; @@ -31,7 +30,6 @@ import android.os.RemoteException; import android.util.Slog; import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.OperationContextExt; @@ -106,13 +104,8 @@ public class FingerprintDetectClient extends AcquisitionClient<AidlSession> resetIgnoreDisplayTouches(); mSensorOverlays.show(getSensorId(), BiometricRequestConstants.REASON_AUTH_KEYGUARD, this); - try { - if (Flags.deHidl()) { - startDetectInteraction(); - } else { - mCancellationSignal = doDetectInteraction(); - } + doDetectInteraction(); } catch (RemoteException e) { Slog.e(TAG, "Remote exception when requesting finger detect", e); mSensorOverlays.hide(getSensorId()); @@ -120,33 +113,7 @@ public class FingerprintDetectClient extends AcquisitionClient<AidlSession> } } - private ICancellationSignal doDetectInteraction() throws RemoteException { - final AidlSession session = getFreshDaemon(); - - if (session.hasContextMethods()) { - final OperationContextExt opContext = getOperationContext(); - final ICancellationSignal cancel = session.getSession().detectInteractionWithContext( - opContext.toAidlContext(mOptions)); - getBiometricContext().subscribe(opContext, ctx -> { - try { - session.getSession().onContextChanged(ctx); - // TODO(b/317414324): Deprecate setIgnoreDisplayTouches - if (ctx.operationState != null && ctx.operationState.getTag() - == OperationState.fingerprintOperationState) { - session.getSession().setIgnoreDisplayTouches( - ctx.operationState.getFingerprintOperationState().isHardwareIgnoringTouches); - } - } catch (RemoteException e) { - Slog.e(TAG, "Unable to notify context changed", e); - } - }); - return cancel; - } else { - return session.getSession().detectInteraction(); - } - } - - private void startDetectInteraction() throws RemoteException { + private void doDetectInteraction() throws RemoteException { final AidlSession session = getFreshDaemon(); if (session.hasContextMethods()) { diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClient.java index a24ab1d022c6..86ebabe50abd 100644 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClient.java +++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClient.java @@ -26,7 +26,6 @@ import android.hardware.biometrics.BiometricFingerprintConstants; import android.hardware.biometrics.BiometricFingerprintConstants.FingerprintAcquired; import android.hardware.biometrics.BiometricStateListener; import android.hardware.biometrics.common.ICancellationSignal; -import android.hardware.biometrics.common.OperationState; import android.hardware.biometrics.fingerprint.PointerContext; import android.hardware.fingerprint.Fingerprint; import android.hardware.fingerprint.FingerprintEnrollOptions; @@ -40,7 +39,6 @@ import android.os.RemoteException; import android.util.Slog; import android.view.accessibility.AccessibilityManager; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.HardwareAuthTokenUtils; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; @@ -209,11 +207,7 @@ public class FingerprintEnrollClient extends EnrollClient<AidlSession> implement BiometricNotificationUtils.cancelBadCalibrationNotification(getContext()); try { - if (Flags.deHidl()) { - startEnroll(); - } else { - mCancellationSignal = doEnroll(); - } + doEnroll(); } catch (RemoteException e) { Slog.e(TAG, "Remote exception when requesting enroll", e); onError(BiometricFingerprintConstants.FINGERPRINT_ERROR_UNABLE_TO_PROCESS, @@ -222,35 +216,7 @@ public class FingerprintEnrollClient extends EnrollClient<AidlSession> implement } } - private ICancellationSignal doEnroll() throws RemoteException { - final AidlSession session = getFreshDaemon(); - final HardwareAuthToken hat = - HardwareAuthTokenUtils.toHardwareAuthToken(mHardwareAuthToken); - - if (session.hasContextMethods()) { - final OperationContextExt opContext = getOperationContext(); - final ICancellationSignal cancel = session.getSession().enrollWithContext( - hat, opContext.toAidlContext()); - getBiometricContext().subscribe(opContext, ctx -> { - try { - session.getSession().onContextChanged(ctx); - // TODO(b/317414324): Deprecate setIgnoreDisplayTouches - if (ctx.operationState != null && ctx.operationState.getTag() - == OperationState.fingerprintOperationState) { - session.getSession().setIgnoreDisplayTouches( - ctx.operationState.getFingerprintOperationState().isHardwareIgnoringTouches); - } - } catch (RemoteException e) { - Slog.e(TAG, "Unable to notify context changed", e); - } - }); - return cancel; - } else { - return session.getSession().enroll(hat); - } - } - - private void startEnroll() throws RemoteException { + private void doEnroll() throws RemoteException { final AidlSession session = getFreshDaemon(); final HardwareAuthToken hat = HardwareAuthTokenUtils.toHardwareAuthToken(mHardwareAuthToken); diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java index 9290f8a48b79..beb3f2f2bb71 100644 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java +++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java @@ -29,12 +29,10 @@ import android.content.pm.UserInfo; import android.content.res.TypedArray; import android.hardware.biometrics.BiometricAuthenticator; import android.hardware.biometrics.BiometricsProtoEnums; -import android.hardware.biometrics.ComponentInfoInternal; import android.hardware.biometrics.IInvalidationCallback; import android.hardware.biometrics.ITestSession; import android.hardware.biometrics.ITestSessionCallback; import android.hardware.biometrics.SensorLocationInternal; -import android.hardware.biometrics.common.ComponentInfo; import android.hardware.biometrics.fingerprint.IFingerprint; import android.hardware.biometrics.fingerprint.PointerContext; import android.hardware.biometrics.fingerprint.SensorProps; @@ -50,10 +48,8 @@ import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; -import android.os.Looper; import android.os.RemoteException; import android.os.ServiceManager; -import android.os.SystemClock; import android.os.UserHandle; import android.os.UserManager; import android.util.Slog; @@ -63,7 +59,6 @@ import com.android.internal.annotations.VisibleForTesting; import com.android.server.biometrics.AuthenticationStatsBroadcastReceiver; import com.android.server.biometrics.AuthenticationStatsCollector; import com.android.server.biometrics.BiometricHandlerProvider; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.Utils; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; @@ -96,10 +91,8 @@ import org.json.JSONObject; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicLong; -import java.util.stream.Collectors; /** * Provider for a single instance of the {@link IFingerprint} HAL. @@ -200,11 +193,7 @@ public class FingerprintProvider implements IBinder.DeathRecipient, ServiceProvi mAuthenticationStateListeners = authenticationStateListeners; mHalInstanceName = halInstanceName; mFingerprintSensors = new SensorList<>(ActivityManager.getService()); - if (Flags.deHidl()) { - mHandler = biometricHandlerProvider.getFingerprintHandler(); - } else { - mHandler = new Handler(Looper.getMainLooper()); - } + mHandler = biometricHandlerProvider.getFingerprintHandler(); mLockoutResetDispatcher = lockoutResetDispatcher; mActivityTaskManager = ActivityTaskManager.getInstance(); mTaskStackListener = new BiometricTaskStackListener(); @@ -230,66 +219,19 @@ public class FingerprintProvider implements IBinder.DeathRecipient, ServiceProvi private void initSensors(boolean resetLockoutRequiresHardwareAuthToken, SensorProps[] props, GestureAvailabilityDispatcher gestureAvailabilityDispatcher) { - if (Flags.deHidl()) { - if (!resetLockoutRequiresHardwareAuthToken) { - Slog.d(getTag(), "Adding HIDL configs"); - for (SensorProps sensorConfig: props) { - addHidlSensors(sensorConfig, gestureAvailabilityDispatcher, - resetLockoutRequiresHardwareAuthToken); - } - } else { - Slog.d(getTag(), "Adding AIDL configs"); - final List<SensorLocationInternal> workaroundLocations = - getWorkaroundSensorProps(mContext); - for (SensorProps prop : props) { - addAidlSensors(prop, gestureAvailabilityDispatcher, workaroundLocations, - resetLockoutRequiresHardwareAuthToken); - } + if (!resetLockoutRequiresHardwareAuthToken) { + Slog.d(getTag(), "Adding HIDL configs"); + for (SensorProps sensorConfig: props) { + addHidlSensors(sensorConfig, gestureAvailabilityDispatcher, + resetLockoutRequiresHardwareAuthToken); } } else { + Slog.d(getTag(), "Adding AIDL configs"); final List<SensorLocationInternal> workaroundLocations = getWorkaroundSensorProps(mContext); - for (SensorProps prop : props) { - final int sensorId = prop.commonProps.sensorId; - final List<ComponentInfoInternal> componentInfo = new ArrayList<>(); - if (prop.commonProps.componentInfo != null) { - for (ComponentInfo info : prop.commonProps.componentInfo) { - componentInfo.add(new ComponentInfoInternal(info.componentId, - info.hardwareVersion, info.firmwareVersion, info.serialNumber, - info.softwareVersion)); - } - } - final FingerprintSensorPropertiesInternal internalProp = - new FingerprintSensorPropertiesInternal(prop.commonProps.sensorId, - prop.commonProps.sensorStrength, - prop.commonProps.maxEnrollmentsPerUser, - componentInfo, - prop.sensorType, - prop.halControlsIllumination, - true /* resetLockoutRequiresHardwareAuthToken */, - !workaroundLocations.isEmpty() ? workaroundLocations : - Arrays.stream(prop.sensorLocations).map( - location -> new SensorLocationInternal( - location.display, - location.sensorLocationX, - location.sensorLocationY, - location.sensorRadius)) - .collect(Collectors.toList())); - final Sensor sensor = new Sensor(this, mContext, mHandler, internalProp, - mBiometricContext); - sensor.init(gestureAvailabilityDispatcher, mLockoutResetDispatcher); - final int sessionUserId = - sensor.getLazySession().get() == null ? UserHandle.USER_NULL : - sensor.getLazySession().get().getUserId(); - mFingerprintSensors.addSensor(sensorId, sensor, sessionUserId, - new SynchronousUserSwitchObserver() { - @Override - public void onUserSwitching(int newUserId) { - scheduleInternalCleanup(sensorId, newUserId, null /* callback */); - } - }); - Slog.d(getTag(), "Added: " + mFingerprintSensors.get(sensorId).toString()); + addAidlSensors(prop, gestureAvailabilityDispatcher, workaroundLocations, + resetLockoutRequiresHardwareAuthToken); } } } @@ -546,23 +488,7 @@ public class FingerprintProvider implements IBinder.DeathRecipient, ServiceProvi mFingerprintSensors.get(sensorId).getSensorProperties(), mUdfpsOverlayController, mSidefpsController, mAuthenticationStateListeners, maxTemplatesPerUser, enrollReason, options); - if (Flags.deHidl()) { - scheduleForSensor(sensorId, client, mBiometricStateCallback); - } else { - scheduleForSensor(sensorId, client, new ClientMonitorCompositeCallback( - mBiometricStateCallback, new ClientMonitorCallback() { - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - ClientMonitorCallback.super.onClientFinished( - clientMonitor, success); - if (success) { - scheduleLoadAuthenticatorIdsForUser(sensorId, userId); - scheduleInvalidationRequest(sensorId, userId); - } - } - })); - } + scheduleForSensor(sensorId, client, mBiometricStateCallback); }); return id; } @@ -605,13 +531,8 @@ public class FingerprintProvider implements IBinder.DeathRecipient, ServiceProvi final int userId = options.getUserId(); final int sensorId = options.getSensorId(); final boolean isStrongBiometric = Utils.isStrongBiometric(sensorId); - final LockoutTracker lockoutTracker; - if (Flags.deHidl()) { - lockoutTracker = mFingerprintSensors.get(sensorId) - .getLockoutTracker(true /* forAuth */); - } else { - lockoutTracker = null; - } + final LockoutTracker lockoutTracker = mFingerprintSensors.get(sensorId) + .getLockoutTracker(true /* forAuth */); final FingerprintAuthenticationClient client = new FingerprintAuthenticationClient( mContext, mFingerprintSensors.get(sensorId).getLazySession(), token, requestId, callback, operationId, restricted, options, cookie, @@ -622,22 +543,16 @@ public class FingerprintProvider implements IBinder.DeathRecipient, ServiceProvi mTaskStackListener, mUdfpsOverlayController, mSidefpsController, mAuthenticationStateListeners, allowBackgroundAuthentication, - mFingerprintSensors.get(sensorId).getSensorProperties(), mHandler, + mFingerprintSensors.get(sensorId).getSensorProperties(), Utils.getCurrentStrength(sensorId), - SystemClock.elapsedRealtimeClock(), lockoutTracker); scheduleForSensor(sensorId, client, new ClientMonitorCallback() { @Override public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { mBiometricStateCallback.onClientStarted(clientMonitor); - if (Flags.deHidl()) { - mBiometricHandlerProvider.getBiometricCallbackHandler().post(() -> - mAuthSessionCoordinator.authStartedFor(userId, sensorId, - requestId)); - } else { - mAuthSessionCoordinator.authStartedFor(userId, sensorId, requestId); - } + mBiometricHandlerProvider.getBiometricCallbackHandler().post(() -> + mAuthSessionCoordinator.authStartedFor(userId, sensorId, requestId)); } @Override @@ -649,15 +564,10 @@ public class FingerprintProvider implements IBinder.DeathRecipient, ServiceProvi public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, boolean success) { mBiometricStateCallback.onClientFinished(clientMonitor, success); - if (Flags.deHidl()) { - mBiometricHandlerProvider.getBiometricCallbackHandler().post(() -> - mAuthSessionCoordinator.authEndedFor(userId, - Utils.getCurrentStrength(sensorId), sensorId, requestId, - success)); - } else { - mAuthSessionCoordinator.authEndedFor(userId, - Utils.getCurrentStrength(sensorId), sensorId, requestId, success); - } + mBiometricHandlerProvider.getBiometricCallbackHandler().post(() -> + mAuthSessionCoordinator.authEndedFor(userId, + Utils.getCurrentStrength(sensorId), sensorId, requestId, + success)); } }); @@ -764,10 +674,7 @@ public class FingerprintProvider implements IBinder.DeathRecipient, ServiceProvi @Override public boolean isHardwareDetected(int sensorId) { - if (Flags.deHidl()) { - return mFingerprintSensors.get(sensorId).isHardwareDetected(mHalInstanceName); - } - return hasHalInstance(); + return mFingerprintSensors.get(sensorId).isHardwareDetected(mHalInstanceName); } @Override @@ -805,12 +712,7 @@ public class FingerprintProvider implements IBinder.DeathRecipient, ServiceProvi @Override public int getLockoutModeForUser(int sensorId, int userId) { - if (Flags.deHidl()) { - return mFingerprintSensors.get(sensorId).getLockoutModeForUser(userId); - } else { - return mBiometricContext.getAuthSessionCoordinator().getLockoutStateFor(userId, - Utils.getCurrentStrength(sensorId)); - } + return mFingerprintSensors.get(sensorId).getLockoutModeForUser(userId); } @Override diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/Sensor.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/Sensor.java index af88c62904fc..b7e3f70a5763 100644 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/Sensor.java +++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/Sensor.java @@ -42,7 +42,6 @@ import android.util.Slog; import android.util.proto.ProtoOutputStream; import com.android.internal.util.FrameworkStatsLog; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.SensorServiceStateProto; import com.android.server.biometrics.SensorStateProto; import com.android.server.biometrics.UserStateProto; @@ -58,7 +57,6 @@ import com.android.server.biometrics.sensors.LockoutResetDispatcher; import com.android.server.biometrics.sensors.LockoutTracker; import com.android.server.biometrics.sensors.StartUserClient; import com.android.server.biometrics.sensors.StopUserClient; -import com.android.server.biometrics.sensors.UserAwareBiometricScheduler; import com.android.server.biometrics.sensors.UserSwitchProvider; import com.android.server.biometrics.sensors.fingerprint.FingerprintUtils; import com.android.server.biometrics.sensors.fingerprint.GestureAvailabilityDispatcher; @@ -110,13 +108,6 @@ public class Sensor { } Sensor(@NonNull FingerprintProvider provider, @NonNull Context context, - @NonNull Handler handler, @NonNull FingerprintSensorPropertiesInternal sensorProperties, - @NonNull BiometricContext biometricContext) { - this(provider, context, handler, sensorProperties, - biometricContext, null); - } - - Sensor(@NonNull FingerprintProvider provider, @NonNull Context context, @NonNull Handler handler, @NonNull SensorProps sensorProp, @NonNull BiometricContext biometricContext, @NonNull List<SensorLocationInternal> workaroundLocation, @@ -131,13 +122,8 @@ public class Sensor { */ public void init(@NonNull GestureAvailabilityDispatcher gestureAvailabilityDispatcher, @NonNull LockoutResetDispatcher lockoutResetDispatcher) { - if (Flags.deHidl()) { - setScheduler(getBiometricSchedulerForInit(gestureAvailabilityDispatcher, - lockoutResetDispatcher)); - } else { - setScheduler(getUserAwareBiometricSchedulerForInit(gestureAvailabilityDispatcher, - lockoutResetDispatcher)); - } + setScheduler(getBiometricSchedulerForInit(gestureAvailabilityDispatcher, + lockoutResetDispatcher)); mLockoutTracker = new LockoutCache(); mLazySession = () -> mCurrentSession != null ? mCurrentSession : null; } @@ -168,7 +154,7 @@ public class Sensor { final AidlResponseHandler resultController = new AidlResponseHandler( mContext, mScheduler, sensorId, newUserId, mLockoutTracker, lockoutResetDispatcher, - mBiometricContext.getAuthSessionCoordinator(), () -> {}, + mBiometricContext.getAuthSessionCoordinator(), new AidlResponseHandler.AidlResponseHandlerCallback() { @Override public void onEnrollSuccess() { @@ -192,45 +178,6 @@ public class Sensor { }); } - private UserAwareBiometricScheduler<ISession, AidlSession> - getUserAwareBiometricSchedulerForInit( - GestureAvailabilityDispatcher gestureAvailabilityDispatcher, - LockoutResetDispatcher lockoutResetDispatcher) { - return new UserAwareBiometricScheduler<>(TAG, - BiometricScheduler.sensorTypeFromFingerprintProperties(mSensorProperties), - gestureAvailabilityDispatcher, - () -> mCurrentSession != null ? mCurrentSession.getUserId() : UserHandle.USER_NULL, - new UserAwareBiometricScheduler.UserSwitchCallback() { - @NonNull - @Override - public StopUserClient<ISession> getStopUserClient(int userId) { - return new FingerprintStopUserClient(mContext, - () -> mLazySession.get().getSession(), mToken, - userId, mSensorProperties.sensorId, - BiometricLogger.ofUnknown(mContext), mBiometricContext, - () -> mCurrentSession = null); - } - - @NonNull - @Override - public StartUserClient<IFingerprint, ISession> getStartUserClient( - int newUserId) { - final int sensorId = mSensorProperties.sensorId; - - final AidlResponseHandler resultController = new AidlResponseHandler( - mContext, mScheduler, sensorId, newUserId, - mLockoutTracker, lockoutResetDispatcher, - mBiometricContext.getAuthSessionCoordinator(), () -> { - Slog.e(TAG, "Fingerprint hardware unavailable."); - mCurrentSession = null; - }); - - return Sensor.this.getStartUserClient(resultController, sensorId, - newUserId); - } - }); - } - private FingerprintStartUserClient getStartUserClient(AidlResponseHandler resultController, int sensorId, int newUserId) { final StartUserClient.UserStartedCallback<ISession> userStartedCallback = diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/BiometricTestSessionImpl.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/BiometricTestSessionImpl.java deleted file mode 100644 index fc037aeb7e17..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/BiometricTestSessionImpl.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.ITestSession; -import android.hardware.biometrics.ITestSessionCallback; -import android.hardware.fingerprint.Fingerprint; -import android.hardware.fingerprint.FingerprintEnrollOptions; -import android.hardware.fingerprint.FingerprintManager; -import android.hardware.fingerprint.IFingerprintServiceReceiver; -import android.os.Binder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.sensors.BaseClientMonitor; -import com.android.server.biometrics.sensors.BiometricStateCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.fingerprint.FingerprintUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Random; -import java.util.Set; - -/** - * A test session implementation for the {@link Fingerprint21} provider. See - * {@link android.hardware.biometrics.BiometricTestSession}. - */ -public class BiometricTestSessionImpl extends ITestSession.Stub { - - private static final String TAG = "BiometricTestSessionImpl"; - - @NonNull private final Context mContext; - private final int mSensorId; - @NonNull private final ITestSessionCallback mCallback; - @NonNull private final BiometricStateCallback mBiometricStateCallback; - @NonNull private final Fingerprint21 mFingerprint21; - @NonNull private final Fingerprint21.HalResultController mHalResultController; - @NonNull private final Set<Integer> mEnrollmentIds; - @NonNull private final Random mRandom; - - /** - * Internal receiver currently only used for enroll. Results do not need to be forwarded to the - * test, since enrollment is a platform-only API. The authentication path is tested through - * the public FingerprintManager APIs and does not use this receiver. - */ - private final IFingerprintServiceReceiver mReceiver = new IFingerprintServiceReceiver.Stub() { - @Override - public void onEnrollResult(Fingerprint fp, int remaining) { - - } - - @Override - public void onAcquired(int acquiredInfo, int vendorCode) { - - } - - @Override - public void onAuthenticationSucceeded(Fingerprint fp, int userId, - boolean isStrongBiometric) { - - } - - @Override - public void onFingerprintDetected(int sensorId, int userId, boolean isStrongBiometric) { - - } - - @Override - public void onAuthenticationFailed() { - - } - - @Override - public void onError(int error, int vendorCode) { - - } - - @Override - public void onRemoved(Fingerprint fp, int remaining) { - - } - - @Override - public void onChallengeGenerated(int sensorId, int userId, long challenge) { - - } - - @Override - public void onUdfpsPointerDown(int sensorId) { - - } - - @Override - public void onUdfpsPointerUp(int sensorId) { - - } - - @Override - public void onUdfpsOverlayShown() { - - } - }; - - BiometricTestSessionImpl(@NonNull Context context, int sensorId, - @NonNull ITestSessionCallback callback, - @NonNull BiometricStateCallback biometricStateCallback, - @NonNull Fingerprint21 fingerprint21, - @NonNull Fingerprint21.HalResultController halResultController) { - mContext = context; - mSensorId = sensorId; - mCallback = callback; - mFingerprint21 = fingerprint21; - mBiometricStateCallback = biometricStateCallback; - mHalResultController = halResultController; - mEnrollmentIds = new HashSet<>(); - mRandom = new Random(); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void setTestHalEnabled(boolean enabled) { - - super.setTestHalEnabled_enforcePermission(); - - mFingerprint21.setTestHalEnabled(enabled); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void startEnroll(int userId) { - - super.startEnroll_enforcePermission(); - - mFingerprint21.scheduleEnroll(mSensorId, new Binder(), new byte[69], userId, mReceiver, - mContext.getOpPackageName(), FingerprintManager.ENROLL_ENROLL, - (new FingerprintEnrollOptions.Builder()).build()); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void finishEnroll(int userId) { - - super.finishEnroll_enforcePermission(); - - int nextRandomId = mRandom.nextInt(); - while (mEnrollmentIds.contains(nextRandomId)) { - nextRandomId = mRandom.nextInt(); - } - - mEnrollmentIds.add(nextRandomId); - mHalResultController.onEnrollResult(0 /* deviceId */, - nextRandomId /* fingerId */, userId, 0); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void acceptAuthentication(int userId) { - - // Fake authentication with any of the existing fingers - super.acceptAuthentication_enforcePermission(); - - List<Fingerprint> fingerprints = FingerprintUtils.getLegacyInstance(mSensorId) - .getBiometricsForUser(mContext, userId); - if (fingerprints.isEmpty()) { - Slog.w(TAG, "No fingerprints, returning"); - return; - } - final int fid = fingerprints.get(0).getBiometricId(); - final ArrayList<Byte> hat = new ArrayList<>(Collections.nCopies(69, (byte) 0)); - mHalResultController.onAuthenticated(0 /* deviceId */, fid, userId, hat); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void rejectAuthentication(int userId) { - - super.rejectAuthentication_enforcePermission(); - - mHalResultController.onAuthenticated(0 /* deviceId */, 0 /* fingerId */, userId, null); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void notifyAcquired(int userId, int acquireInfo) { - - super.notifyAcquired_enforcePermission(); - - mHalResultController.onAcquired(0 /* deviceId */, acquireInfo, 0 /* vendorCode */); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void notifyError(int userId, int errorCode) { - - super.notifyError_enforcePermission(); - - mHalResultController.onError(0 /* deviceId */, errorCode, 0 /* vendorCode */); - } - - @android.annotation.EnforcePermission(android.Manifest.permission.TEST_BIOMETRIC) - @Override - public void cleanupInternalState(int userId) { - - super.cleanupInternalState_enforcePermission(); - - mFingerprint21.scheduleInternalCleanup(mSensorId, userId, new ClientMonitorCallback() { - @Override - public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { - try { - mCallback.onCleanupStarted(clientMonitor.getTargetUserId()); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception", e); - } - } - - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - try { - mCallback.onCleanupFinished(clientMonitor.getTargetUserId()); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception", e); - } - } - }); - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21.java deleted file mode 100644 index 33e448bbe612..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21.java +++ /dev/null @@ -1,1289 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.app.ActivityManager; -import android.app.ActivityTaskManager; -import android.app.SynchronousUserSwitchObserver; -import android.app.TaskStackListener; -import android.app.UserSwitchObserver; -import android.content.Context; -import android.content.pm.UserInfo; -import android.hardware.biometrics.BiometricConstants; -import android.hardware.biometrics.BiometricsProtoEnums; -import android.hardware.biometrics.IInvalidationCallback; -import android.hardware.biometrics.ITestSession; -import android.hardware.biometrics.ITestSessionCallback; -import android.hardware.biometrics.fingerprint.PointerContext; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.hardware.biometrics.fingerprint.V2_2.IBiometricsFingerprintClientCallback; -import android.hardware.fingerprint.Fingerprint; -import android.hardware.fingerprint.FingerprintAuthenticateOptions; -import android.hardware.fingerprint.FingerprintEnrollOptions; -import android.hardware.fingerprint.FingerprintManager; -import android.hardware.fingerprint.FingerprintSensorProperties; -import android.hardware.fingerprint.FingerprintSensorPropertiesInternal; -import android.hardware.fingerprint.IFingerprintServiceReceiver; -import android.hardware.fingerprint.ISidefpsController; -import android.hardware.fingerprint.IUdfpsOverlayController; -import android.os.Handler; -import android.os.IBinder; -import android.os.IHwBinder; -import android.os.RemoteException; -import android.os.UserHandle; -import android.os.UserManager; -import android.util.Slog; -import android.util.proto.ProtoOutputStream; - -import com.android.internal.annotations.VisibleForTesting; -import com.android.internal.util.FrameworkStatsLog; -import com.android.server.biometrics.AuthenticationStatsBroadcastReceiver; -import com.android.server.biometrics.AuthenticationStatsCollector; -import com.android.server.biometrics.Flags; -import com.android.server.biometrics.SensorServiceStateProto; -import com.android.server.biometrics.SensorStateProto; -import com.android.server.biometrics.UserStateProto; -import com.android.server.biometrics.Utils; -import com.android.server.biometrics.fingerprint.FingerprintServiceDumpProto; -import com.android.server.biometrics.fingerprint.FingerprintUserStatsProto; -import com.android.server.biometrics.fingerprint.PerformanceStatsProto; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.AcquisitionClient; -import com.android.server.biometrics.sensors.AuthSessionCoordinator; -import com.android.server.biometrics.sensors.AuthenticationClient; -import com.android.server.biometrics.sensors.AuthenticationConsumer; -import com.android.server.biometrics.sensors.AuthenticationStateListeners; -import com.android.server.biometrics.sensors.BaseClientMonitor; -import com.android.server.biometrics.sensors.BiometricScheduler; -import com.android.server.biometrics.sensors.BiometricStateCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.ClientMonitorCompositeCallback; -import com.android.server.biometrics.sensors.EnumerateConsumer; -import com.android.server.biometrics.sensors.ErrorConsumer; -import com.android.server.biometrics.sensors.LockoutCache; -import com.android.server.biometrics.sensors.LockoutResetDispatcher; -import com.android.server.biometrics.sensors.LockoutTracker; -import com.android.server.biometrics.sensors.PerformanceTracker; -import com.android.server.biometrics.sensors.RemovalConsumer; -import com.android.server.biometrics.sensors.fingerprint.FingerprintUtils; -import com.android.server.biometrics.sensors.fingerprint.GestureAvailabilityDispatcher; -import com.android.server.biometrics.sensors.fingerprint.ServiceProvider; -import com.android.server.biometrics.sensors.fingerprint.Udfps; -import com.android.server.biometrics.sensors.fingerprint.aidl.AidlResponseHandler; -import com.android.server.biometrics.sensors.fingerprint.aidl.AidlSession; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.FileDescriptor; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Supplier; - -/** - * Supports a single instance of the {@link android.hardware.biometrics.fingerprint.V2_1} or - * its extended minor versions. - */ -public class Fingerprint21 implements IHwBinder.DeathRecipient, ServiceProvider { - - private static final String TAG = "Fingerprint21"; - private static final int ENROLL_TIMEOUT_SEC = 60; - - private boolean mTestHalEnabled; - - final Context mContext; - @NonNull private final BiometricStateCallback mBiometricStateCallback; - @NonNull private final AuthenticationStateListeners mAuthenticationStateListeners; - private final ActivityTaskManager mActivityTaskManager; - @NonNull private final FingerprintSensorPropertiesInternal mSensorProperties; - private final BiometricScheduler<IBiometricsFingerprint, AidlSession> mScheduler; - private final Handler mHandler; - private final LockoutResetDispatcher mLockoutResetDispatcher; - private final LockoutFrameworkImpl mLockoutTracker; - private final BiometricTaskStackListener mTaskStackListener; - private final Supplier<IBiometricsFingerprint> mLazyDaemon; - private final Map<Integer, Long> mAuthenticatorIds; - - @Nullable private IBiometricsFingerprint mDaemon; - @NonNull private final HalResultController mHalResultController; - @Nullable private IUdfpsOverlayController mUdfpsOverlayController; - - // TODO(b/288175061): remove with Flags.FLAG_SIDEFPS_CONTROLLER_REFACTOR - @Nullable private ISidefpsController mSidefpsController; - @NonNull private final BiometricContext mBiometricContext; - @Nullable private AuthenticationStatsCollector mAuthenticationStatsCollector; - // for requests that do not use biometric prompt - @NonNull private final AtomicLong mRequestCounter = new AtomicLong(0); - private int mCurrentUserId = UserHandle.USER_NULL; - private final boolean mIsUdfps; - private final int mSensorId; - private final boolean mIsPowerbuttonFps; - private AidlSession mSession; - - private final class BiometricTaskStackListener extends TaskStackListener { - @Override - public void onTaskStackChanged() { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof AuthenticationClient)) { - Slog.e(TAG, "Task stack changed for client: " + client); - return; - } - if (Utils.isKeyguard(mContext, client.getOwnerString()) - || Utils.isSystem(mContext, client.getOwnerString())) { - return; // Keyguard is always allowed - } - - if (Utils.isBackground(client.getOwnerString()) - && !client.isAlreadyDone()) { - Slog.e(TAG, "Stopping background authentication," - + " currentClient: " + client); - mScheduler.cancelAuthenticationOrDetection( - client.getToken(), client.getRequestId()); - } - }); - } - } - - private final LockoutFrameworkImpl.LockoutResetCallback mLockoutResetCallback = - new LockoutFrameworkImpl.LockoutResetCallback() { - @Override - public void onLockoutReset(int userId) { - mLockoutResetDispatcher.notifyLockoutResetCallbacks(mSensorProperties.sensorId); - } - }; - - private final UserSwitchObserver mUserSwitchObserver = new SynchronousUserSwitchObserver() { - @Override - public void onUserSwitching(int newUserId) { - scheduleInternalCleanup(newUserId, null /* callback */); - } - }; - - public static class HalResultController extends IBiometricsFingerprintClientCallback.Stub { - - /** - * Interface to sends results to the HalResultController's owner. - */ - public interface Callback { - /** - * Invoked when the HAL sends ERROR_HW_UNAVAILABLE. - */ - void onHardwareUnavailable(); - } - - private final int mSensorId; - @NonNull private final Context mContext; - @NonNull final Handler mHandler; - @NonNull final BiometricScheduler<IBiometricsFingerprint, AidlSession> mScheduler; - @Nullable private Callback mCallback; - - HalResultController(int sensorId, @NonNull Context context, @NonNull Handler handler, - @NonNull BiometricScheduler<IBiometricsFingerprint, AidlSession> scheduler) { - mSensorId = sensorId; - mContext = context; - mHandler = handler; - mScheduler = scheduler; - } - - public void setCallback(@Nullable Callback callback) { - mCallback = callback; - } - - @Override - public void onEnrollResult(long deviceId, int fingerId, int groupId, int remaining) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof FingerprintEnrollClient)) { - Slog.e(TAG, "onEnrollResult for non-enroll client: " - + Utils.getClientName(client)); - return; - } - - final int currentUserId = client.getTargetUserId(); - final CharSequence name = FingerprintUtils.getLegacyInstance(mSensorId) - .getUniqueName(mContext, currentUserId); - final Fingerprint fingerprint = new Fingerprint(name, groupId, fingerId, deviceId); - - final FingerprintEnrollClient enrollClient = (FingerprintEnrollClient) client; - enrollClient.onEnrollResult(fingerprint, remaining); - }); - } - - @Override - public void onAcquired(long deviceId, int acquiredInfo, int vendorCode) { - onAcquired_2_2(deviceId, acquiredInfo, vendorCode); - } - - @Override - public void onAcquired_2_2(long deviceId, int acquiredInfo, int vendorCode) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof AcquisitionClient)) { - Slog.e(TAG, "onAcquired for non-acquisition client: " - + Utils.getClientName(client)); - return; - } - - final AcquisitionClient<?> acquisitionClient = (AcquisitionClient<?>) client; - acquisitionClient.onAcquired(acquiredInfo, vendorCode); - }); - } - - @Override - public void onAuthenticated(long deviceId, int fingerId, int groupId, - ArrayList<Byte> token) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof AuthenticationConsumer)) { - Slog.e(TAG, "onAuthenticated for non-authentication consumer: " - + Utils.getClientName(client)); - return; - } - - final AuthenticationConsumer authenticationConsumer = - (AuthenticationConsumer) client; - final boolean authenticated = fingerId != 0; - final Fingerprint fp = new Fingerprint("", groupId, fingerId, deviceId); - authenticationConsumer.onAuthenticated(fp, authenticated, token); - }); - } - - @Override - public void onError(long deviceId, int error, int vendorCode) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - Slog.d(TAG, "handleError" - + ", client: " + Utils.getClientName(client) - + ", error: " + error - + ", vendorCode: " + vendorCode); - if (!(client instanceof ErrorConsumer)) { - Slog.e(TAG, "onError for non-error consumer: " + Utils.getClientName(client)); - return; - } - - final ErrorConsumer errorConsumer = (ErrorConsumer) client; - errorConsumer.onError(error, vendorCode); - - if (error == BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE) { - Slog.e(TAG, "Got ERROR_HW_UNAVAILABLE"); - if (mCallback != null) { - mCallback.onHardwareUnavailable(); - } - } - }); - } - - @Override - public void onRemoved(long deviceId, int fingerId, int groupId, int remaining) { - mHandler.post(() -> { - Slog.d(TAG, "Removed, fingerId: " + fingerId + ", remaining: " + remaining); - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof RemovalConsumer)) { - Slog.e(TAG, "onRemoved for non-removal consumer: " - + Utils.getClientName(client)); - return; - } - - final Fingerprint fp = new Fingerprint("", groupId, fingerId, deviceId); - final RemovalConsumer removalConsumer = (RemovalConsumer) client; - removalConsumer.onRemoved(fp, remaining); - }); - } - - @Override - public void onEnumerate(long deviceId, int fingerId, int groupId, int remaining) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof EnumerateConsumer)) { - Slog.e(TAG, "onEnumerate for non-enumerate consumer: " - + Utils.getClientName(client)); - return; - } - - final Fingerprint fp = new Fingerprint("", groupId, fingerId, deviceId); - final EnumerateConsumer enumerateConsumer = (EnumerateConsumer) client; - enumerateConsumer.onEnumerationResult(fp, remaining); - }); - } - } - - @VisibleForTesting - Fingerprint21(@NonNull Context context, - @NonNull BiometricStateCallback biometricStateCallback, - @NonNull AuthenticationStateListeners authenticationStateListeners, - @NonNull FingerprintSensorPropertiesInternal sensorProps, - @NonNull BiometricScheduler<IBiometricsFingerprint, AidlSession> scheduler, - @NonNull Handler handler, - @NonNull LockoutResetDispatcher lockoutResetDispatcher, - @NonNull HalResultController controller, - @NonNull BiometricContext biometricContext) { - mContext = context; - mBiometricStateCallback = biometricStateCallback; - mAuthenticationStateListeners = authenticationStateListeners; - mBiometricContext = biometricContext; - - mSensorProperties = sensorProps; - mSensorId = sensorProps.sensorId; - mIsUdfps = sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL - || sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_ULTRASONIC; - mIsPowerbuttonFps = sensorProps.sensorType == FingerprintSensorProperties.TYPE_POWER_BUTTON; - - mScheduler = scheduler; - mHandler = handler; - mActivityTaskManager = ActivityTaskManager.getInstance(); - mTaskStackListener = new BiometricTaskStackListener(); - mAuthenticatorIds = Collections.synchronizedMap(new HashMap<>()); - mLazyDaemon = Fingerprint21.this::getDaemon; - mLockoutResetDispatcher = lockoutResetDispatcher; - mLockoutTracker = new LockoutFrameworkImpl(context, mLockoutResetCallback); - mHalResultController = controller; - mHalResultController.setCallback(() -> { - mDaemon = null; - mCurrentUserId = UserHandle.USER_NULL; - }); - - AuthenticationStatsBroadcastReceiver mBroadcastReceiver = - new AuthenticationStatsBroadcastReceiver( - mContext, - BiometricsProtoEnums.MODALITY_FINGERPRINT, - (AuthenticationStatsCollector collector) -> { - Slog.d(TAG, "Initializing AuthenticationStatsCollector"); - mAuthenticationStatsCollector = collector; - }); - - try { - ActivityManager.getService().registerUserSwitchObserver(mUserSwitchObserver, TAG); - } catch (RemoteException e) { - Slog.e(TAG, "Unable to register user switch observer"); - } - } - - public static Fingerprint21 newInstance(@NonNull Context context, - @NonNull BiometricStateCallback biometricStateCallback, - @NonNull AuthenticationStateListeners authenticationStateListeners, - @NonNull FingerprintSensorPropertiesInternal sensorProps, - @NonNull Handler handler, - @NonNull LockoutResetDispatcher lockoutResetDispatcher, - @NonNull GestureAvailabilityDispatcher gestureAvailabilityDispatcher) { - final BiometricScheduler<IBiometricsFingerprint, AidlSession> scheduler = - new BiometricScheduler<>( - BiometricScheduler.sensorTypeFromFingerprintProperties(sensorProps), - gestureAvailabilityDispatcher); - final HalResultController controller = new HalResultController(sensorProps.sensorId, - context, handler, scheduler); - return new Fingerprint21(context, biometricStateCallback, authenticationStateListeners, - sensorProps, scheduler, handler, lockoutResetDispatcher, controller, - BiometricContext.getInstance(context)); - } - - @Override - public void serviceDied(long cookie) { - Slog.e(TAG, "HAL died"); - mHandler.post(() -> { - PerformanceTracker.getInstanceForSensorId(mSensorProperties.sensorId) - .incrementHALDeathCount(); - mDaemon = null; - mCurrentUserId = UserHandle.USER_NULL; - - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (client instanceof ErrorConsumer) { - Slog.e(TAG, "Sending ERROR_HW_UNAVAILABLE for client: " + client); - final ErrorConsumer errorConsumer = (ErrorConsumer) client; - errorConsumer.onError(BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE, - 0 /* vendorCode */); - - FrameworkStatsLog.write(FrameworkStatsLog.BIOMETRIC_SYSTEM_HEALTH_ISSUE_DETECTED, - BiometricsProtoEnums.MODALITY_FINGERPRINT, - BiometricsProtoEnums.ISSUE_HAL_DEATH, - -1 /* sensorId */); - } - - mScheduler.recordCrashState(); - mScheduler.reset(); - }); - } - - synchronized AidlSession getSession() { - if (mDaemon != null && mSession != null) { - return mSession; - } else { - return mSession = new AidlSession(this::getDaemon, - mCurrentUserId, new AidlResponseHandler(mContext, - mScheduler, mSensorId, mCurrentUserId, new LockoutCache(), - mLockoutResetDispatcher, new AuthSessionCoordinator(), () -> { - mDaemon = null; - mCurrentUserId = UserHandle.USER_NULL; - })); - } - } - - @VisibleForTesting - synchronized IBiometricsFingerprint getDaemon() { - if (mTestHalEnabled) { - final TestHal testHal = new TestHal(mContext, mSensorId); - testHal.setNotify(mHalResultController); - return testHal; - } - - if (mDaemon != null) { - return mDaemon; - } - - Slog.d(TAG, "Daemon was null, reconnecting, current operation: " - + mScheduler.getCurrentClient()); - try { - mDaemon = IBiometricsFingerprint.getService(); - } catch (java.util.NoSuchElementException e) { - // Service doesn't exist or cannot be opened. - Slog.w(TAG, "NoSuchElementException", e); - } catch (RemoteException e) { - Slog.e(TAG, "Failed to get fingerprint HAL", e); - } - - if (mDaemon == null) { - Slog.w(TAG, "Fingerprint HAL not available"); - return null; - } - - mDaemon.asBinder().linkToDeath(this, 0 /* flags */); - - // HAL ID for these HIDL versions are only used to determine if callbacks have been - // successfully set. - long halId = 0; - try { - halId = mDaemon.setNotify(mHalResultController); - } catch (RemoteException e) { - Slog.e(TAG, "Failed to set callback for fingerprint HAL", e); - mDaemon = null; - } - - Slog.d(TAG, "Fingerprint HAL ready, HAL ID: " + halId); - if (halId != 0) { - scheduleLoadAuthenticatorIds(); - scheduleInternalCleanup(ActivityManager.getCurrentUser(), null /* callback */); - } else { - Slog.e(TAG, "Unable to set callback"); - mDaemon = null; - } - - return mDaemon; - } - - @Nullable IUdfpsOverlayController getUdfpsOverlayController() { - return mUdfpsOverlayController; - } - - private void scheduleLoadAuthenticatorIds() { - // Note that this can be performed on the scheduler (as opposed to being done immediately - // when the HAL is (re)loaded, since - // 1) If this is truly the first time it's being performed (e.g. system has just started), - // this will be run very early and way before any applications need to generate keys. - // 2) If this is being performed to refresh the authenticatorIds (e.g. HAL crashed and has - // just been reloaded), the framework already has a cache of the authenticatorIds. This - // is safe because authenticatorIds only change when A) new template has been enrolled, - // or B) all templates are removed. - mHandler.post(() -> { - for (UserInfo user : UserManager.get(mContext).getAliveUsers()) { - final int targetUserId = user.id; - if (!mAuthenticatorIds.containsKey(targetUserId)) { - scheduleUpdateActiveUserWithoutHandler(targetUserId, true /* force */); - } - } - }); - } - - private void scheduleUpdateActiveUserWithoutHandler(int targetUserId) { - scheduleUpdateActiveUserWithoutHandler(targetUserId, false /* force */); - } - - /** - * Schedules the {@link FingerprintUpdateActiveUserClient} without posting the work onto the - * handler. Many/most APIs are user-specific. However, the HAL requires explicit "setActiveUser" - * invocation prior to authenticate/enroll/etc. Thus, internally we usually want to schedule - * this operation on the same lambda/runnable as those operations so that the ordering is - * correct. - * - * @param targetUserId Switch to this user, and update their authenticatorId - * @param force Always retrieve the authenticatorId, even if we are already the targetUserId - */ - private void scheduleUpdateActiveUserWithoutHandler(int targetUserId, boolean force) { - final boolean hasEnrolled = - !getEnrolledFingerprints(mSensorProperties.sensorId, targetUserId).isEmpty(); - final FingerprintUpdateActiveUserClientLegacy client = - new FingerprintUpdateActiveUserClientLegacy(mContext, mLazyDaemon, targetUserId, - mContext.getOpPackageName(), mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext, - this::getCurrentUser, hasEnrolled, mAuthenticatorIds, force); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - if (success) { - if (mCurrentUserId != targetUserId) { - // Create new session with updated user ID - mSession = null; - } - mCurrentUserId = targetUserId; - } else { - Slog.w(TAG, "Failed to change user, still: " + mCurrentUserId); - } - } - }); - } - - private int getCurrentUser() { - return mCurrentUserId; - } - - @Override - public boolean containsSensor(int sensorId) { - return mSensorProperties.sensorId == sensorId; - } - - @Override - @NonNull - public List<FingerprintSensorPropertiesInternal> getSensorProperties() { - final List<FingerprintSensorPropertiesInternal> properties = new ArrayList<>(); - properties.add(mSensorProperties); - return properties; - } - - @Nullable - @Override - public FingerprintSensorPropertiesInternal getSensorProperties(int sensorId) { - return mSensorProperties; - } - - @Override - public void scheduleResetLockout(int sensorId, int userId, @Nullable byte[] hardwareAuthToken) { - // Fingerprint2.1 keeps track of lockout in the framework. Let's just do it on the handler - // thread. - mHandler.post(() -> { - if (Flags.deHidl()) { - scheduleResetLockoutAidl(sensorId, userId, hardwareAuthToken); - } else { - scheduleResetLockoutHidl(sensorId, userId); - } - }); - } - - private void scheduleResetLockoutAidl(int sensorId, int userId, - @Nullable byte[] hardwareAuthToken) { - final com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintResetLockoutClient client = - new com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintResetLockoutClient( - mContext, this::getSession, userId, mContext.getOpPackageName(), - sensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext, hardwareAuthToken, mLockoutTracker, - mLockoutResetDispatcher, - Utils.getCurrentStrength(sensorId)); - mScheduler.scheduleClientMonitor(client); - } - - private void scheduleResetLockoutHidl(int sensorId, int userId) { - final FingerprintResetLockoutClient client = new FingerprintResetLockoutClient(mContext, - userId, mContext.getOpPackageName(), sensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext, mLockoutTracker); - mScheduler.scheduleClientMonitor(client); - } - - @Override - public void scheduleGenerateChallenge(int sensorId, int userId, @NonNull IBinder token, - @NonNull IFingerprintServiceReceiver receiver, @NonNull String opPackageName) { - mHandler.post(() -> { - if (Flags.deHidl()) { - scheduleGenerateChallengeAidl(userId, token, receiver, opPackageName); - } else { - scheduleGenerateChallengeHidl(userId, token, receiver, opPackageName); - } - }); - } - - private void scheduleGenerateChallengeAidl(int userId, @NonNull IBinder token, - @NonNull IFingerprintServiceReceiver receiver, @NonNull String opPackageName) { - final com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintGenerateChallengeClient client = - new com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintGenerateChallengeClient( - mContext, this::getSession, token, - new ClientMonitorCallbackConverter(receiver), userId, opPackageName, - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext); - mScheduler.scheduleClientMonitor(client); - } - - private void scheduleGenerateChallengeHidl(int userId, @NonNull IBinder token, - @NonNull IFingerprintServiceReceiver receiver, @NonNull String opPackageName) { - final FingerprintGenerateChallengeClient client = - new FingerprintGenerateChallengeClient(mContext, mLazyDaemon, token, - new ClientMonitorCallbackConverter(receiver), userId, opPackageName, - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext); - mScheduler.scheduleClientMonitor(client); - } - - @Override - public void scheduleRevokeChallenge(int sensorId, int userId, @NonNull IBinder token, - @NonNull String opPackageName, long challenge) { - mHandler.post(() -> { - if (Flags.deHidl()) { - scheduleRevokeChallengeAidl(userId, token, opPackageName); - } else { - scheduleRevokeChallengeHidl(userId, token, opPackageName); - } - }); - } - - private void scheduleRevokeChallengeAidl(int userId, @NonNull IBinder token, - @NonNull String opPackageName) { - final com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintRevokeChallengeClient client = - new com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintRevokeChallengeClient( - mContext, this::getSession, - token, userId, opPackageName, - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext, 0L); - mScheduler.scheduleClientMonitor(client); - } - - private void scheduleRevokeChallengeHidl(int userId, @NonNull IBinder token, - @NonNull String opPackageName) { - final FingerprintRevokeChallengeClient client = new FingerprintRevokeChallengeClient( - mContext, mLazyDaemon, token, userId, opPackageName, - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_UNKNOWN, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext); - mScheduler.scheduleClientMonitor(client); - } - - @Override - public long scheduleEnroll(int sensorId, @NonNull IBinder token, - @NonNull byte[] hardwareAuthToken, int userId, - @NonNull IFingerprintServiceReceiver receiver, @NonNull String opPackageName, - @FingerprintManager.EnrollReason int enrollReason, - @NonNull FingerprintEnrollOptions options) { - final long id = mRequestCounter.incrementAndGet(); - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - - if (Flags.deHidl()) { - scheduleEnrollAidl(token, hardwareAuthToken, userId, receiver, - opPackageName, enrollReason, id, options); - } else { - scheduleEnrollHidl(token, hardwareAuthToken, userId, receiver, - opPackageName, enrollReason, id, options); - } - }); - return id; - } - - private void scheduleEnrollHidl(@NonNull IBinder token, - @NonNull byte[] hardwareAuthToken, int userId, - @NonNull IFingerprintServiceReceiver receiver, @NonNull String opPackageName, - @FingerprintManager.EnrollReason int enrollReason, long id, - @NonNull FingerprintEnrollOptions options) { - final FingerprintEnrollClient client = new FingerprintEnrollClient(mContext, - mLazyDaemon, token, id, new ClientMonitorCallbackConverter(receiver), - userId, hardwareAuthToken, opPackageName, - FingerprintUtils.getLegacyInstance(mSensorId), ENROLL_TIMEOUT_SEC, - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_ENROLL, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, mUdfpsOverlayController, - // TODO(b/288175061): remove with Flags.FLAG_SIDEFPS_CONTROLLER_REFACTOR - mSidefpsController, - mAuthenticationStateListeners, enrollReason, options); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { - mBiometricStateCallback.onClientStarted(clientMonitor); - } - - @Override - public void onBiometricAction(int action) { - mBiometricStateCallback.onBiometricAction(action); - } - - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - mBiometricStateCallback.onClientFinished(clientMonitor, success); - if (success) { - // Update authenticatorIds - scheduleUpdateActiveUserWithoutHandler(clientMonitor.getTargetUserId(), - true /* force */); - } - } - }); - } - - private void scheduleEnrollAidl(@NonNull IBinder token, - @NonNull byte[] hardwareAuthToken, int userId, - @NonNull IFingerprintServiceReceiver receiver, @NonNull String opPackageName, - @FingerprintManager.EnrollReason int enrollReason, long id, - @NonNull FingerprintEnrollOptions options) { - final com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintEnrollClient - client = - new com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintEnrollClient( - mContext, - this::getSession, token, id, - new ClientMonitorCallbackConverter(receiver), - userId, hardwareAuthToken, opPackageName, - FingerprintUtils.getLegacyInstance(mSensorId), - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_ENROLL, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext, null /* sensorProps */, - mUdfpsOverlayController, - // TODO(b/288175061): remove with Flags.FLAG_SIDEFPS_CONTROLLER_REFACTOR - mSidefpsController, - mAuthenticationStateListeners, - mContext.getResources().getInteger( - com.android.internal.R.integer.config_fingerprintMaxTemplatesPerUser), - enrollReason, options); - mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() { - @Override - public void onClientStarted(@NonNull BaseClientMonitor clientMonitor) { - mBiometricStateCallback.onClientStarted(clientMonitor); - } - - @Override - public void onBiometricAction(int action) { - mBiometricStateCallback.onBiometricAction(action); - } - - @Override - public void onClientFinished(@NonNull BaseClientMonitor clientMonitor, - boolean success) { - mBiometricStateCallback.onClientFinished(clientMonitor, success); - if (success) { - // Update authenticatorIds - scheduleUpdateActiveUserWithoutHandler(clientMonitor.getTargetUserId(), - true /* force */); - } - } - }); - } - - @Override - public void cancelEnrollment(int sensorId, @NonNull IBinder token, long requestId) { - mHandler.post(() -> mScheduler.cancelEnrollment(token, requestId)); - } - - @Override - public long scheduleFingerDetect(@NonNull IBinder token, - @NonNull ClientMonitorCallbackConverter listener, - @NonNull FingerprintAuthenticateOptions options, - int statsClient) { - final long id = mRequestCounter.incrementAndGet(); - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(options.getUserId()); - - final boolean isStrongBiometric = Utils.isStrongBiometric(mSensorProperties.sensorId); - - if (Flags.deHidl()) { - scheduleFingerDetectAidl(token, listener, options, statsClient, id, - isStrongBiometric); - } else { - scheduleFingerDetectHidl(token, listener, options, statsClient, id, - isStrongBiometric); - } - }); - - return id; - } - - private void scheduleFingerDetectHidl(@NonNull IBinder token, - @NonNull ClientMonitorCallbackConverter listener, - @NonNull FingerprintAuthenticateOptions options, - int statsClient, long id, boolean isStrongBiometric) { - final FingerprintDetectClient client = new FingerprintDetectClient(mContext, - mLazyDaemon, token, id, listener, options, - createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient, - mAuthenticationStatsCollector), - mBiometricContext, mUdfpsOverlayController, isStrongBiometric); - mScheduler.scheduleClientMonitor(client, mBiometricStateCallback); - } - - private void scheduleFingerDetectAidl(@NonNull IBinder token, - @NonNull ClientMonitorCallbackConverter listener, - @NonNull FingerprintAuthenticateOptions options, - int statsClient, long id, boolean isStrongBiometric) { - final com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintDetectClient - client = - new com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintDetectClient( - mContext, - this::getSession, token, id, listener, options, - createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient, - mAuthenticationStatsCollector), - mBiometricContext, mUdfpsOverlayController, isStrongBiometric); - mScheduler.scheduleClientMonitor(client, mBiometricStateCallback); - } - - @Override - public void scheduleAuthenticate(@NonNull IBinder token, long operationId, - int cookie, @NonNull ClientMonitorCallbackConverter listener, - @NonNull FingerprintAuthenticateOptions options, - long requestId, boolean restricted, int statsClient, - boolean allowBackgroundAuthentication) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(options.getUserId()); - - final boolean isStrongBiometric = Utils.isStrongBiometric(mSensorProperties.sensorId); - - if (Flags.deHidl()) { - scheduleAuthenticateAidl(token, operationId, cookie, listener, options, requestId, - restricted, statsClient, allowBackgroundAuthentication, isStrongBiometric); - } else { - scheduleAuthenticateHidl(token, operationId, cookie, listener, options, requestId, - restricted, statsClient, allowBackgroundAuthentication, isStrongBiometric); - } - }); - } - - private void scheduleAuthenticateAidl(@NonNull IBinder token, long operationId, - int cookie, @NonNull ClientMonitorCallbackConverter listener, - @NonNull FingerprintAuthenticateOptions options, - long requestId, boolean restricted, int statsClient, - boolean allowBackgroundAuthentication, boolean isStrongBiometric) { - final com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintAuthenticationClient - client = - new com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintAuthenticationClient( - mContext, this::getSession, token, requestId, listener, operationId, - restricted, options, cookie, false /* requireConfirmation */, - createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient, - mAuthenticationStatsCollector), - mBiometricContext, isStrongBiometric, - mTaskStackListener, - mUdfpsOverlayController, mSidefpsController, - mAuthenticationStateListeners, - allowBackgroundAuthentication, mSensorProperties, mHandler, - Utils.getCurrentStrength(mSensorId), null /* clock */, mLockoutTracker); - mScheduler.scheduleClientMonitor(client, mBiometricStateCallback); - } - - private void scheduleAuthenticateHidl(@NonNull IBinder token, long operationId, - int cookie, @NonNull ClientMonitorCallbackConverter listener, - @NonNull FingerprintAuthenticateOptions options, - long requestId, boolean restricted, int statsClient, - boolean allowBackgroundAuthentication, boolean isStrongBiometric) { - final FingerprintAuthenticationClient client = new FingerprintAuthenticationClient( - mContext, mLazyDaemon, token, requestId, listener, operationId, - restricted, options, cookie, false /* requireConfirmation */, - createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient, - mAuthenticationStatsCollector), - mBiometricContext, isStrongBiometric, - mTaskStackListener, mLockoutTracker, - mUdfpsOverlayController, mSidefpsController, - mAuthenticationStateListeners, - allowBackgroundAuthentication, mSensorProperties, - Utils.getCurrentStrength(mSensorId)); - mScheduler.scheduleClientMonitor(client, mBiometricStateCallback); - } - - @Override - public long scheduleAuthenticate(@NonNull IBinder token, long operationId, - int cookie, @NonNull ClientMonitorCallbackConverter listener, - @NonNull FingerprintAuthenticateOptions options, boolean restricted, int statsClient, - boolean allowBackgroundAuthentication) { - final long id = mRequestCounter.incrementAndGet(); - - scheduleAuthenticate(token, operationId, cookie, listener, - options, id, restricted, statsClient, allowBackgroundAuthentication); - - return id; - } - - @Override - public void startPreparedClient(int sensorId, int cookie) { - mHandler.post(() -> mScheduler.startPreparedClient(cookie)); - } - - @Override - public void cancelAuthentication(int sensorId, @NonNull IBinder token, long requestId) { - Slog.d(TAG, "cancelAuthentication, sensorId: " + sensorId); - mHandler.post(() -> mScheduler.cancelAuthenticationOrDetection(token, requestId)); - } - - @Override - public void scheduleRemove(int sensorId, @NonNull IBinder token, - @NonNull IFingerprintServiceReceiver receiver, int fingerId, int userId, - @NonNull String opPackageName) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - - if (Flags.deHidl()) { - scheduleRemoveAidl(token, receiver, fingerId, userId, opPackageName); - } else { - scheduleRemoveHidl(token, receiver, fingerId, userId, opPackageName); - } - }); - } - - private void scheduleRemoveHidl(@NonNull IBinder token, - @NonNull IFingerprintServiceReceiver receiver, int fingerId, int userId, - @NonNull String opPackageName) { - final FingerprintRemovalClient client = new FingerprintRemovalClient(mContext, - mLazyDaemon, token, new ClientMonitorCallbackConverter(receiver), fingerId, - userId, opPackageName, FingerprintUtils.getLegacyInstance(mSensorId), - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_REMOVE, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, mBiometricStateCallback); - } - - private void scheduleRemoveAidl(@NonNull IBinder token, - @NonNull IFingerprintServiceReceiver receiver, int fingerId, int userId, - @NonNull String opPackageName) { - final com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintRemovalClient client = - new com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintRemovalClient( - mContext, this::getSession, token, - new ClientMonitorCallbackConverter(receiver), new int[]{fingerId}, userId, - opPackageName, FingerprintUtils.getLegacyInstance(mSensorId), mSensorId, - createLogger(BiometricsProtoEnums.ACTION_REMOVE, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, mBiometricStateCallback); - } - - @Override - public void scheduleRemoveAll(int sensorId, @NonNull IBinder token, - @NonNull IFingerprintServiceReceiver receiver, int userId, - @NonNull String opPackageName) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - - // For IBiometricsFingerprint@2.1, remove(0) means remove all enrollments - if (Flags.deHidl()) { - scheduleRemoveAidl(token, receiver, 0 /* fingerId */, userId, opPackageName); - } else { - scheduleRemoveHidl(token, receiver, 0 /* fingerId */, userId, opPackageName); - } - }); - } - - private void scheduleInternalCleanup(int userId, - @Nullable ClientMonitorCallback callback) { - mHandler.post(() -> { - scheduleUpdateActiveUserWithoutHandler(userId); - - if (Flags.deHidl()) { - scheduleInternalCleanupAidl(userId, callback); - } else { - scheduleInternalCleanupHidl(userId, callback); - } - }); - } - - private void scheduleInternalCleanupHidl(int userId, - @Nullable ClientMonitorCallback callback) { - final FingerprintInternalCleanupClient client = new FingerprintInternalCleanupClient( - mContext, mLazyDaemon, userId, mContext.getOpPackageName(), - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_ENUMERATE, - BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector), - mBiometricContext, - FingerprintUtils.getLegacyInstance(mSensorId), mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, callback); - } - - private void scheduleInternalCleanupAidl(int userId, - @Nullable ClientMonitorCallback callback) { - final com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintInternalCleanupClient - client = - new com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintInternalCleanupClient( - mContext, this::getSession, userId, mContext.getOpPackageName(), - mSensorProperties.sensorId, - createLogger(BiometricsProtoEnums.ACTION_ENUMERATE, - BiometricsProtoEnums.CLIENT_UNKNOWN, - mAuthenticationStatsCollector), - mBiometricContext, - FingerprintUtils.getLegacyInstance(mSensorId), mAuthenticatorIds); - mScheduler.scheduleClientMonitor(client, callback); - } - - @Override - public void scheduleInternalCleanup(int sensorId, int userId, - @Nullable ClientMonitorCallback callback) { - scheduleInternalCleanup(userId, new ClientMonitorCompositeCallback(callback, - mBiometricStateCallback)); - } - - @Override - public void scheduleInternalCleanup(int sensorId, int userId, - @Nullable ClientMonitorCallback callback, boolean favorHalEnrollments) { - scheduleInternalCleanup(userId, new ClientMonitorCompositeCallback(callback, - mBiometricStateCallback)); - } - - private BiometricLogger createLogger(int statsAction, int statsClient, - AuthenticationStatsCollector authenticationStatsCollector) { - return new BiometricLogger(mContext, BiometricsProtoEnums.MODALITY_FINGERPRINT, - statsAction, statsClient, authenticationStatsCollector); - } - - @Override - public boolean isHardwareDetected(int sensorId) { - return getDaemon() != null; - } - - @Override - public void rename(int sensorId, int fingerId, int userId, @NonNull String name) { - mHandler.post(() -> { - FingerprintUtils.getLegacyInstance(mSensorId) - .renameBiometricForUser(mContext, userId, fingerId, name); - }); - } - - @Override - @NonNull - public List<Fingerprint> getEnrolledFingerprints(int sensorId, int userId) { - return FingerprintUtils.getLegacyInstance(mSensorId).getBiometricsForUser(mContext, userId); - } - - @Override - public boolean hasEnrollments(int sensorId, int userId) { - return !getEnrolledFingerprints(sensorId, userId).isEmpty(); - } - - @Override - @LockoutTracker.LockoutMode public int getLockoutModeForUser(int sensorId, int userId) { - return mLockoutTracker.getLockoutModeForUser(userId); - } - - @Override - public long getAuthenticatorId(int sensorId, int userId) { - return mAuthenticatorIds.getOrDefault(userId, 0L); - } - - @Override - public void onPointerDown(long requestId, int sensorId, PointerContext pc) { - mScheduler.getCurrentClientIfMatches(requestId, (client) -> { - if (!(client instanceof Udfps)) { - Slog.w(TAG, "onFingerDown received during client: " + client); - return; - } - ((Udfps) client).onPointerDown(pc); - }); - } - - @Override - public void onPointerUp(long requestId, int sensorId, PointerContext pc) { - mScheduler.getCurrentClientIfMatches(requestId, (client) -> { - if (!(client instanceof Udfps)) { - Slog.w(TAG, "onFingerDown received during client: " + client); - return; - } - ((Udfps) client).onPointerUp(pc); - }); - } - - @Override - public void onUdfpsUiEvent(@FingerprintManager.UdfpsUiEvent int event, long requestId, - int sensorId) { - mScheduler.getCurrentClientIfMatches(requestId, (client) -> { - if (!(client instanceof Udfps)) { - Slog.w(TAG, "onUdfpsUiEvent received during client: " + client); - return; - } - ((Udfps) client).onUdfpsUiEvent(event); - }); - } - - @Override - public void onPowerPressed() { - Slog.e(TAG, "onPowerPressed not supported for HIDL clients"); - } - - @Override - public void setUdfpsOverlayController(@NonNull IUdfpsOverlayController controller) { - mUdfpsOverlayController = controller; - } - - // TODO(b/288175061): remove with Flags.FLAG_SIDEFPS_CONTROLLER_REFACTOR - @Override - public void setSidefpsController(@NonNull ISidefpsController controller) { - mSidefpsController = controller; - } - - @Override - public void dumpProtoState(int sensorId, @NonNull ProtoOutputStream proto, - boolean clearSchedulerBuffer) { - final long sensorToken = proto.start(SensorServiceStateProto.SENSOR_STATES); - - proto.write(SensorStateProto.SENSOR_ID, mSensorProperties.sensorId); - proto.write(SensorStateProto.MODALITY, SensorStateProto.FINGERPRINT); - if (mSensorProperties.isAnyUdfpsType()) { - proto.write(SensorStateProto.MODALITY_FLAGS, SensorStateProto.FINGERPRINT_UDFPS); - } - proto.write(SensorStateProto.CURRENT_STRENGTH, - Utils.getCurrentStrength(mSensorProperties.sensorId)); - proto.write(SensorStateProto.SCHEDULER, mScheduler.dumpProtoState(clearSchedulerBuffer)); - - for (UserInfo user : UserManager.get(mContext).getUsers()) { - final int userId = user.getUserHandle().getIdentifier(); - - final long userToken = proto.start(SensorStateProto.USER_STATES); - proto.write(UserStateProto.USER_ID, userId); - proto.write(UserStateProto.NUM_ENROLLED, FingerprintUtils.getLegacyInstance(mSensorId) - .getBiometricsForUser(mContext, userId).size()); - proto.end(userToken); - } - - proto.write(SensorStateProto.RESET_LOCKOUT_REQUIRES_HARDWARE_AUTH_TOKEN, - mSensorProperties.resetLockoutRequiresHardwareAuthToken); - proto.write(SensorStateProto.RESET_LOCKOUT_REQUIRES_CHALLENGE, - mSensorProperties.resetLockoutRequiresChallenge); - - proto.end(sensorToken); - } - - @Override - public void dumpProtoMetrics(int sensorId, FileDescriptor fd) { - PerformanceTracker tracker = - PerformanceTracker.getInstanceForSensorId(mSensorProperties.sensorId); - - final ProtoOutputStream proto = new ProtoOutputStream(fd); - for (UserInfo user : UserManager.get(mContext).getUsers()) { - final int userId = user.getUserHandle().getIdentifier(); - - final long userToken = proto.start(FingerprintServiceDumpProto.USERS); - - proto.write(FingerprintUserStatsProto.USER_ID, userId); - proto.write(FingerprintUserStatsProto.NUM_FINGERPRINTS, - FingerprintUtils.getLegacyInstance(mSensorId) - .getBiometricsForUser(mContext, userId).size()); - - // Normal fingerprint authentications (e.g. lockscreen) - long countsToken = proto.start(FingerprintUserStatsProto.NORMAL); - proto.write(PerformanceStatsProto.ACCEPT, tracker.getAcceptForUser(userId)); - proto.write(PerformanceStatsProto.REJECT, tracker.getRejectForUser(userId)); - proto.write(PerformanceStatsProto.ACQUIRE, tracker.getAcquireForUser(userId)); - proto.write(PerformanceStatsProto.LOCKOUT, tracker.getTimedLockoutForUser(userId)); - proto.write(PerformanceStatsProto.PERMANENT_LOCKOUT, - tracker.getPermanentLockoutForUser(userId)); - proto.end(countsToken); - - // Statistics about secure fingerprint transactions (e.g. to unlock password - // storage, make secure purchases, etc.) - countsToken = proto.start(FingerprintUserStatsProto.CRYPTO); - proto.write(PerformanceStatsProto.ACCEPT, tracker.getAcceptCryptoForUser(userId)); - proto.write(PerformanceStatsProto.REJECT, tracker.getRejectCryptoForUser(userId)); - proto.write(PerformanceStatsProto.ACQUIRE, tracker.getAcquireCryptoForUser(userId)); - proto.write(PerformanceStatsProto.LOCKOUT, 0); // meaningless for crypto - proto.write(PerformanceStatsProto.PERMANENT_LOCKOUT, 0); // meaningless for crypto - proto.end(countsToken); - - proto.end(userToken); - } - proto.flush(); - tracker.clear(); - } - - @Override - public void scheduleInvalidateAuthenticatorId(int sensorId, int userId, - @NonNull IInvalidationCallback callback) { - // TODO (b/179101888): Remove this temporary workaround. - try { - callback.onCompleted(); - } catch (RemoteException e) { - Slog.e(TAG, "Failed to complete InvalidateAuthenticatorId"); - } - } - - @Override - public void dumpInternal(int sensorId, @NonNull PrintWriter pw) { - PerformanceTracker performanceTracker = - PerformanceTracker.getInstanceForSensorId(mSensorProperties.sensorId); - - JSONObject dump = new JSONObject(); - try { - dump.put("service", TAG); - dump.put("isUdfps", mIsUdfps); - dump.put("isPowerbuttonFps", mIsPowerbuttonFps); - - JSONArray sets = new JSONArray(); - for (UserInfo user : UserManager.get(mContext).getUsers()) { - final int userId = user.getUserHandle().getIdentifier(); - final int N = FingerprintUtils.getLegacyInstance(mSensorId) - .getBiometricsForUser(mContext, userId).size(); - JSONObject set = new JSONObject(); - set.put("id", userId); - set.put("count", N); - set.put("accept", performanceTracker.getAcceptForUser(userId)); - set.put("reject", performanceTracker.getRejectForUser(userId)); - set.put("acquire", performanceTracker.getAcquireForUser(userId)); - set.put("lockout", performanceTracker.getTimedLockoutForUser(userId)); - set.put("permanentLockout", performanceTracker.getPermanentLockoutForUser(userId)); - // cryptoStats measures statistics about secure fingerprint transactions - // (e.g. to unlock password storage, make secure purchases, etc.) - set.put("acceptCrypto", performanceTracker.getAcceptCryptoForUser(userId)); - set.put("rejectCrypto", performanceTracker.getRejectCryptoForUser(userId)); - set.put("acquireCrypto", performanceTracker.getAcquireCryptoForUser(userId)); - sets.put(set); - } - - dump.put("prints", sets); - } catch (JSONException e) { - Slog.e(TAG, "dump formatting failure", e); - } - pw.println(dump); - pw.println("HAL deaths since last reboot: " + performanceTracker.getHALDeathCount()); - mScheduler.dump(pw); - } - - void setTestHalEnabled(boolean enabled) { - mTestHalEnabled = enabled; - } - - @NonNull - @Override - public ITestSession createTestSession(int sensorId, @NonNull ITestSessionCallback callback, - @NonNull String opPackageName) { - return new BiometricTestSessionImpl(mContext, mSensorProperties.sensorId, callback, - mBiometricStateCallback, this, mHalResultController); - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21UdfpsMock.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21UdfpsMock.java deleted file mode 100644 index f85794673476..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21UdfpsMock.java +++ /dev/null @@ -1,573 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.app.trust.TrustManager; -import android.content.ContentResolver; -import android.content.Context; -import android.hardware.biometrics.fingerprint.PointerContext; -import android.hardware.fingerprint.FingerprintAuthenticateOptions; -import android.hardware.fingerprint.FingerprintManager; -import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback; -import android.hardware.fingerprint.FingerprintManager.AuthenticationResult; -import android.hardware.fingerprint.FingerprintSensorProperties; -import android.hardware.fingerprint.FingerprintSensorPropertiesInternal; -import android.hardware.fingerprint.IFingerprintServiceReceiver; -import android.hardware.fingerprint.IUdfpsOverlayController; -import android.os.Handler; -import android.os.IBinder; -import android.os.Looper; -import android.os.RemoteException; -import android.os.UserHandle; -import android.provider.Settings; -import android.util.Slog; -import android.util.SparseBooleanArray; - -import com.android.internal.R; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.sensors.AuthenticationConsumer; -import com.android.server.biometrics.sensors.AuthenticationStateListeners; -import com.android.server.biometrics.sensors.BaseClientMonitor; -import com.android.server.biometrics.sensors.BiometricScheduler; -import com.android.server.biometrics.sensors.BiometricStateCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.LockoutResetDispatcher; -import com.android.server.biometrics.sensors.fingerprint.GestureAvailabilityDispatcher; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * A mockable/testable provider of the {@link android.hardware.biometrics.fingerprint.V2_3} HIDL - * interface. This class is intended simulate UDFPS logic for devices that do not have an actual - * fingerprint@2.3 HAL (where UDFPS starts to become supported) - * - * UDFPS "accept" can only happen within a set amount of time after a sensor authentication. This is - * specified by {@link MockHalResultController#AUTH_VALIDITY_MS}. Touches after this duration will - * be treated as "reject". - * - * This class provides framework logic to emulate, for testing only, the UDFPS functionalies below: - * - * 1) IF either A) the caller is keyguard, and the device is not in a trusted state (authenticated - * via biometric sensor or unlocked with a trust agent {@see android.app.trust.TrustManager}, OR - * B) the caller is not keyguard, and regardless of trusted state, AND (following applies to both - * (A) and (B) above) {@link FingerprintManager#onFingerDown(int, int, float, float)} is - * received, this class will respond with {@link AuthenticationCallback#onAuthenticationFailed()} - * after a tunable flat_time + variance_time. - * - * In the case above (1), callers must not receive a successful authentication event here because - * the sensor has not actually been authenticated. - * - * 2) IF A) the caller is keyguard and the device is not in a trusted state, OR B) the caller is not - * keyguard and regardless of trusted state, AND (following applies to both (A) and (B)) the - * sensor is touched and the fingerprint is accepted by the HAL, and then - * {@link FingerprintManager#onFingerDown(int, int, float, float)} is received, this class will - * respond with {@link AuthenticationCallback#onAuthenticationSucceeded(AuthenticationResult)} - * after a tunable flat_time + variance_time. Note that the authentication callback from the - * sensor is held until {@link FingerprintManager#onFingerDown(int, int, float, float)} is - * invoked. - * - * In the case above (2), callers can receive a successful authentication callback because the - * real sensor was authenticated. Note that even though the real sensor was touched, keyguard - * fingerprint authentication does not put keyguard into a trusted state because the - * authentication callback is held until onFingerDown was invoked. This allows callers such as - * keyguard to simulate a realistic path. - * - * 3) IF the caller is keyguard AND the device in a trusted state and then - * {@link FingerprintManager#onFingerDown(int, int, float, float)} is received, this class will - * respond with {@link AuthenticationCallback#onAuthenticationSucceeded(AuthenticationResult)} - * after a tunable flat_time + variance time. - * - * In the case above (3), since the device is already unlockable via trust agent, it's fine to - * simulate the successful auth path. Non-keyguard clients will fall into either (1) or (2) - * above. - * - * This class currently does not simulate false rejection. Conversely, this class relies on the - * real hardware sensor so does not affect false acceptance. - */ -@SuppressWarnings("deprecation") -public class Fingerprint21UdfpsMock extends Fingerprint21 implements TrustManager.TrustListener { - - private static final String TAG = "Fingerprint21UdfpsMock"; - - // Secure setting integer. If true, the system will load this class to enable udfps testing. - public static final String CONFIG_ENABLE_TEST_UDFPS = - "com.android.server.biometrics.sensors.fingerprint.test_udfps.enable"; - // Secure setting integer. A fixed duration intended to simulate something like the duration - // required for image capture. - private static final String CONFIG_AUTH_DELAY_PT1 = - "com.android.server.biometrics.sensors.fingerprint.test_udfps.auth_delay_pt1"; - // Secure setting integer. A fixed duration intended to simulate something like the duration - // required for template matching to complete. - private static final String CONFIG_AUTH_DELAY_PT2 = - "com.android.server.biometrics.sensors.fingerprint.test_udfps.auth_delay_pt2"; - // Secure setting integer. A random value between [-randomness, randomness] will be added to the - // capture delay above for each accept/reject. - private static final String CONFIG_AUTH_DELAY_RANDOMNESS = - "com.android.server.biometrics.sensors.fingerprint.test_udfps.auth_delay_randomness"; - - private static final int DEFAULT_AUTH_DELAY_PT1_MS = 300; - private static final int DEFAULT_AUTH_DELAY_PT2_MS = 400; - private static final int DEFAULT_AUTH_DELAY_RANDOMNESS_MS = 100; - - @NonNull private final TestableBiometricScheduler mScheduler; - @NonNull private final Handler mHandler; - @NonNull private final FingerprintSensorPropertiesInternal mSensorProperties; - @NonNull private final MockHalResultController mMockHalResultController; - @NonNull private final TrustManager mTrustManager; - @NonNull private final SparseBooleanArray mUserHasTrust; - @NonNull private final Random mRandom; - @NonNull private final FakeRejectRunnable mFakeRejectRunnable; - @NonNull private final FakeAcceptRunnable mFakeAcceptRunnable; - @NonNull private final RestartAuthRunnable mRestartAuthRunnable; - - private static class TestableBiometricScheduler extends BiometricScheduler { - @NonNull private Fingerprint21UdfpsMock mFingerprint21; - - TestableBiometricScheduler( - @Nullable GestureAvailabilityDispatcher gestureAvailabilityDispatcher) { - super(BiometricScheduler.SENSOR_TYPE_FP_OTHER, gestureAvailabilityDispatcher); - } - - void init(@NonNull Fingerprint21UdfpsMock fingerprint21) { - mFingerprint21 = fingerprint21; - } - } - - /** - * All of the mocking/testing should happen in here. This way we don't need to modify the - * {@link BaseClientMonitor} implementations and can run the - * real path there. - */ - private static class MockHalResultController extends HalResultController { - - // Duration for which a sensor authentication can be treated as UDFPS success. - private static final int AUTH_VALIDITY_MS = 10 * 1000; // 10 seconds - - static class LastAuthArgs { - @NonNull final AuthenticationConsumer lastAuthenticatedClient; - final long deviceId; - final int fingerId; - final int groupId; - @Nullable final ArrayList<Byte> token; - - LastAuthArgs(@NonNull AuthenticationConsumer authenticationConsumer, long deviceId, - int fingerId, int groupId, @Nullable ArrayList<Byte> token) { - lastAuthenticatedClient = authenticationConsumer; - this.deviceId = deviceId; - this.fingerId = fingerId; - this.groupId = groupId; - if (token == null) { - this.token = null; - } else { - // Store a copy so the owner can be GC'd - this.token = new ArrayList<>(token); - } - } - } - - // Initialized after the constructor, but before it's ever used. - @NonNull private RestartAuthRunnable mRestartAuthRunnable; - @NonNull private Fingerprint21UdfpsMock mFingerprint21; - @Nullable private LastAuthArgs mLastAuthArgs; - - MockHalResultController(int sensorId, @NonNull Context context, @NonNull Handler handler, - @NonNull BiometricScheduler scheduler) { - super(sensorId, context, handler, scheduler); - } - - void init(@NonNull RestartAuthRunnable restartAuthRunnable, - @NonNull Fingerprint21UdfpsMock fingerprint21) { - mRestartAuthRunnable = restartAuthRunnable; - mFingerprint21 = fingerprint21; - } - - @Nullable AuthenticationConsumer getLastAuthenticatedClient() { - return mLastAuthArgs != null ? mLastAuthArgs.lastAuthenticatedClient : null; - } - - /** - * Intercepts the HAL authentication and holds it until the UDFPS simulation decides - * that authentication finished. - */ - @Override - public void onAuthenticated(long deviceId, int fingerId, int groupId, - ArrayList<Byte> token) { - mHandler.post(() -> { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - if (!(client instanceof AuthenticationConsumer)) { - Slog.e(TAG, "Non authentication consumer: " + client); - return; - } - - final boolean accepted = fingerId != 0; - if (accepted) { - mFingerprint21.setDebugMessage("Finger accepted"); - } else { - mFingerprint21.setDebugMessage("Finger rejected"); - } - - final AuthenticationConsumer authenticationConsumer = - (AuthenticationConsumer) client; - mLastAuthArgs = new LastAuthArgs(authenticationConsumer, deviceId, fingerId, - groupId, token); - - // Remove any existing restart runnbables since auth just started, and put a new - // one on the queue. - mHandler.removeCallbacks(mRestartAuthRunnable); - mRestartAuthRunnable.setLastAuthReference(authenticationConsumer); - mHandler.postDelayed(mRestartAuthRunnable, AUTH_VALIDITY_MS); - }); - } - - /** - * Calls through to the real interface and notifies clients of accept/reject. - */ - void sendAuthenticated(long deviceId, int fingerId, int groupId, - ArrayList<Byte> token) { - Slog.d(TAG, "sendAuthenticated: " + (fingerId != 0)); - mFingerprint21.setDebugMessage("Udfps match: " + (fingerId != 0)); - super.onAuthenticated(deviceId, fingerId, groupId, token); - } - } - - public static Fingerprint21UdfpsMock newInstance(@NonNull Context context, - @NonNull BiometricStateCallback biometricStateCallback, - @NonNull AuthenticationStateListeners authenticationStateListeners, - @NonNull FingerprintSensorPropertiesInternal sensorProps, - @NonNull LockoutResetDispatcher lockoutResetDispatcher, - @NonNull GestureAvailabilityDispatcher gestureAvailabilityDispatcher, - @NonNull BiometricContext biometricContext) { - Slog.d(TAG, "Creating Fingerprint23Mock!"); - - final Handler handler = new Handler(Looper.getMainLooper()); - final TestableBiometricScheduler scheduler = - new TestableBiometricScheduler(gestureAvailabilityDispatcher); - final MockHalResultController controller = - new MockHalResultController(sensorProps.sensorId, context, handler, scheduler); - return new Fingerprint21UdfpsMock(context, biometricStateCallback, - authenticationStateListeners, sensorProps, scheduler, handler, - lockoutResetDispatcher, controller, biometricContext); - } - - private static abstract class FakeFingerRunnable implements Runnable { - private long mFingerDownTime; - private int mCaptureDuration; - - /** - * @param fingerDownTime System time when onFingerDown occurred - * @param captureDuration Duration that the finger needs to be down for - */ - void setSimulationTime(long fingerDownTime, int captureDuration) { - mFingerDownTime = fingerDownTime; - mCaptureDuration = captureDuration; - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - boolean isImageCaptureComplete() { - return System.currentTimeMillis() - mFingerDownTime > mCaptureDuration; - } - } - - private final class FakeRejectRunnable extends FakeFingerRunnable { - @Override - public void run() { - mMockHalResultController.sendAuthenticated(0, 0, 0, null); - } - } - - private final class FakeAcceptRunnable extends FakeFingerRunnable { - @Override - public void run() { - if (mMockHalResultController.mLastAuthArgs == null) { - // This can happen if the user has trust agents enabled, which make lockscreen - // dismissable. Send a fake non-zero (accept) finger. - Slog.d(TAG, "Sending fake finger"); - mMockHalResultController.sendAuthenticated(1 /* deviceId */, - 1 /* fingerId */, 1 /* groupId */, null /* token */); - } else { - mMockHalResultController.sendAuthenticated( - mMockHalResultController.mLastAuthArgs.deviceId, - mMockHalResultController.mLastAuthArgs.fingerId, - mMockHalResultController.mLastAuthArgs.groupId, - mMockHalResultController.mLastAuthArgs.token); - } - } - } - - /** - * The fingerprint HAL allows multiple (5) fingerprint attempts per HIDL invocation of the - * authenticate method. However, valid fingerprint authentications are invalidated after - * {@link MockHalResultController#AUTH_VALIDITY_MS}, meaning UDFPS touches will be reported as - * rejects if touched after that duration. However, since a valid fingerprint was detected, the - * HAL and FingerprintService will not look for subsequent fingerprints. - * - * In order to keep the FingerprintManager API consistent (that multiple fingerprint attempts - * are allowed per auth lifecycle), we internally cancel and restart authentication so that the - * sensor is responsive again. - */ - private static final class RestartAuthRunnable implements Runnable { - @NonNull private final Fingerprint21UdfpsMock mFingerprint21; - @NonNull private final TestableBiometricScheduler mScheduler; - - // Store a reference to the auth consumer that should be invalidated. - private AuthenticationConsumer mLastAuthConsumer; - - RestartAuthRunnable(@NonNull Fingerprint21UdfpsMock fingerprint21, - @NonNull TestableBiometricScheduler scheduler) { - mFingerprint21 = fingerprint21; - mScheduler = scheduler; - } - - void setLastAuthReference(AuthenticationConsumer lastAuthConsumer) { - mLastAuthConsumer = lastAuthConsumer; - } - - @Override - public void run() { - final BaseClientMonitor client = mScheduler.getCurrentClient(); - - // We don't care about FingerprintDetectClient, since accept/rejects are both OK. UDFPS - // rejects will just simulate the path where non-enrolled fingers are presented. - if (!(client instanceof FingerprintAuthenticationClient)) { - Slog.e(TAG, "Non-FingerprintAuthenticationClient client: " + client); - return; - } - - // Perhaps the runnable is stale, or the user stopped/started auth manually. Do not - // restart auth in this case. - if (client != mLastAuthConsumer) { - Slog.e(TAG, "Current client: " + client - + " does not match mLastAuthConsumer: " + mLastAuthConsumer); - return; - } - - Slog.d(TAG, "Restarting auth, current: " + client); - mFingerprint21.setDebugMessage("Auth timed out"); - - final FingerprintAuthenticationClient authClient = - (FingerprintAuthenticationClient) client; - // Store the authClient parameters so it can be rescheduled - final IBinder token = client.getToken(); - final long operationId = authClient.getOperationId(); - final int cookie = client.getCookie(); - final ClientMonitorCallbackConverter listener = new ClientMonitorCallbackConverter( - new IFingerprintServiceReceiver.Default()); - final boolean restricted = authClient.isRestricted(); - final int statsClient = client.getLogger().getStatsClient(); - final boolean isKeyguard = authClient.isKeyguard(); - final FingerprintAuthenticateOptions options = - new FingerprintAuthenticateOptions.Builder() - .setUserId(client.getTargetUserId()) - .setOpPackageName(client.getOwnerString()) - .build(); - - // Don't actually send cancel() to the HAL, since successful auth already finishes - // HAL authenticate() lifecycle. Just - mScheduler.getInternalCallback().onClientFinished(client, true /* success */); - - // Schedule this only after we invoke onClientFinished for the previous client, so that - // internal preemption logic is not run. - mFingerprint21.scheduleAuthenticate(token, - operationId, cookie, listener, options, restricted, statsClient, - isKeyguard); - } - } - - private Fingerprint21UdfpsMock(@NonNull Context context, - @NonNull BiometricStateCallback biometricStateCallback, - @NonNull AuthenticationStateListeners authenticationStateListeners, - @NonNull FingerprintSensorPropertiesInternal sensorProps, - @NonNull TestableBiometricScheduler scheduler, - @NonNull Handler handler, - @NonNull LockoutResetDispatcher lockoutResetDispatcher, - @NonNull MockHalResultController controller, - @NonNull BiometricContext biometricContext) { - super(context, biometricStateCallback, authenticationStateListeners, sensorProps, scheduler, - handler, lockoutResetDispatcher, controller, biometricContext); - mScheduler = scheduler; - mScheduler.init(this); - mHandler = handler; - // resetLockout is controlled by the framework, so hardwareAuthToken is not required - final boolean resetLockoutRequiresHardwareAuthToken = false; - final int maxTemplatesAllowed = mContext.getResources() - .getInteger(R.integer.config_fingerprintMaxTemplatesPerUser); - mSensorProperties = new FingerprintSensorPropertiesInternal(sensorProps.sensorId, - sensorProps.sensorStrength, maxTemplatesAllowed, sensorProps.componentInfo, - FingerprintSensorProperties.TYPE_UDFPS_OPTICAL, false /* halControlsIllumination */, - resetLockoutRequiresHardwareAuthToken, sensorProps.getAllLocations()); - mMockHalResultController = controller; - mUserHasTrust = new SparseBooleanArray(); - mTrustManager = context.getSystemService(TrustManager.class); - mTrustManager.registerTrustListener(this); - mRandom = new Random(); - mFakeRejectRunnable = new FakeRejectRunnable(); - mFakeAcceptRunnable = new FakeAcceptRunnable(); - mRestartAuthRunnable = new RestartAuthRunnable(this, mScheduler); - - // We can't initialize this during MockHalresultController's constructor due to a circular - // dependency. - mMockHalResultController.init(mRestartAuthRunnable, this); - } - - @Override - public void onTrustChanged(boolean enabled, boolean newlyUnlocked, int userId, int flags, - List<String> trustGrantedMessages) { - mUserHasTrust.put(userId, enabled); - } - - @Override - public void onTrustManagedChanged(boolean enabled, int userId) { - - } - - @Override - public void onTrustError(CharSequence message) { - - } - - @Override - public void onEnabledTrustAgentsChanged(int userId) { - - } - - @Override - public void onIsActiveUnlockRunningChanged(boolean isRunning, int userId) { - - } - - @Override - @NonNull - public List<FingerprintSensorPropertiesInternal> getSensorProperties() { - final List<FingerprintSensorPropertiesInternal> properties = new ArrayList<>(); - properties.add(mSensorProperties); - return properties; - } - - @Override - public void onPointerDown(long requestId, int sensorId, PointerContext pc) { - mHandler.post(() -> { - Slog.d(TAG, "onFingerDown"); - final AuthenticationConsumer lastAuthenticatedConsumer = - mMockHalResultController.getLastAuthenticatedClient(); - final BaseClientMonitor currentScheduledClient = mScheduler.getCurrentClient(); - - if (currentScheduledClient == null) { - Slog.d(TAG, "Not authenticating"); - return; - } - - mHandler.removeCallbacks(mFakeRejectRunnable); - mHandler.removeCallbacks(mFakeAcceptRunnable); - - // The sensor was authenticated, is still the currently scheduled client, and the - // user touched the UDFPS affordance. Pretend that auth succeeded. - final boolean authenticatedClientIsCurrent = lastAuthenticatedConsumer != null - && lastAuthenticatedConsumer == currentScheduledClient; - // User is unlocked on keyguard via Trust Agent - final boolean keyguardAndTrusted; - if (currentScheduledClient instanceof FingerprintAuthenticationClient) { - keyguardAndTrusted = ((FingerprintAuthenticationClient) currentScheduledClient) - .isKeyguard() - && mUserHasTrust.get(currentScheduledClient.getTargetUserId(), false); - } else { - keyguardAndTrusted = false; - } - - final int captureDuration = getNewCaptureDuration(); - final int matchingDuration = getMatchingDuration(); - final int totalDuration = captureDuration + matchingDuration; - setDebugMessage("Duration: " + totalDuration - + " (" + captureDuration + " + " + matchingDuration + ")"); - if (authenticatedClientIsCurrent || keyguardAndTrusted) { - mFakeAcceptRunnable.setSimulationTime(System.currentTimeMillis(), captureDuration); - mHandler.postDelayed(mFakeAcceptRunnable, totalDuration); - } else if (currentScheduledClient instanceof AuthenticationConsumer) { - // Something is authenticating but authentication has not succeeded yet. Pretend - // that auth rejected. - mFakeRejectRunnable.setSimulationTime(System.currentTimeMillis(), captureDuration); - mHandler.postDelayed(mFakeRejectRunnable, totalDuration); - } - }); - } - - @Override - public void onPointerUp(long requestId, int sensorId, PointerContext pc) { - mHandler.post(() -> { - Slog.d(TAG, "onFingerUp"); - - // Only one of these can be on the handler at any given time (see onFingerDown). If - // image capture is not complete, send ACQUIRED_TOO_FAST and remove the runnable from - // the handler. Image capture (onFingerDown) needs to happen again. - if (mHandler.hasCallbacks(mFakeRejectRunnable) - && !mFakeRejectRunnable.isImageCaptureComplete()) { - mHandler.removeCallbacks(mFakeRejectRunnable); - mMockHalResultController.onAcquired(0 /* deviceId */, - FingerprintManager.FINGERPRINT_ACQUIRED_TOO_FAST, - 0 /* vendorCode */); - } else if (mHandler.hasCallbacks(mFakeAcceptRunnable) - && !mFakeAcceptRunnable.isImageCaptureComplete()) { - mHandler.removeCallbacks(mFakeAcceptRunnable); - mMockHalResultController.onAcquired(0 /* deviceId */, - FingerprintManager.FINGERPRINT_ACQUIRED_TOO_FAST, - 0 /* vendorCode */); - } - }); - } - - private int getNewCaptureDuration() { - final ContentResolver contentResolver = mContext.getContentResolver(); - final int captureTime = Settings.Secure.getIntForUser(contentResolver, - CONFIG_AUTH_DELAY_PT1, - DEFAULT_AUTH_DELAY_PT1_MS, - UserHandle.USER_CURRENT); - final int randomDelayRange = Settings.Secure.getIntForUser(contentResolver, - CONFIG_AUTH_DELAY_RANDOMNESS, - DEFAULT_AUTH_DELAY_RANDOMNESS_MS, - UserHandle.USER_CURRENT); - final int randomDelay = mRandom.nextInt(randomDelayRange * 2) - randomDelayRange; - - // Must be at least 0 - return Math.max(captureTime + randomDelay, 0); - } - - private int getMatchingDuration() { - final int matchingTime = Settings.Secure.getIntForUser(mContext.getContentResolver(), - CONFIG_AUTH_DELAY_PT2, - DEFAULT_AUTH_DELAY_PT2_MS, - UserHandle.USER_CURRENT); - - // Must be at least 0 - return Math.max(matchingTime, 0); - } - - private void setDebugMessage(String message) { - try { - final IUdfpsOverlayController controller = getUdfpsOverlayController(); - // Things can happen before SysUI loads and sets the controller. - if (controller != null) { - Slog.d(TAG, "setDebugMessage: " + message); - controller.setDebugMessage(mSensorProperties.sensorId, message); - } - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when sending message: " + message, e); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintAuthenticationClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintAuthenticationClient.java deleted file mode 100644 index b6311afb5ea1..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintAuthenticationClient.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import static android.adaptiveauth.Flags.reportBiometricAuthAttempts; - -import static com.android.systemui.shared.Flags.sidefpsControllerRefactor; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.app.TaskStackListener; -import android.content.Context; -import android.hardware.biometrics.BiometricAuthenticator; -import android.hardware.biometrics.BiometricConstants; -import android.hardware.biometrics.BiometricFingerprintConstants; -import android.hardware.biometrics.BiometricManager.Authenticators; -import android.hardware.biometrics.BiometricSourceType; -import android.hardware.biometrics.fingerprint.PointerContext; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.hardware.fingerprint.FingerprintAuthenticateOptions; -import android.hardware.fingerprint.FingerprintManager; -import android.hardware.fingerprint.FingerprintSensorPropertiesInternal; -import android.hardware.fingerprint.ISidefpsController; -import android.hardware.fingerprint.IUdfpsOverlayController; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.log.CallbackWithProbe; -import com.android.server.biometrics.log.Probe; -import com.android.server.biometrics.sensors.AuthenticationClient; -import com.android.server.biometrics.sensors.AuthenticationStateListeners; -import com.android.server.biometrics.sensors.BiometricNotificationUtils; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.ClientMonitorCompositeCallback; -import com.android.server.biometrics.sensors.LockoutTracker; -import com.android.server.biometrics.sensors.PerformanceTracker; -import com.android.server.biometrics.sensors.SensorOverlays; -import com.android.server.biometrics.sensors.fingerprint.Udfps; -import com.android.server.biometrics.sensors.fingerprint.UdfpsHelper; - -import java.util.ArrayList; -import java.util.function.Supplier; - -/** - * Fingerprint-specific authentication client supporting the - * {@link android.hardware.biometrics.fingerprint.V2_1} and - * {@link android.hardware.biometrics.fingerprint.V2_2} HIDL interfaces. - */ -class FingerprintAuthenticationClient - extends AuthenticationClient<IBiometricsFingerprint, FingerprintAuthenticateOptions> - implements Udfps { - - private static final String TAG = "Biometrics/FingerprintAuthClient"; - - private final LockoutFrameworkImpl mLockoutFrameworkImpl; - @NonNull private final SensorOverlays mSensorOverlays; - @NonNull private final FingerprintSensorPropertiesInternal mSensorProps; - @NonNull private final CallbackWithProbe<Probe> mALSProbeCallback; - @NonNull private final AuthenticationStateListeners mAuthenticationStateListeners; - - private boolean mIsPointerDown; - - FingerprintAuthenticationClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, - @NonNull IBinder token, long requestId, - @NonNull ClientMonitorCallbackConverter listener, long operationId, - boolean restricted, @NonNull FingerprintAuthenticateOptions options, - int cookie, boolean requireConfirmation, @NonNull BiometricLogger logger, - @NonNull BiometricContext biometricContext, boolean isStrongBiometric, - @NonNull TaskStackListener taskStackListener, - @NonNull LockoutFrameworkImpl lockoutTracker, - @Nullable IUdfpsOverlayController udfpsOverlayController, - // TODO(b/288175061): remove with Flags.FLAG_SIDEFPS_CONTROLLER_REFACTOR - @Nullable ISidefpsController sidefpsController, - @NonNull AuthenticationStateListeners authenticationStateListeners, - boolean allowBackgroundAuthentication, - @NonNull FingerprintSensorPropertiesInternal sensorProps, - @Authenticators.Types int sensorStrength) { - super(context, lazyDaemon, token, listener, operationId, restricted, - options, cookie, requireConfirmation, logger, biometricContext, - isStrongBiometric, taskStackListener, lockoutTracker, allowBackgroundAuthentication, - false /* shouldVibrate */, sensorStrength); - setRequestId(requestId); - mLockoutFrameworkImpl = lockoutTracker; - if (sidefpsControllerRefactor()) { - mSensorOverlays = new SensorOverlays(udfpsOverlayController); - } else { - mSensorOverlays = new SensorOverlays(udfpsOverlayController, sidefpsController); - } - mAuthenticationStateListeners = authenticationStateListeners; - mSensorProps = sensorProps; - mALSProbeCallback = getLogger().getAmbientLightProbe(false /* startWithClient */); - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - - if (mSensorProps.isAnyUdfpsType()) { - // UDFPS requires user to touch before becoming "active" - mState = STATE_STARTED_PAUSED; - } else { - mState = STATE_STARTED; - } - } - - @NonNull - @Override - protected ClientMonitorCallback wrapCallbackForStart(@NonNull ClientMonitorCallback callback) { - return new ClientMonitorCompositeCallback(mALSProbeCallback, callback); - } - - @Override - public void onAuthenticated(BiometricAuthenticator.Identifier identifier, - boolean authenticated, ArrayList<Byte> token) { - super.onAuthenticated(identifier, authenticated, token); - - // Authentication lifecycle ends either when - // 1) Authenticated == true - // 2) Error occurred (lockout or some other error) - // Note that authentication doesn't end when Authenticated == false - - if (authenticated) { - mState = STATE_STOPPED; - resetFailedAttempts(getTargetUserId()); - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - if (reportBiometricAuthAttempts()) { - mAuthenticationStateListeners.onAuthenticationSucceeded(getRequestReason(), - getTargetUserId()); - } - } else { - mState = STATE_STARTED_PAUSED_ATTEMPTED; - final @LockoutTracker.LockoutMode int lockoutMode = - mLockoutFrameworkImpl.getLockoutModeForUser(getTargetUserId()); - if (lockoutMode != LockoutTracker.LOCKOUT_NONE) { - Slog.w(TAG, "Fingerprint locked out, lockoutMode(" + lockoutMode + ")"); - final int errorCode = lockoutMode == LockoutTracker.LOCKOUT_TIMED - ? BiometricConstants.BIOMETRIC_ERROR_LOCKOUT - : BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT; - // Send the error, but do not invoke the FinishCallback yet. Since lockout is not - // controlled by the HAL, the framework must stop the sensor before finishing the - // client. - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - onErrorInternal(errorCode, 0 /* vendorCode */, false /* finish */); - cancel(); - } - if (reportBiometricAuthAttempts()) { - mAuthenticationStateListeners.onAuthenticationFailed(getRequestReason(), - getTargetUserId()); - } - } - } - - @Override - public void onError(int errorCode, int vendorCode) { - super.onError(errorCode, vendorCode); - - if (errorCode == BiometricFingerprintConstants.FINGERPRINT_ERROR_BAD_CALIBRATION) { - BiometricNotificationUtils.showBadCalibrationNotification(getContext()); - } - - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - } - - private void resetFailedAttempts(int userId) { - mLockoutFrameworkImpl.resetFailedAttemptsForUser(true /* clearAttemptCounter */, userId); - } - - @Override - protected void handleLifecycleAfterAuth(boolean authenticated) { - if (authenticated) { - mCallback.onClientFinished(this, true /* success */); - } - } - - @Override - public void onAcquired(int acquiredInfo, int vendorCode) { - mAuthenticationStateListeners.onAuthenticationAcquired( - BiometricSourceType.FINGERPRINT, getRequestReason(), acquiredInfo); - super.onAcquired(acquiredInfo, vendorCode); - - @LockoutTracker.LockoutMode final int lockoutMode = - getLockoutTracker().getLockoutModeForUser(getTargetUserId()); - if (lockoutMode == LockoutTracker.LOCKOUT_NONE) { - PerformanceTracker pt = PerformanceTracker.getInstanceForSensorId(getSensorId()); - pt.incrementAcquireForUser(getTargetUserId(), isCryptoOperation()); - } - } - - @Override - public boolean wasUserDetected() { - // TODO: Update if it needs to be used for fingerprint, i.e. success/reject, error_timeout - return false; - } - - @Override - public @LockoutTracker.LockoutMode int handleFailedAttempt(int userId) { - mLockoutFrameworkImpl.addFailedAttemptForUser(userId); - @LockoutTracker.LockoutMode final int lockoutMode = - getLockoutTracker().getLockoutModeForUser(userId); - final PerformanceTracker performanceTracker = - PerformanceTracker.getInstanceForSensorId(getSensorId()); - if (lockoutMode == LockoutTracker.LOCKOUT_PERMANENT) { - performanceTracker.incrementPermanentLockoutForUser(userId); - } else if (lockoutMode == LockoutTracker.LOCKOUT_TIMED) { - performanceTracker.incrementTimedLockoutForUser(userId); - } - - return lockoutMode; - } - - @Override - protected void startHalOperation() { - mSensorOverlays.show(getSensorId(), getRequestReason(), this); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStarted(getRequestReason()); - } - - try { - // GroupId was never used. In fact, groupId is always the same as userId. - getFreshDaemon().authenticate(mOperationId, getTargetUserId()); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting auth", e); - onError(BiometricFingerprintConstants.FINGERPRINT_ERROR_HW_UNAVAILABLE, - 0 /* vendorCode */); - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - protected void stopHalOperation() { - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - - try { - getFreshDaemon().cancel(); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting cancel", e); - onError(BiometricFingerprintConstants.FINGERPRINT_ERROR_HW_UNAVAILABLE, - 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - public void onPointerDown(PointerContext pc) { - mIsPointerDown = true; - mState = STATE_STARTED; - mALSProbeCallback.getProbe().enable(); - UdfpsHelper.onFingerDown(getFreshDaemon(), (int) pc.x, (int) pc.y, pc.minor, pc.major); - - try { - getListener().onUdfpsPointerDown(getSensorId()); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception", e); - } - } - - @Override - public void onPointerUp(PointerContext pc) { - mIsPointerDown = false; - mState = STATE_STARTED_PAUSED_ATTEMPTED; - mALSProbeCallback.getProbe().disable(); - UdfpsHelper.onFingerUp(getFreshDaemon()); - - try { - getListener().onUdfpsPointerUp(getSensorId()); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception", e); - } - } - - @Override - public boolean isPointerDown() { - return mIsPointerDown; - } - - @Override - public void onUdfpsUiEvent(@FingerprintManager.UdfpsUiEvent int event) { - // Unsupported in HIDL. - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintDetectClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintDetectClient.java deleted file mode 100644 index 50e48fe91c56..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintDetectClient.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import static com.android.systemui.shared.Flags.sidefpsControllerRefactor; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.content.Context; -import android.hardware.biometrics.BiometricAuthenticator; -import android.hardware.biometrics.BiometricFingerprintConstants; -import android.hardware.biometrics.BiometricRequestConstants; -import android.hardware.biometrics.fingerprint.PointerContext; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.hardware.fingerprint.FingerprintAuthenticateOptions; -import android.hardware.fingerprint.FingerprintManager; -import android.hardware.fingerprint.IUdfpsOverlayController; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.AcquisitionClient; -import com.android.server.biometrics.sensors.AuthenticationConsumer; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.PerformanceTracker; -import com.android.server.biometrics.sensors.SensorOverlays; -import com.android.server.biometrics.sensors.fingerprint.Udfps; -import com.android.server.biometrics.sensors.fingerprint.UdfpsHelper; - -import java.util.ArrayList; -import java.util.function.Supplier; - -/** - * Performs fingerprint detection without exposing any matching information (e.g. accept/reject - * have the same haptic, lockout counter is not increased). - */ -class FingerprintDetectClient extends AcquisitionClient<IBiometricsFingerprint> - implements AuthenticationConsumer, Udfps { - - private static final String TAG = "FingerprintDetectClient"; - - private final boolean mIsStrongBiometric; - @NonNull private final SensorOverlays mSensorOverlays; - private boolean mIsPointerDown; - - public FingerprintDetectClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, - @NonNull IBinder token, long requestId, - @NonNull ClientMonitorCallbackConverter listener, - @NonNull FingerprintAuthenticateOptions options, - @NonNull BiometricLogger biometricLogger, @NonNull BiometricContext biometricContext, - @Nullable IUdfpsOverlayController udfpsOverlayController, - boolean isStrongBiometric) { - super(context, lazyDaemon, token, listener, options.getUserId(), - options.getOpPackageName(), 0 /* cookie */, options.getSensorId(), - true /* shouldVibrate */, biometricLogger, biometricContext); - setRequestId(requestId); - if (sidefpsControllerRefactor()) { - mSensorOverlays = new SensorOverlays(udfpsOverlayController); - } else { - mSensorOverlays = new SensorOverlays( - udfpsOverlayController, null /* sideFpsController */); - } - mIsStrongBiometric = isStrongBiometric; - } - - @Override - protected void stopHalOperation() { - mSensorOverlays.hide(getSensorId()); - - try { - getFreshDaemon().cancel(); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting cancel", e); - onError(BiometricFingerprintConstants.FINGERPRINT_ERROR_HW_UNAVAILABLE, - 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - startHalOperation(); - } - - @Override - protected void startHalOperation() { - mSensorOverlays.show(getSensorId(), BiometricRequestConstants.REASON_AUTH_KEYGUARD, - this); - - try { - getFreshDaemon().authenticate(0 /* operationId */, getTargetUserId()); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting auth", e); - onError(BiometricFingerprintConstants.FINGERPRINT_ERROR_HW_UNAVAILABLE, - 0 /* vendorCode */); - mSensorOverlays.hide(getSensorId()); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - public void onPointerDown(PointerContext pc) { - mIsPointerDown = true; - UdfpsHelper.onFingerDown(getFreshDaemon(), (int) pc.x, (int) pc.y, pc.minor, pc.major); - } - - @Override - public void onPointerUp(PointerContext pc) { - mIsPointerDown = false; - UdfpsHelper.onFingerUp(getFreshDaemon()); - } - - @Override - public boolean isPointerDown() { - return mIsPointerDown; - } - - @Override - public void onUdfpsUiEvent(@FingerprintManager.UdfpsUiEvent int event) { - // Unsupported in HIDL. - } - - @Override - public void onAuthenticated(BiometricAuthenticator.Identifier identifier, - boolean authenticated, ArrayList<Byte> hardwareAuthToken) { - getLogger().logOnAuthenticated(getContext(), getOperationContext(), - authenticated, false /* requireConfirmation */, - getTargetUserId(), false /* isBiometricPrompt */); - - // Do not distinguish between success/failures. - vibrateSuccess(); - - final PerformanceTracker pm = PerformanceTracker.getInstanceForSensorId(getSensorId()); - pm.incrementAuthForUser(getTargetUserId(), authenticated); - - try { - getListener().onDetected(getSensorId(), getTargetUserId(), mIsStrongBiometric); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when sending onDetected", e); - } - } - - @Override - public int getProtoEnum() { - return BiometricsProto.CM_DETECT_INTERACTION; - } - - @Override - public boolean interruptsPrecedingClients() { - return true; - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintEnrollClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintEnrollClient.java deleted file mode 100644 index 8f937fc65cbb..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintEnrollClient.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import static com.android.systemui.shared.Flags.sidefpsControllerRefactor; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.content.Context; -import android.hardware.biometrics.BiometricAuthenticator; -import android.hardware.biometrics.BiometricFingerprintConstants; -import android.hardware.biometrics.BiometricStateListener; -import android.hardware.biometrics.fingerprint.PointerContext; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.hardware.fingerprint.Fingerprint; -import android.hardware.fingerprint.FingerprintEnrollOptions; -import android.hardware.fingerprint.FingerprintManager; -import android.hardware.fingerprint.ISidefpsController; -import android.hardware.fingerprint.IUdfpsOverlayController; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.AuthenticationStateListeners; -import com.android.server.biometrics.sensors.BiometricNotificationUtils; -import com.android.server.biometrics.sensors.BiometricUtils; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.ClientMonitorCompositeCallback; -import com.android.server.biometrics.sensors.EnrollClient; -import com.android.server.biometrics.sensors.SensorOverlays; -import com.android.server.biometrics.sensors.fingerprint.Udfps; -import com.android.server.biometrics.sensors.fingerprint.UdfpsHelper; - -import java.util.function.Supplier; - -/** - * Fingerprint-specific enroll client supporting the - * {@link android.hardware.biometrics.fingerprint.V2_1} and - * {@link android.hardware.biometrics.fingerprint.V2_2} HIDL interfaces. - */ -public class FingerprintEnrollClient extends EnrollClient<IBiometricsFingerprint> - implements Udfps { - - private static final String TAG = "FingerprintEnrollClient"; - - @NonNull private final SensorOverlays mSensorOverlays; - private final @FingerprintManager.EnrollReason int mEnrollReason; - @NonNull private final AuthenticationStateListeners mAuthenticationStateListeners; - private boolean mIsPointerDown; - - FingerprintEnrollClient( - @NonNull Context context, @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, - @NonNull IBinder token, long requestId, - @NonNull ClientMonitorCallbackConverter listener, int userId, - @NonNull byte[] hardwareAuthToken, @NonNull String owner, - @NonNull BiometricUtils<Fingerprint> utils, int timeoutSec, int sensorId, - @NonNull BiometricLogger biometricLogger, @NonNull BiometricContext biometricContext, - @Nullable IUdfpsOverlayController udfpsOverlayController, - // TODO(b/288175061): remove with Flags.FLAG_SIDEFPS_CONTROLLER_REFACTOR - @Nullable ISidefpsController sidefpsController, - @NonNull AuthenticationStateListeners authenticationStateListeners, - @FingerprintManager.EnrollReason int enrollReason, - @NonNull FingerprintEnrollOptions options) { - super(context, lazyDaemon, token, listener, userId, hardwareAuthToken, owner, utils, - timeoutSec, sensorId, true /* shouldVibrate */, biometricLogger, - biometricContext, - BiometricFingerprintConstants.reasonToMetric(options.getEnrollReason())); - setRequestId(requestId); - if (sidefpsControllerRefactor()) { - mSensorOverlays = new SensorOverlays(udfpsOverlayController); - } else { - mSensorOverlays = new SensorOverlays(udfpsOverlayController, sidefpsController); - } - mAuthenticationStateListeners = authenticationStateListeners; - - mEnrollReason = enrollReason; - if (enrollReason == FingerprintManager.ENROLL_FIND_SENSOR) { - getLogger().disableMetrics(); - } - Slog.w(TAG, "EnrollOptions " - + FingerprintEnrollOptions.enrollReasonToString(options.getEnrollReason())); - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - - BiometricNotificationUtils.cancelFingerprintEnrollNotification(getContext()); - } - - @NonNull - @Override - protected ClientMonitorCallback wrapCallbackForStart(@NonNull ClientMonitorCallback callback) { - return new ClientMonitorCompositeCallback( - getLogger().getAmbientLightProbe(true /* startWithClient */), callback); - } - - @Override - protected boolean hasReachedEnrollmentLimit() { - final int limit = getContext().getResources().getInteger( - com.android.internal.R.integer.config_fingerprintMaxTemplatesPerUser); - final int enrolled = mBiometricUtils.getBiometricsForUser(getContext(), getTargetUserId()) - .size(); - if (enrolled >= limit) { - Slog.w(TAG, "Too many fingerprints registered, user: " + getTargetUserId()); - return true; - } - return false; - } - - @Override - protected void startHalOperation() { - mSensorOverlays.show(getSensorId(), getRequestReasonFromEnrollReason(mEnrollReason), - this); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStarted( - getRequestReasonFromEnrollReason(mEnrollReason)); - } - - BiometricNotificationUtils.cancelBadCalibrationNotification(getContext()); - try { - // GroupId was never used. In fact, groupId is always the same as userId. - getFreshDaemon().enroll(mHardwareAuthToken, getTargetUserId(), mTimeoutSec); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting enroll", e); - onError(BiometricFingerprintConstants.FINGERPRINT_ERROR_HW_UNAVAILABLE, - 0 /* vendorCode */); - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - protected void stopHalOperation() { - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - - try { - getFreshDaemon().cancel(); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting cancel", e); - onError(BiometricFingerprintConstants.FINGERPRINT_ERROR_HW_UNAVAILABLE, - 0 /* vendorCode */); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - public void onEnrollResult(BiometricAuthenticator.Identifier identifier, int remaining) { - super.onEnrollResult(identifier, remaining); - - mSensorOverlays.ifUdfps( - controller -> controller.onEnrollmentProgress(getSensorId(), remaining)); - - if (remaining == 0) { - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - } - } - - @Override - public void onAcquired(int acquiredInfo, int vendorCode) { - super.onAcquired(acquiredInfo, vendorCode); - - mSensorOverlays.ifUdfps(controller -> { - if (UdfpsHelper.isValidAcquisitionMessage(getContext(), acquiredInfo, vendorCode)) { - controller.onEnrollmentHelp(getSensorId()); - } - }); - - mCallback.onBiometricAction(BiometricStateListener.ACTION_SENSOR_TOUCH); - } - - @Override - public void onError(int errorCode, int vendorCode) { - super.onError(errorCode, vendorCode); - - mSensorOverlays.hide(getSensorId()); - if (sidefpsControllerRefactor()) { - mAuthenticationStateListeners.onAuthenticationStopped(); - } - } - - @Override - public void onPointerDown(PointerContext pc) { - mIsPointerDown = true; - UdfpsHelper.onFingerDown(getFreshDaemon(), (int) pc.x, (int) pc.y, pc.minor, pc.major); - } - - @Override - public void onPointerUp(PointerContext pc) { - mIsPointerDown = false; - UdfpsHelper.onFingerUp(getFreshDaemon()); - } - - @Override - public boolean isPointerDown() { - return mIsPointerDown; - } - - @Override - public void onUdfpsUiEvent(@FingerprintManager.UdfpsUiEvent int event) { - // Unsupported in HIDL. - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintGenerateChallengeClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintGenerateChallengeClient.java deleted file mode 100644 index 3bb7135a3e06..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintGenerateChallengeClient.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.GenerateChallengeClient; - -import java.util.function.Supplier; - -/** - * Fingerprint-specific generateChallenge/preEnroll client supporting the - * {@link android.hardware.biometrics.fingerprint.V2_1} and - * {@link android.hardware.biometrics.fingerprint.V2_2} HIDL interfaces. - */ -public class FingerprintGenerateChallengeClient - extends GenerateChallengeClient<IBiometricsFingerprint> { - - private static final String TAG = "FingerprintGenerateChallengeClient"; - - FingerprintGenerateChallengeClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, @NonNull IBinder token, - @NonNull ClientMonitorCallbackConverter listener, int userId, @NonNull String owner, - int sensorId, @NonNull BiometricLogger logger, - @NonNull BiometricContext biometricContext) { - super(context, lazyDaemon, token, listener, userId, owner, sensorId, logger, - biometricContext); - } - - @Override - protected void startHalOperation() { - try { - final long challenge = getFreshDaemon().preEnroll(); - try { - getListener().onChallengeGenerated(getSensorId(), getTargetUserId(), challenge); - mCallback.onClientFinished(this, true /* success */); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception", e); - mCallback.onClientFinished(this, false /* success */); - } - } catch (RemoteException e) { - Slog.e(TAG, "preEnroll failed", e); - mCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintInternalCleanupClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintInternalCleanupClient.java deleted file mode 100644 index 8b61f5966c14..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintInternalCleanupClient.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.hardware.fingerprint.Fingerprint; -import android.os.IBinder; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.BiometricUtils; -import com.android.server.biometrics.sensors.InternalCleanupClient; -import com.android.server.biometrics.sensors.InternalEnumerateClient; -import com.android.server.biometrics.sensors.RemovalClient; - -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -/** - * Fingerprint-specific internal cleanup client supporting the - * {@link android.hardware.biometrics.fingerprint.V2_1} and - * {@link android.hardware.biometrics.fingerprint.V2_2} HIDL interfaces. - */ -class FingerprintInternalCleanupClient - extends InternalCleanupClient<Fingerprint, IBiometricsFingerprint> { - - FingerprintInternalCleanupClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, int userId, - @NonNull String owner, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - @NonNull BiometricUtils<Fingerprint> utils, - @NonNull Map<Integer, Long> authenticatorIds) { - super(context, lazyDaemon, userId, owner, sensorId, logger, biometricContext, - utils, authenticatorIds); - } - - @Override - protected InternalEnumerateClient<IBiometricsFingerprint> getEnumerateClient( - Context context, Supplier<IBiometricsFingerprint> lazyDaemon, IBinder token, - int userId, String owner, List<Fingerprint> enrolledList, - BiometricUtils<Fingerprint> utils, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext) { - return new FingerprintInternalEnumerateClient(context, lazyDaemon, token, userId, owner, - enrolledList, utils, sensorId, logger, biometricContext); - } - - @Override - protected RemovalClient<Fingerprint, IBiometricsFingerprint> getRemovalClient(Context context, - Supplier<IBiometricsFingerprint> lazyDaemon, IBinder token, - int biometricId, int userId, String owner, BiometricUtils<Fingerprint> utils, - int sensorId, @NonNull BiometricLogger logger, - @NonNull BiometricContext biometricContext, Map<Integer, Long> authenticatorIds) { - // Internal remove does not need to send results to anyone. Cleanup (enumerate + remove) - // is all done internally. - return new FingerprintRemovalClient(context, lazyDaemon, token, - null /* ClientMonitorCallbackConverter */, biometricId, userId, owner, utils, - sensorId, logger, biometricContext, authenticatorIds); - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintInternalEnumerateClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintInternalEnumerateClient.java deleted file mode 100644 index 0840f1b36903..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintInternalEnumerateClient.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.hardware.fingerprint.Fingerprint; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.BiometricUtils; -import com.android.server.biometrics.sensors.InternalEnumerateClient; - -import java.util.List; -import java.util.function.Supplier; - -/** - * Fingerprint-specific internal enumerate client supporting the - * {@link android.hardware.biometrics.fingerprint.V2_1} and - * {@link android.hardware.biometrics.fingerprint.V2_2} HIDL interfaces. - */ -class FingerprintInternalEnumerateClient extends InternalEnumerateClient<IBiometricsFingerprint> { - private static final String TAG = "FingerprintInternalEnumerateClient"; - - FingerprintInternalEnumerateClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, @NonNull IBinder token, - int userId, @NonNull String owner, @NonNull List<Fingerprint> enrolledList, - @NonNull BiometricUtils<Fingerprint> utils, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext) { - super(context, lazyDaemon, token, userId, owner, enrolledList, utils, sensorId, - logger, biometricContext); - } - - @Override - protected void startHalOperation() { - try { - getFreshDaemon().enumerate(); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting enumerate", e); - mCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintRemovalClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintRemovalClient.java deleted file mode 100644 index 9ec56c2a7dcd..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintRemovalClient.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.hardware.fingerprint.Fingerprint; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.BiometricUtils; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; -import com.android.server.biometrics.sensors.RemovalClient; - -import java.util.Map; -import java.util.function.Supplier; - -/** - * Fingerprint-specific removal client supporting the - * {@link android.hardware.biometrics.fingerprint.V2_1} and - * {@link android.hardware.biometrics.fingerprint.V2_2} HIDL interfaces. - */ -class FingerprintRemovalClient extends RemovalClient<Fingerprint, IBiometricsFingerprint> { - private static final String TAG = "FingerprintRemovalClient"; - - private final int mBiometricId; - - FingerprintRemovalClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, @NonNull IBinder token, - @NonNull ClientMonitorCallbackConverter listener, int biometricId, int userId, - @NonNull String owner, @NonNull BiometricUtils<Fingerprint> utils, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - @NonNull Map<Integer, Long> authenticatorIds) { - super(context, lazyDaemon, token, listener, userId, owner, utils, sensorId, - logger, biometricContext, authenticatorIds); - mBiometricId = biometricId; - } - - @Override - protected void startHalOperation() { - try { - // GroupId was never used. In fact, groupId is always the same as userId. - getFreshDaemon().remove(getTargetUserId(), mBiometricId); - } catch (RemoteException e) { - Slog.e(TAG, "Remote exception when requesting remove", e); - mCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintResetLockoutClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintResetLockoutClient.java deleted file mode 100644 index 843fcc8ee2a6..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintResetLockoutClient.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.content.Context; - -import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.BaseClientMonitor; -import com.android.server.biometrics.sensors.ClientMonitorCallback; - -/** - * Clears lockout, which is handled in the framework (and not the HAL) for the - * IBiometricsFingerprint@2.1 interface. - */ -public class FingerprintResetLockoutClient extends BaseClientMonitor { - - @NonNull final LockoutFrameworkImpl mLockoutTracker; - - public FingerprintResetLockoutClient(@NonNull Context context, int userId, - @NonNull String owner, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - @NonNull LockoutFrameworkImpl lockoutTracker) { - super(context, null /* token */, null /* listener */, userId, owner, 0 /* cookie */, - sensorId, logger, biometricContext); - mLockoutTracker = lockoutTracker; - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - mLockoutTracker.resetFailedAttemptsForUser(true /* clearAttemptCounter */, - getTargetUserId()); - callback.onClientFinished(this, true /* success */); - } - - public boolean interruptsPrecedingClients() { - return true; - } - - @Override - public int getProtoEnum() { - return BiometricsProto.CM_RESET_LOCKOUT; - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintRevokeChallengeClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintRevokeChallengeClient.java deleted file mode 100644 index 6273417eb0db..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintRevokeChallengeClient.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Slog; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.RevokeChallengeClient; - -import java.util.function.Supplier; - -/** - * Fingerprint-specific revokeChallenge client supporting the - * {@link android.hardware.biometrics.fingerprint.V2_1} and - * {@link android.hardware.biometrics.fingerprint.V2_2} HIDL interfaces. - */ -public class FingerprintRevokeChallengeClient - extends RevokeChallengeClient<IBiometricsFingerprint> { - - private static final String TAG = "FingerprintRevokeChallengeClient"; - - FingerprintRevokeChallengeClient(@NonNull Context context, - @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, @NonNull IBinder token, - int userId, @NonNull String owner, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext) { - super(context, lazyDaemon, token, userId, owner, sensorId, logger, biometricContext); - } - - @Override - protected void startHalOperation() { - try { - getFreshDaemon().postEnroll(); - mCallback.onClientFinished(this, true /* success */); - } catch (RemoteException e) { - Slog.e(TAG, "revokeChallenge/postEnroll failed", e); - mCallback.onClientFinished(this, false /* success */); - } - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintUpdateActiveUserClientLegacy.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintUpdateActiveUserClientLegacy.java deleted file mode 100644 index fc85402edef4..000000000000 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintUpdateActiveUserClientLegacy.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2024 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import android.annotation.NonNull; -import android.content.Context; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.os.Build; -import android.os.Environment; -import android.os.RemoteException; -import android.os.SELinux; -import android.util.Slog; - -import com.android.server.biometrics.BiometricsProto; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.HalClientMonitor; - -import java.io.File; -import java.util.Map; -import java.util.function.Supplier; - -/** - * TODO(b/304604965): Delete this class once Flags.DE_HIDL is ready for release. - */ -public class FingerprintUpdateActiveUserClientLegacy extends - HalClientMonitor<IBiometricsFingerprint> { - private static final String TAG = "FingerprintUpdateActiveUserClient"; - private static final String FP_DATA_DIR = "fpdata"; - - private final Supplier<Integer> mCurrentUserId; - private final boolean mForceUpdateAuthenticatorId; - private final boolean mHasEnrolledBiometrics; - private final Map<Integer, Long> mAuthenticatorIds; - private File mDirectory; - - FingerprintUpdateActiveUserClientLegacy(@NonNull Context context, - @NonNull Supplier<IBiometricsFingerprint> lazyDaemon, int userId, - @NonNull String owner, int sensorId, - @NonNull BiometricLogger logger, @NonNull BiometricContext biometricContext, - @NonNull Supplier<Integer> currentUserId, - boolean hasEnrolledBiometrics, @NonNull Map<Integer, Long> authenticatorIds, - boolean forceUpdateAuthenticatorId) { - super(context, lazyDaemon, null /* token */, null /* listener */, userId, owner, - 0 /* cookie */, sensorId, logger, biometricContext); - mCurrentUserId = currentUserId; - mForceUpdateAuthenticatorId = forceUpdateAuthenticatorId; - mHasEnrolledBiometrics = hasEnrolledBiometrics; - mAuthenticatorIds = authenticatorIds; - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - - if (mCurrentUserId.get() == getTargetUserId() && !mForceUpdateAuthenticatorId) { - Slog.d(TAG, "Already user: " + mCurrentUserId + ", returning"); - callback.onClientFinished(this, true /* success */); - return; - } - - int firstSdkInt = Build.VERSION.DEVICE_INITIAL_SDK_INT; - if (firstSdkInt < Build.VERSION_CODES.BASE) { - Slog.e(TAG, "First SDK version " + firstSdkInt + " is invalid; must be " - + "at least VERSION_CODES.BASE"); - } - File baseDir; - if (firstSdkInt <= Build.VERSION_CODES.O_MR1) { - baseDir = Environment.getUserSystemDirectory(getTargetUserId()); - } else { - baseDir = Environment.getDataVendorDeDirectory(getTargetUserId()); - } - - mDirectory = new File(baseDir, FP_DATA_DIR); - if (!mDirectory.exists()) { - if (!mDirectory.mkdir()) { - Slog.e(TAG, "Cannot make directory: " + mDirectory.getAbsolutePath()); - callback.onClientFinished(this, false /* success */); - return; - } - // Calling mkdir() from this process will create a directory with our - // permissions (inherited from the containing dir). This command fixes - // the label. - if (!SELinux.restorecon(mDirectory)) { - Slog.e(TAG, "Restorecons failed. Directory will have wrong label."); - callback.onClientFinished(this, false /* success */); - return; - } - } - - startHalOperation(); - } - - @Override - public void unableToStart() { - // Nothing to do here - } - - @Override - protected void startHalOperation() { - try { - final int targetId = getTargetUserId(); - Slog.d(TAG, "Setting active user: " + targetId); - getFreshDaemon().setActiveGroup(targetId, mDirectory.getAbsolutePath()); - mAuthenticatorIds.put(targetId, mHasEnrolledBiometrics - ? getFreshDaemon().getAuthenticatorId() : 0L); - mCallback.onClientFinished(this, true /* success */); - } catch (RemoteException e) { - Slog.e(TAG, "Failed to setActiveGroup: " + e); - mCallback.onClientFinished(this, false /* success */); - } - } - - @Override - public int getProtoEnum() { - return BiometricsProto.CM_UPDATE_ACTIVE_USER; - } -} diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/HidlToAidlSensorAdapter.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/HidlToAidlSensorAdapter.java index 47fdcdb92a99..3214b6d3363f 100644 --- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/HidlToAidlSensorAdapter.java +++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/HidlToAidlSensorAdapter.java @@ -186,7 +186,7 @@ public class HidlToAidlSensorAdapter extends Sensor implements IHwBinder.DeathRe mLockoutTracker, mLockoutResetDispatcher, mAuthSessionCoordinator, - () -> {}, mAidlResponseHandlerCallback); + mAidlResponseHandlerCallback); } @VisibleForTesting IBiometricsFingerprint getIBiometricsFingerprint() { diff --git a/services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java index 7e04277fddc0..90b131a80b2e 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java @@ -16,10 +16,10 @@ package com.android.server.biometrics; -import static android.adaptiveauth.Flags.FLAG_REPORT_BIOMETRIC_AUTH_ATTEMPTS; import static android.Manifest.permission.MANAGE_BIOMETRIC; import static android.Manifest.permission.TEST_BIOMETRIC; import static android.Manifest.permission.USE_BIOMETRIC_INTERNAL; +import static android.adaptiveauth.Flags.FLAG_REPORT_BIOMETRIC_AUTH_ATTEMPTS; import static android.hardware.biometrics.BiometricAuthenticator.TYPE_NONE; import static android.hardware.biometrics.BiometricConstants.BIOMETRIC_ERROR_CANCELED; import static android.hardware.biometrics.BiometricConstants.BIOMETRIC_SUCCESS; @@ -65,8 +65,6 @@ import android.os.RemoteException; import android.os.UserHandle; import android.os.test.TestLooper; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.platform.test.flag.junit.SetFlagsRule; @@ -204,43 +202,7 @@ public class AuthServiceTest { } @Test - @RequiresFlagsDisabled(com.android.server.biometrics.Flags.FLAG_DE_HIDL) - public void testRegisterAuthenticator_registerAuthenticators() throws Exception { - final int fingerprintId = 0; - final int fingerprintStrength = 15; - - final int faceId = 1; - final int faceStrength = 15; - - final String[] config = { - // ID0:Fingerprint:Strong - String.format("%d:2:%d", fingerprintId, fingerprintStrength), - // ID2:Face:Convenience - String.format("%d:8:%d", faceId, faceStrength) - }; - - when(mInjector.getConfiguration(any())).thenReturn(config); - - mAuthService = new AuthService(mContext, mInjector); - mAuthService.onStart(); - - verify(mFingerprintService).registerAuthenticators(mFingerprintPropsCaptor.capture()); - final FingerprintSensorPropertiesInternal fingerprintProp = - mFingerprintPropsCaptor.getValue().get(0); - assertEquals(fingerprintProp.sensorId, fingerprintId); - assertEquals(fingerprintProp.sensorStrength, - Utils.authenticatorStrengthToPropertyStrength(fingerprintStrength)); - - verify(mFaceService).registerAuthenticators(mFacePropsCaptor.capture()); - final FaceSensorPropertiesInternal faceProp = mFacePropsCaptor.getValue().get(0); - assertEquals(faceProp.sensorId, faceId); - assertEquals(faceProp.sensorStrength, - Utils.authenticatorStrengthToPropertyStrength(faceStrength)); - } - - @Test - @RequiresFlagsEnabled(com.android.server.biometrics.Flags.FLAG_DE_HIDL) - public void testRegisterAuthenticator_registerAuthenticatorsLegacy() throws RemoteException { + public void testRegisterAuthenticator_registerAuthenticators() throws RemoteException { final int fingerprintId = 0; final int fingerprintStrength = 15; @@ -265,7 +227,7 @@ public class AuthServiceTest { mFingerprintLooper.dispatchAll(); mFaceLooper.dispatchAll(); - verify(mFingerprintService).registerAuthenticatorsLegacy( + verify(mFingerprintService).registerAuthenticators( mFingerprintSensorConfigurationsCaptor.capture()); final SensorProps[] fingerprintProp = mFingerprintSensorConfigurationsCaptor.getValue() @@ -275,8 +237,7 @@ public class AuthServiceTest { assertEquals(fingerprintProp[0].commonProps.sensorStrength, Utils.authenticatorStrengthToPropertyStrength(fingerprintStrength)); - verify(mFaceService).registerAuthenticatorsLegacy( - mFaceSensorConfigurationsCaptor.capture()); + verify(mFaceService).registerAuthenticators(mFaceSensorConfigurationsCaptor.capture()); final android.hardware.biometrics.face.SensorProps[] faceProp = mFaceSensorConfigurationsCaptor.getValue() diff --git a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java index 5fd29c2b0cb9..503ab8e60cac 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java @@ -76,7 +76,6 @@ import android.hardware.keymaster.HardwareAuthenticatorType; import android.os.Binder; import android.os.Handler; import android.os.IBinder; -import android.os.Looper; import android.os.RemoteException; import android.os.UserManager; import android.platform.test.annotations.Presubmit; @@ -90,7 +89,6 @@ import android.view.Display; import android.view.DisplayInfo; import android.view.WindowManager; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; import com.android.internal.R; @@ -246,14 +244,8 @@ public class BiometricServiceTest { when(mInjector.getGateKeeperService()).thenReturn(mGateKeeperService); when(mInjector.getNotificationLogger()).thenReturn(mNotificationLogger); when(mGateKeeperService.getSecureUserId(anyInt())).thenReturn(42L); - - if (com.android.server.biometrics.Flags.deHidl()) { - when(mBiometricHandlerProvider.getBiometricCallbackHandler()).thenReturn( - new Handler(TestableLooper.get(this).getLooper())); - } else { - when(mBiometricHandlerProvider.getBiometricCallbackHandler()).thenReturn( - new Handler(Looper.getMainLooper())); - } + when(mBiometricHandlerProvider.getBiometricCallbackHandler()).thenReturn( + new Handler(TestableLooper.get(this).getLooper())); final String[] config = { "0:2:15", // ID0:Fingerprint:Strong @@ -2037,11 +2029,7 @@ public class BiometricServiceTest { } private void waitForIdle() { - if (com.android.server.biometrics.Flags.deHidl()) { - TestableLooper.get(this).processAllMessages(); - } else { - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); - } + TestableLooper.get(this).processAllMessages(); } private byte[] generateRandomHAT() { diff --git a/services/tests/servicestests/src/com/android/server/biometrics/log/BiometricContextProviderTest.java b/services/tests/servicestests/src/com/android/server/biometrics/log/BiometricContextProviderTest.java index c7300bbb50a7..960357f41afe 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/log/BiometricContextProviderTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/log/BiometricContextProviderTest.java @@ -87,8 +87,12 @@ public class BiometricContextProviderTest { private ISessionListener mSessionListener; @Mock private WindowManager mWindowManager; + @Mock + private Consumer<OperationContext> mStartHalConsumer; - private OperationContextExt mOpContext = new OperationContextExt(true); + private final FingerprintAuthenticateOptions mAuthenticateOptions = + new FingerprintAuthenticateOptions.Builder().build(); + private final OperationContextExt mOpContext = new OperationContextExt(true); private IBiometricContextListener mListener; private BiometricContextProvider mProvider; @@ -200,11 +204,11 @@ public class BiometricContextProviderTest { final List<Integer> actual = new ArrayList<>(); final List<Integer> expected = List.of(FoldState.FULLY_CLOSED, FoldState.FULLY_OPENED, FoldState.UNKNOWN, FoldState.HALF_OPENED); - mProvider.subscribe(mOpContext, ctx -> { + mProvider.subscribe(mOpContext, mStartHalConsumer, ctx -> { assertThat(ctx).isSameInstanceAs(mOpContext.toAidlContext()); assertThat(mProvider.getFoldState()).isEqualTo(ctx.foldState); actual.add(ctx.foldState); - }); + }, mAuthenticateOptions); for (int v : expected) { mListener.onFoldChanged(v); @@ -228,11 +232,11 @@ public class BiometricContextProviderTest { AuthenticateOptions.DISPLAY_STATE_NO_UI, AuthenticateOptions.DISPLAY_STATE_LOCKSCREEN); - mProvider.subscribe(mOpContext, ctx -> { + mProvider.subscribe(mOpContext, mStartHalConsumer, ctx -> { assertThat(ctx).isSameInstanceAs(mOpContext.toAidlContext()); assertThat(mProvider.getDisplayState()).isEqualTo(ctx.displayState); actual.add(ctx.displayState); - }); + }, mAuthenticateOptions); for (int v : expected) { mListener.onDisplayStateChanged(v); @@ -250,11 +254,11 @@ public class BiometricContextProviderTest { public void testSubscribesToAod() throws RemoteException { final List<Boolean> actual = new ArrayList<>(); - mProvider.subscribe(mOpContext, ctx -> { + mProvider.subscribe(mOpContext, mStartHalConsumer, ctx -> { assertThat(ctx).isSameInstanceAs(mOpContext.toAidlContext()); assertThat(mProvider.isAod()).isEqualTo(ctx.isAod); actual.add(ctx.isAod); - }); + }, mAuthenticateOptions); for (int v : List.of( AuthenticateOptions.DISPLAY_STATE_AOD, @@ -273,10 +277,10 @@ public class BiometricContextProviderTest { public void testSubscribesToAwake() throws RemoteException { final List<Boolean> actual = new ArrayList<>(); - mProvider.subscribe(mOpContext, ctx -> { + mProvider.subscribe(mOpContext, mStartHalConsumer, ctx -> { assertThat(ctx).isSameInstanceAs(mOpContext.toAidlContext()); actual.add(mProvider.isAwake()); - }); + }, mAuthenticateOptions); for (int v : List.of( AuthenticateOptions.DISPLAY_STATE_LOCKSCREEN, @@ -295,14 +299,15 @@ public class BiometricContextProviderTest { public void testSubscribesWithDifferentState() throws RemoteException { final Consumer<OperationContext> nonEmptyConsumer = mock(Consumer.class); mListener.onDisplayStateChanged(AuthenticateOptions.DISPLAY_STATE_AOD); - mProvider.subscribe(mOpContext, nonEmptyConsumer); - verify(nonEmptyConsumer).accept(same(mOpContext.toAidlContext())); + mProvider.subscribe(mOpContext, mStartHalConsumer, nonEmptyConsumer, mAuthenticateOptions); + + assertThat(mOpContext.getDisplayState()).isEqualTo(AuthenticateOptions.DISPLAY_STATE_AOD); } @Test public void testUnsubscribes() throws RemoteException { final Consumer<OperationContext> emptyConsumer = mock(Consumer.class); - mProvider.subscribe(mOpContext, emptyConsumer); + mProvider.subscribe(mOpContext, mStartHalConsumer, emptyConsumer, mAuthenticateOptions); mProvider.unsubscribe(mOpContext); mListener.onDisplayStateChanged(AuthenticateOptions.DISPLAY_STATE_AOD); @@ -311,7 +316,7 @@ public class BiometricContextProviderTest { mListener.onDisplayStateChanged(AuthenticateOptions.DISPLAY_STATE_UNKNOWN); final Consumer<OperationContext> nonEmptyConsumer = mock(Consumer.class); - mProvider.subscribe(mOpContext, nonEmptyConsumer); + mProvider.subscribe(mOpContext, mStartHalConsumer, nonEmptyConsumer, mAuthenticateOptions); mListener.onDisplayStateChanged(AuthenticateOptions.DISPLAY_STATE_LOCKSCREEN); mProvider.unsubscribe(mOpContext); mListener.onDisplayStateChanged(AuthenticateOptions.DISPLAY_STATE_NO_UI); diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/BiometricSchedulerTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/BiometricSchedulerTest.java index 971323ac567a..fc573d243129 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/BiometricSchedulerTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/BiometricSchedulerTest.java @@ -52,13 +52,12 @@ import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.os.UserHandle; +import android.os.test.TestLooper; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.testing.AndroidTestingRunner; import android.testing.TestableContext; -import android.testing.TestableLooper; import android.util.Slog; import androidx.annotation.NonNull; @@ -66,7 +65,6 @@ import androidx.annotation.Nullable; import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.nano.BiometricSchedulerProto; @@ -79,7 +77,8 @@ import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; import java.util.ArrayList; import java.util.HashMap; @@ -90,7 +89,6 @@ import java.util.function.Supplier; @Presubmit @SmallTest @RunWith(AndroidTestingRunner.class) -@TestableLooper.RunWithLooper(setAsMainLooper = true) public class BiometricSchedulerTest { private static final String TAG = "BiometricSchedulerTest"; @@ -105,6 +103,9 @@ public class BiometricSchedulerTest { @Rule public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule(); + @Rule + public final MockitoRule mockito = MockitoJUnit.rule(); + private BiometricScheduler<IFingerprint, ISession> mScheduler; private IBinder mToken; private int mCurrentUserId = UserHandle.USER_SYSTEM; @@ -121,8 +122,10 @@ public class BiometricSchedulerTest { mUsersStoppedCount++; mCurrentUserId = UserHandle.USER_NULL; }; + private TestLooper mLooper; private boolean mStartOperationsFinish = true; private int mStartUserClientCount = 0; + @Mock private IBiometricService mBiometricService; @Mock @@ -140,44 +143,39 @@ public class BiometricSchedulerTest { @Before public void setUp() { - MockitoAnnotations.initMocks(this); mToken = new Binder(); + mLooper = new TestLooper(); + when(mAuthSessionCoordinator.getLockoutStateFor(anyInt(), anyInt())).thenReturn( BIOMETRIC_SUCCESS); when(mBiometricContext.getAuthSessionCoordinator()).thenReturn(mAuthSessionCoordinator); - if (Flags.deHidl()) { - mScheduler = new BiometricScheduler<>( - new Handler(TestableLooper.get(this).getLooper()), - BiometricScheduler.SENSOR_TYPE_UNKNOWN, - null /* gestureAvailabilityDispatcher */, - mBiometricService, - LOG_NUM_RECENT_OPERATIONS, - () -> mCurrentUserId, - new UserSwitchProvider<IFingerprint, ISession>() { - @NonNull - @Override - public StopUserClient<ISession> getStopUserClient(int userId) { - return new TestStopUserClient(mContext, () -> mSession, mToken, userId, - TEST_SENSOR_ID, mBiometricLogger, mBiometricContext, - mUserStoppedCallback, () -> mShouldFailStopUser); - } - - @NonNull - @Override - public StartUserClient<IFingerprint, ISession> getStartUserClient( - int newUserId) { - mStartUserClientCount++; - return new TestStartUserClient(mContext, () -> mFingerprint, mToken, - newUserId, TEST_SENSOR_ID, mBiometricLogger, mBiometricContext, - mUserStartedCallback, mStartOperationsFinish); - } - }); - } else { - mScheduler = new BiometricScheduler<>( - new Handler(TestableLooper.get(this).getLooper()), - BiometricScheduler.SENSOR_TYPE_UNKNOWN, null /* gestureAvailabilityTracker */, - mBiometricService, LOG_NUM_RECENT_OPERATIONS); - } + + mScheduler = new BiometricScheduler<>( + new Handler(mLooper.getLooper()), + BiometricScheduler.SENSOR_TYPE_UNKNOWN, + null /* gestureAvailabilityDispatcher */, + mBiometricService, + LOG_NUM_RECENT_OPERATIONS, + () -> mCurrentUserId, + new UserSwitchProvider<IFingerprint, ISession>() { + @NonNull + @Override + public StopUserClient<ISession> getStopUserClient(int userId) { + return new TestStopUserClient(mContext, () -> mSession, mToken, userId, + TEST_SENSOR_ID, mBiometricLogger, mBiometricContext, + mUserStoppedCallback, () -> mShouldFailStopUser); + } + + @NonNull + @Override + public StartUserClient<IFingerprint, ISession> getStartUserClient( + int newUserId) { + mStartUserClientCount++; + return new TestStartUserClient(mContext, () -> mFingerprint, mToken, + newUserId, TEST_SENSOR_ID, mBiometricLogger, mBiometricContext, + mUserStartedCallback, mStartOperationsFinish); + } + }); } @Test @@ -657,7 +655,6 @@ public class BiometricSchedulerTest { @Test public void testClearBiometricQueue_clearsHungAuthOperation() { // Creating a hung client - final TestableLooper looper = TestableLooper.get(this); final Supplier<Object> lazyDaemon1 = () -> mock(Object.class); final TestAuthenticationClient client1 = new TestAuthenticationClient(mContext, lazyDaemon1, mToken, mock(ClientMonitorCallbackConverter.class), 0 /* cookie */, @@ -676,9 +673,9 @@ public class BiometricSchedulerTest { assertNotNull(mScheduler.mCurrentOperation); assertEquals(0, mScheduler.getCurrentPendingCount()); - looper.moveTimeForward(10000); + mLooper.moveTimeForward(10000); waitForIdle(); - looper.moveTimeForward(3000); + mLooper.moveTimeForward(3000); waitForIdle(); // The hung client did not honor this operation, verify onError and authenticated @@ -693,7 +690,6 @@ public class BiometricSchedulerTest { @Test public void testAuthWorks_afterClearBiometricQueue() { // Creating a hung client - final TestableLooper looper = TestableLooper.get(this); final Supplier<Object> lazyDaemon1 = () -> mock(Object.class); final TestAuthenticationClient client1 = new TestAuthenticationClient(mContext, lazyDaemon1, mToken, mock(ClientMonitorCallbackConverter.class), 0 /* cookie */, @@ -714,10 +710,10 @@ public class BiometricSchedulerTest { waitForIdle(); // The watchdog should kick off the cancellation - looper.moveTimeForward(10000); + mLooper.moveTimeForward(10000); waitForIdle(); // After 10 seconds the HAL has 3 seconds to respond to a cancel - looper.moveTimeForward(3000); + mLooper.moveTimeForward(3000); waitForIdle(); // The hung client did not honor this operation, verify onError and authenticated @@ -752,10 +748,10 @@ public class BiometricSchedulerTest { client2.getCallback().onClientFinished(client2, true); waitForIdle(); - looper.moveTimeForward(10000); + mLooper.moveTimeForward(10000); waitForIdle(); // After 10 seconds the HAL has 3 seconds to respond to a cancel - looper.moveTimeForward(3000); + mLooper.moveTimeForward(3000); waitForIdle(); //Asserting auth client passes @@ -766,7 +762,6 @@ public class BiometricSchedulerTest { @Test public void testClearBiometricQueue_doesNotClearOperationsWhenQueueNotStuck() { //Creating clients - final TestableLooper looper = TestableLooper.get(this); final Supplier<Object> lazyDaemon1 = () -> mock(Object.class); final TestAuthenticationClient client1 = new TestAuthenticationClient(mContext, lazyDaemon1, mToken, mock(ClientMonitorCallbackConverter.class), 0 /* cookie */, @@ -793,10 +788,10 @@ public class BiometricSchedulerTest { waitForIdle(); // The watchdog should kick off the cancellation - looper.moveTimeForward(10000); + mLooper.moveTimeForward(10000); waitForIdle(); // After 10 seconds the HAL has 3 seconds to respond to a cancel - looper.moveTimeForward(3000); + mLooper.moveTimeForward(3000); waitForIdle(); //Watchdog does not clear pending operations @@ -855,7 +850,6 @@ public class BiometricSchedulerTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testScheduleOperation_whenNoUser() { mCurrentUserId = UserHandle.USER_NULL; @@ -871,7 +865,6 @@ public class BiometricSchedulerTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testScheduleOperation_whenNoUser_notStarted() { mCurrentUserId = UserHandle.USER_NULL; mStartOperationsFinish = false; @@ -896,7 +889,6 @@ public class BiometricSchedulerTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testScheduleOperation_whenNoUser_notStarted_andReset() { mCurrentUserId = UserHandle.USER_NULL; mStartOperationsFinish = false; @@ -923,7 +915,6 @@ public class BiometricSchedulerTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testScheduleOperation_whenSameUser() { mCurrentUserId = 10; @@ -940,7 +931,6 @@ public class BiometricSchedulerTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testScheduleOperation_whenDifferentUser() { mCurrentUserId = 10; @@ -961,7 +951,6 @@ public class BiometricSchedulerTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testStartUser_alwaysStartsNextOperation() { mCurrentUserId = UserHandle.USER_NULL; @@ -990,7 +979,6 @@ public class BiometricSchedulerTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testStartUser_failsClearsStopUserClient() { mCurrentUserId = UserHandle.USER_NULL; @@ -1033,7 +1021,7 @@ public class BiometricSchedulerTest { } private void waitForIdle() { - TestableLooper.get(this).processAllMessages(); + mLooper.dispatchAll(); } private static class TestAuthenticateOptions implements AuthenticateOptions { diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/UserAwareBiometricSchedulerTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/UserAwareBiometricSchedulerTest.java deleted file mode 100644 index dd5d826b1739..000000000000 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/UserAwareBiometricSchedulerTest.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors; - -import static android.testing.TestableLooper.RunWithLooper; - -import static com.google.common.truth.Truth.assertThat; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.content.Context; -import android.hardware.biometrics.IBiometricService; -import android.os.Binder; -import android.os.Handler; -import android.os.IBinder; -import android.os.UserHandle; -import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.flag.junit.CheckFlagsRule; -import android.platform.test.flag.junit.DeviceFlagsValueProvider; -import android.testing.AndroidTestingRunner; -import android.testing.TestableLooper; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.test.filters.SmallTest; - -import com.android.server.biometrics.Flags; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -@Presubmit -@RunWith(AndroidTestingRunner.class) -@RunWithLooper -@SmallTest -public class UserAwareBiometricSchedulerTest { - - private static final String TAG = "UserAwareBiometricSchedulerTest"; - private static final int TEST_SENSOR_ID = 0; - - @Rule - public final MockitoRule mockito = MockitoJUnit.rule(); - @Rule - public final CheckFlagsRule mCheckFlagsRule = - DeviceFlagsValueProvider.createCheckFlagsRule(); - - private Handler mHandler; - private UserAwareBiometricScheduler mScheduler; - private final IBinder mToken = new Binder(); - - @Mock - private Context mContext; - @Mock - private IBiometricService mBiometricService; - @Mock - private BiometricLogger mBiometricLogger; - @Mock - private BiometricContext mBiometricContext; - - private boolean mShouldFailStopUser = false; - private final StopUserClientShouldFail mStopUserClientShouldFail = - () -> { - return mShouldFailStopUser; - }; - private final TestUserStartedCallback mUserStartedCallback = new TestUserStartedCallback(); - private final TestUserStoppedCallback mUserStoppedCallback = new TestUserStoppedCallback(); - private int mCurrentUserId = UserHandle.USER_NULL; - private boolean mStartOperationsFinish = true; - private int mStartUserClientCount = 0; - - @Before - public void setUp() { - mShouldFailStopUser = false; - mHandler = new Handler(TestableLooper.get(this).getLooper()); - mScheduler = new UserAwareBiometricScheduler(TAG, - mHandler, - BiometricScheduler.SENSOR_TYPE_UNKNOWN, - null /* gestureAvailabilityDispatcher */, - mBiometricService, - () -> mCurrentUserId, - new UserAwareBiometricScheduler.UserSwitchCallback() { - @NonNull - @Override - public StopUserClient<?> getStopUserClient(int userId) { - return new TestStopUserClient(mContext, Object::new, mToken, userId, - TEST_SENSOR_ID, mBiometricLogger, mBiometricContext, - mUserStoppedCallback, mStopUserClientShouldFail); - } - - @NonNull - @Override - public StartUserClient<?, ?> getStartUserClient(int newUserId) { - mStartUserClientCount++; - return new TestStartUserClient(mContext, Object::new, mToken, newUserId, - TEST_SENSOR_ID, mBiometricLogger, mBiometricContext, - mUserStartedCallback, mStartOperationsFinish); - } - }); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void testScheduleOperation_whenNoUser() { - mCurrentUserId = UserHandle.USER_NULL; - - final BaseClientMonitor nextClient = mock(BaseClientMonitor.class); - when(nextClient.getTargetUserId()).thenReturn(0); - - mScheduler.scheduleClientMonitor(nextClient); - waitForIdle(); - - assertThat(mUserStoppedCallback.mNumInvocations).isEqualTo(0); - assertThat(mUserStartedCallback.mStartedUsers).containsExactly(0); - verify(nextClient).start(any()); - } - - @Test - public void testScheduleOperation_whenNoUser_notStarted() { - mCurrentUserId = UserHandle.USER_NULL; - mStartOperationsFinish = false; - - final BaseClientMonitor[] nextClients = new BaseClientMonitor[]{ - mock(BaseClientMonitor.class), - mock(BaseClientMonitor.class), - mock(BaseClientMonitor.class) - }; - for (BaseClientMonitor client : nextClients) { - when(client.getTargetUserId()).thenReturn(5); - mScheduler.scheduleClientMonitor(client); - waitForIdle(); - } - - assertThat(mUserStoppedCallback.mNumInvocations).isEqualTo(0); - assertThat(mUserStartedCallback.mStartedUsers).isEmpty(); - assertThat(mStartUserClientCount).isEqualTo(1); - for (BaseClientMonitor client : nextClients) { - verify(client, never()).start(any()); - } - } - - @Test - public void testScheduleOperation_whenNoUser_notStarted_andReset() { - mCurrentUserId = UserHandle.USER_NULL; - mStartOperationsFinish = false; - - final BaseClientMonitor client = mock(BaseClientMonitor.class); - when(client.getTargetUserId()).thenReturn(5); - mScheduler.scheduleClientMonitor(client); - waitForIdle(); - - final TestStartUserClient startUserClient = - (TestStartUserClient) mScheduler.mCurrentOperation.getClientMonitor(); - mScheduler.reset(); - assertThat(mScheduler.mCurrentOperation).isNull(); - - final BiometricSchedulerOperation fakeOperation = new BiometricSchedulerOperation( - mock(BaseClientMonitor.class), new ClientMonitorCallback() {}); - mScheduler.mCurrentOperation = fakeOperation; - startUserClient.mCallback.onClientFinished(startUserClient, true); - assertThat(fakeOperation).isSameInstanceAs(mScheduler.mCurrentOperation); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void testScheduleOperation_whenSameUser() { - mCurrentUserId = 10; - - BaseClientMonitor nextClient = mock(BaseClientMonitor.class); - when(nextClient.getTargetUserId()).thenReturn(mCurrentUserId); - - mScheduler.scheduleClientMonitor(nextClient); - - waitForIdle(); - - verify(nextClient).start(any()); - assertThat(mUserStoppedCallback.mNumInvocations).isEqualTo(0); - assertThat(mUserStartedCallback.mStartedUsers).isEmpty(); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void testScheduleOperation_whenDifferentUser() { - mCurrentUserId = 10; - - final int nextUserId = 11; - BaseClientMonitor nextClient = mock(BaseClientMonitor.class); - when(nextClient.getTargetUserId()).thenReturn(nextUserId); - - mScheduler.scheduleClientMonitor(nextClient); - - waitForIdle(); - assertThat(mUserStoppedCallback.mNumInvocations).isEqualTo(1); - - waitForIdle(); - assertThat(mUserStartedCallback.mStartedUsers).containsExactly(nextUserId); - - waitForIdle(); - verify(nextClient).start(any()); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void testStartUser_alwaysStartsNextOperation() { - BaseClientMonitor nextClient = mock(BaseClientMonitor.class); - when(nextClient.getTargetUserId()).thenReturn(10); - - mScheduler.scheduleClientMonitor(nextClient); - - waitForIdle(); - verify(nextClient).start(any()); - - // finish first operation - mScheduler.getInternalCallback().onClientFinished(nextClient, true /* success */); - waitForIdle(); - - // schedule second operation but swap out the current operation - // before it runs so that it's not current when it's completion callback runs - nextClient = mock(BaseClientMonitor.class); - when(nextClient.getTargetUserId()).thenReturn(11); - mUserStartedCallback.mAfterStart = () -> mScheduler.mCurrentOperation = null; - mScheduler.scheduleClientMonitor(nextClient); - - waitForIdle(); - verify(nextClient).start(any()); - assertThat(mUserStartedCallback.mStartedUsers).containsExactly(10, 11).inOrder(); - assertThat(mUserStoppedCallback.mNumInvocations).isEqualTo(1); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void testStartUser_failsClearsStopUserClient() { - // When a stop user client fails, check that mStopUserClient - // is set to null to prevent the scheduler from getting stuck. - BaseClientMonitor nextClient = mock(BaseClientMonitor.class); - when(nextClient.getTargetUserId()).thenReturn(10); - - mScheduler.scheduleClientMonitor(nextClient); - - waitForIdle(); - verify(nextClient).start(any()); - - // finish first operation - mScheduler.getInternalCallback().onClientFinished(nextClient, true /* success */); - waitForIdle(); - - // schedule second operation but swap out the current operation - // before it runs so that it's not current when it's completion callback runs - nextClient = mock(BaseClientMonitor.class); - when(nextClient.getTargetUserId()).thenReturn(11); - mUserStartedCallback.mAfterStart = () -> mScheduler.mCurrentOperation = null; - mShouldFailStopUser = true; - mScheduler.scheduleClientMonitor(nextClient); - - waitForIdle(); - assertThat(mUserStartedCallback.mStartedUsers).containsExactly(10, 11).inOrder(); - assertThat(mUserStoppedCallback.mNumInvocations).isEqualTo(0); - assertThat(mScheduler.getStopUserClient()).isEqualTo(null); - } - - private void waitForIdle() { - TestableLooper.get(this).processAllMessages(); - } - - private class TestUserStoppedCallback implements StopUserClient.UserStoppedCallback { - int mNumInvocations; - - @Override - public void onUserStopped() { - mNumInvocations++; - mCurrentUserId = UserHandle.USER_NULL; - } - } - - private class TestUserStartedCallback implements StartUserClient.UserStartedCallback<Object> { - final List<Integer> mStartedUsers = new ArrayList<>(); - Runnable mAfterStart = null; - - @Override - public void onUserStarted(int newUserId, Object newObject, int halInterfaceVersion) { - mStartedUsers.add(newUserId); - mCurrentUserId = newUserId; - if (mAfterStart != null) { - mAfterStart.run(); - } - } - } - - private interface StopUserClientShouldFail { - boolean shouldFail(); - } - - private class TestStopUserClient extends StopUserClient<Object> { - private StopUserClientShouldFail mShouldFailClient; - public TestStopUserClient(@NonNull Context context, - @NonNull Supplier<Object> lazyDaemon, @Nullable IBinder token, int userId, - int sensorId, @NonNull BiometricLogger logger, - @NonNull BiometricContext biometricContext, - @NonNull UserStoppedCallback callback, StopUserClientShouldFail shouldFail) { - super(context, lazyDaemon, token, userId, sensorId, logger, biometricContext, callback); - mShouldFailClient = shouldFail; - } - - @Override - protected void startHalOperation() { - - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - if (mShouldFailClient.shouldFail()) { - getCallback().onClientFinished(this, false /* success */); - // When the above fails, it means that the HAL has died, in this case we - // need to ensure the UserSwitchCallback correctly returns the NULL user handle. - mCurrentUserId = UserHandle.USER_NULL; - } else { - onUserStopped(); - } - } - - @Override - public void unableToStart() { - - } - } - - private static class TestStartUserClient extends StartUserClient<Object, Object> { - private final boolean mShouldFinish; - - ClientMonitorCallback mCallback; - - public TestStartUserClient(@NonNull Context context, - @NonNull Supplier<Object> lazyDaemon, @Nullable IBinder token, int userId, - int sensorId, @NonNull BiometricLogger logger, - @NonNull BiometricContext biometricContext, - @NonNull UserStartedCallback<Object> callback, boolean shouldFinish) { - super(context, lazyDaemon, token, userId, sensorId, logger, biometricContext, callback); - mShouldFinish = shouldFinish; - } - - @Override - protected void startHalOperation() { - - } - - @Override - public void start(@NonNull ClientMonitorCallback callback) { - super.start(callback); - - mCallback = callback; - if (mShouldFinish) { - mUserStartedCallback.onUserStarted( - getTargetUserId(), new Object(), 1 /* halInterfaceVersion */); - callback.onClientFinished(this, true /* success */); - } - } - - @Override - public void unableToStart() { - - } - } -} diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/FaceServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/FaceServiceTest.java index e4c56a7237d4..1ca36a3c9824 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/FaceServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/FaceServiceTest.java @@ -147,11 +147,10 @@ public class FaceServiceTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) - public void registerAuthenticatorsLegacy_defaultOnly() throws Exception { + public void registerAuthenticators_defaultOnly() throws Exception { initService(); - mFaceService.mServiceWrapper.registerAuthenticatorsLegacy(mFaceSensorConfigurations); + mFaceService.mServiceWrapper.registerAuthenticators(mFaceSensorConfigurations); waitForRegistration(); verify(mIBiometricService).registerAuthenticator(eq(ID_DEFAULT), @@ -161,13 +160,13 @@ public class FaceServiceTest { } @Test - @RequiresFlagsEnabled({Flags.FLAG_DE_HIDL, Flags.FLAG_FACE_VHAL_FEATURE}) + @RequiresFlagsEnabled(Flags.FLAG_FACE_VHAL_FEATURE) public void registerAuthenticatorsLegacy_virtualOnly() throws Exception { initService(); Settings.Secure.putInt(mSettingsRule.mockContentResolver(mContext), Settings.Secure.BIOMETRIC_VIRTUAL_ENABLED, 1); - mFaceService.mServiceWrapper.registerAuthenticatorsLegacy(mFaceSensorConfigurations); + mFaceService.mServiceWrapper.registerAuthenticators(mFaceSensorConfigurations); waitForRegistration(); verify(mIBiometricService).registerAuthenticator(eq(ID_VIRTUAL), @@ -176,13 +175,13 @@ public class FaceServiceTest { } @Test - @RequiresFlagsEnabled({Flags.FLAG_DE_HIDL, Flags.FLAG_FACE_VHAL_FEATURE}) - public void registerAuthenticatorsLegacy_virtualFaceOnly() throws Exception { + @RequiresFlagsEnabled(Flags.FLAG_FACE_VHAL_FEATURE) + public void registerAuthenticators_virtualFaceOnly() throws Exception { initService(); Settings.Secure.putInt(mSettingsRule.mockContentResolver(mContext), Settings.Secure.BIOMETRIC_FACE_VIRTUAL_ENABLED, 1); - mFaceService.mServiceWrapper.registerAuthenticatorsLegacy(mFaceSensorConfigurations); + mFaceService.mServiceWrapper.registerAuthenticators(mFaceSensorConfigurations); waitForRegistration(); verify(mIBiometricService).registerAuthenticator(eq(ID_VIRTUAL), @@ -191,13 +190,12 @@ public class FaceServiceTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) - public void registerAuthenticatorsLegacy_virtualAlwaysWhenNoOther() throws Exception { + public void registerAuthenticators_virtualAlwaysWhenNoOther() throws Exception { mFaceSensorConfigurations = new FaceSensorConfigurations(false); mFaceSensorConfigurations.addAidlConfigs(new String[]{NAME_VIRTUAL}); initService(); - mFaceService.mServiceWrapper.registerAuthenticatorsLegacy(mFaceSensorConfigurations); + mFaceService.mServiceWrapper.registerAuthenticators(mFaceSensorConfigurations); waitForRegistration(); verify(mIBiometricService).registerAuthenticator(eq(ID_VIRTUAL), @@ -210,7 +208,7 @@ public class FaceServiceTest { FaceAuthenticateOptions faceAuthenticateOptions = new FaceAuthenticateOptions.Builder() .build(); initService(); - mFaceService.mServiceWrapper.registerAuthenticators(List.of()); + mFaceService.mServiceWrapper.registerAuthenticators(mFaceSensorConfigurations); waitForRegistration(); final long operationId = 5; @@ -230,7 +228,7 @@ public class FaceServiceTest { R.string.config_keyguardComponent, OP_PACKAGE_NAME); initService(); - mFaceService.mServiceWrapper.registerAuthenticators(List.of()); + mFaceService.mServiceWrapper.registerAuthenticators(mFaceSensorConfigurations); waitForRegistration(); mFaceService.mServiceWrapper.detectFace(mToken, mFaceServiceReceiver, faceAuthenticateOptions); diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceAuthenticationClientTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceAuthenticationClientTest.java index 84c36848adbf..a556f52ecb17 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceAuthenticationClientTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceAuthenticationClientTest.java @@ -50,8 +50,6 @@ import android.os.IBinder; import android.os.PowerManager; import android.os.RemoteException; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.platform.test.flag.junit.SetFlagsRule; @@ -60,7 +58,6 @@ import android.testing.TestableContext; import androidx.test.filters.SmallTest; import androidx.test.platform.app.InstrumentationRegistry; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.OperationContextExt; @@ -137,6 +134,8 @@ public class FaceAuthenticationClientTest { private ArgumentCaptor<Consumer<OperationContext>> mContextInjector; @Captor private ArgumentCaptor<Consumer<OperationContext>> mStartHalConsumerCaptor; + @Captor + private ArgumentCaptor<FaceAuthenticateOptions> mFaceAuthenticateOptionsCaptor; @Rule public final MockitoRule mockito = MockitoJUnit.rule(); @@ -159,21 +158,26 @@ public class FaceAuthenticationClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) public void authWithContext_v2() throws RemoteException { final FaceAuthenticationClient client = createClient(2); client.start(mCallback); + verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), + mStartHalConsumerCaptor.capture(), mContextInjector.capture(), + mFaceAuthenticateOptionsCaptor.capture()); + + mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor.getValue().toAidlContext( + mFaceAuthenticateOptionsCaptor.getValue())); InOrder order = inOrder(mHal, mBiometricContext); order.verify(mBiometricContext).updateContext( mOperationContextCaptor.capture(), anyBoolean()); final OperationContext aidlContext = mOperationContextCaptor.getValue().toAidlContext(); + order.verify(mHal).authenticateWithContext(eq(OP_ID), same(aidlContext)); assertThat(aidlContext.wakeReason).isEqualTo(WAKE_REASON); assertThat(aidlContext.authenticateReason.getFaceAuthenticateReason()) .isEqualTo(AUTH_REASON); - verify(mHal, never()).authenticate(anyLong()); } @@ -200,30 +204,6 @@ public class FaceAuthenticationClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void notifyHalWhenContextChanges() throws RemoteException { - final FaceAuthenticationClient client = createClient(); - client.start(mCallback); - - final ArgumentCaptor<OperationContext> captor = - ArgumentCaptor.forClass(OperationContext.class); - verify(mHal).authenticateWithContext(eq(OP_ID), captor.capture()); - OperationContext opContext = captor.getValue(); - - // fake an update to the context - verify(mBiometricContext).subscribe( - mOperationContextCaptor.capture(), mContextInjector.capture()); - assertThat(opContext).isSameInstanceAs( - mOperationContextCaptor.getValue().toAidlContext()); - mContextInjector.getValue().accept(opContext); - verify(mHal).onContextChanged(same(opContext)); - - client.stopHalOperation(); - verify(mBiometricContext).unsubscribe(same(mOperationContextCaptor.getValue())); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void subscribeContextAndStartHal() throws RemoteException { final FaceAuthenticationClient client = createClient(); client.start(mCallback); diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceDetectClientTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceDetectClientTest.java index e626f7307e7e..fd3f05474a70 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceDetectClientTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceDetectClientTest.java @@ -20,7 +20,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.same; import static org.mockito.Mockito.verify; @@ -37,8 +36,6 @@ import android.os.PowerManager; import android.os.RemoteException; import android.os.Vibrator; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.testing.TestableContext; @@ -46,7 +43,6 @@ import android.testing.TestableContext; import androidx.test.filters.SmallTest; import androidx.test.platform.app.InstrumentationRegistry; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.OperationContextExt; @@ -58,7 +54,6 @@ import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -124,49 +119,6 @@ public class FaceDetectClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void detectWithContext_v2() throws RemoteException { - final FaceDetectClient client = createClient(2); - client.start(mCallback); - - InOrder order = inOrder(mHal, mBiometricContext); - order.verify(mBiometricContext).updateContext( - mOperationContextCaptor.capture(), anyBoolean()); - - final OperationContext aidlContext = mOperationContextCaptor.getValue().toAidlContext(); - order.verify(mHal).detectInteractionWithContext(same(aidlContext)); - assertThat(aidlContext.wakeReason).isEqualTo(WAKE_REASON); - assertThat(aidlContext.authenticateReason.getFaceAuthenticateReason()) - .isEqualTo(AUTH_REASON); - - verify(mHal, never()).detectInteraction(); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void notifyHalWhenContextChanges() throws RemoteException { - final FaceDetectClient client = createClient(); - client.start(mCallback); - - final ArgumentCaptor<OperationContext> captor = - ArgumentCaptor.forClass(OperationContext.class); - verify(mHal).detectInteractionWithContext(captor.capture()); - OperationContext opContext = captor.getValue(); - - // fake an update to the context - verify(mBiometricContext).subscribe( - mOperationContextCaptor.capture(), mContextInjector.capture()); - assertThat(opContext).isSameInstanceAs( - mOperationContextCaptor.getValue().toAidlContext()); - mContextInjector.getValue().accept(opContext); - verify(mHal).onContextChanged(same(opContext)); - - client.stopHalOperation(); - verify(mBiometricContext).unsubscribe(same(mOperationContextCaptor.getValue())); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void subscribeContextAndStartHal() throws RemoteException { final FaceDetectClient client = createClient(); client.start(mCallback); diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClientTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClientTest.java index 02363cd66349..d6b57895381c 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClientTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClientTest.java @@ -24,7 +24,6 @@ import static org.mockito.ArgumentMatchers.anyByte; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.same; import static org.mockito.Mockito.verify; @@ -38,8 +37,6 @@ import android.hardware.face.FaceEnrollOptions; import android.os.IBinder; import android.os.RemoteException; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.testing.TestableContext; @@ -47,7 +44,6 @@ import android.testing.TestableContext; import androidx.test.filters.SmallTest; import androidx.test.platform.app.InstrumentationRegistry; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.OperationContextExt; @@ -60,7 +56,6 @@ import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -124,45 +119,6 @@ public class FaceEnrollClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void enrollWithContext_v2() throws RemoteException { - final FaceEnrollClient client = createClient(2); - client.start(mCallback); - - InOrder order = inOrder(mHal, mBiometricContext); - order.verify(mBiometricContext).updateContext( - mOperationContextCaptor.capture(), anyBoolean()); - - final OperationContext aidlContext = mOperationContextCaptor.getValue().toAidlContext(); - order.verify(mHal).enrollWithContext(any(), anyByte(), any(), any(), same(aidlContext)); - verify(mHal, never()).enroll(any(), anyByte(), any(), any()); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void notifyHalWhenContextChanges() throws RemoteException { - final FaceEnrollClient client = createClient(3); - client.start(mCallback); - - final ArgumentCaptor<OperationContext> captor = - ArgumentCaptor.forClass(OperationContext.class); - verify(mHal).enrollWithContext(any(), anyByte(), any(), any(), captor.capture()); - OperationContext opContext = captor.getValue(); - - // fake an update to the context - verify(mBiometricContext).subscribe( - mOperationContextCaptor.capture(), mContextInjector.capture()); - assertThat(opContext).isSameInstanceAs( - mOperationContextCaptor.getValue().toAidlContext()); - mContextInjector.getValue().accept(opContext); - verify(mHal).onContextChanged(same(opContext)); - - client.stopHalOperation(); - verify(mBiometricContext).unsubscribe(same(mOperationContextCaptor.getValue())); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void subscribeContextAndStartHal() throws RemoteException { final FaceEnrollClient client = createClient(3); client.start(mCallback); @@ -192,16 +148,6 @@ public class FaceEnrollClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void enrollWithFaceOptions() throws RemoteException { - final FaceEnrollClient client = createClient(4); - client.start(mCallback); - - verify(mHal).enrollWithOptions(any()); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void enrollWithFaceOptionsAfterSubscribingContext() throws RemoteException { final FaceEnrollClient client = createClient(4); client.start(mCallback); diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceProviderTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceProviderTest.java index 9eca93e9f054..c4e51f8d1445 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceProviderTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceProviderTest.java @@ -44,22 +44,18 @@ import android.hardware.face.FaceAuthenticateOptions; import android.hardware.face.HidlFaceSensorConfig; import android.os.Handler; import android.os.IBinder; -import android.os.Looper; import android.os.Message; import android.os.RemoteException; import android.os.UserManager; import android.os.test.TestLooper; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; import com.android.internal.R; import com.android.server.biometrics.BiometricHandlerProvider; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.sensors.AuthSessionCoordinator; import com.android.server.biometrics.sensors.AuthenticationStateListeners; @@ -134,13 +130,8 @@ public class FaceProviderTest { when(mBiometricHandlerProvider.getBiometricCallbackHandler()).thenReturn( mBiometricCallbackHandler); when(mBiometricContext.getAuthSessionCoordinator()).thenReturn(mAuthSessionCoordinator); - if (Flags.deHidl()) { - when(mBiometricHandlerProvider.getFaceHandler()).thenReturn(new Handler( - mLooper.getLooper())); - } else { - when(mBiometricHandlerProvider.getFaceHandler()).thenReturn(new Handler( - Looper.getMainLooper())); - } + when(mBiometricHandlerProvider.getFaceHandler()).thenReturn(new Handler( + mLooper.getLooper())); final SensorProps sensor1 = new SensorProps(); sensor1.commonProps = new CommonProps(); @@ -176,7 +167,6 @@ public class FaceProviderTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testAddingHidlSensors() { when(mResources.getIntArray(anyInt())).thenReturn(new int[]{}); when(mResources.getBoolean(anyInt())).thenReturn(false); @@ -247,7 +237,6 @@ public class FaceProviderTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testAuthenticateCallbackHandler() { waitForIdle(); @@ -295,10 +284,6 @@ public class FaceProviderTest { } private void waitForIdle() { - if (Flags.deHidl()) { - mLooper.dispatchAll(); - } else { - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); - } + mLooper.dispatchAll(); } } diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/SensorTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/SensorTest.java index fe9cd4353603..6780e60a22b0 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/SensorTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/SensorTest.java @@ -41,7 +41,6 @@ import android.platform.test.annotations.Presubmit; import androidx.test.filters.SmallTest; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.sensors.AuthSessionCoordinator; @@ -50,7 +49,6 @@ import com.android.server.biometrics.sensors.BiometricScheduler; import com.android.server.biometrics.sensors.LockoutCache; import com.android.server.biometrics.sensors.LockoutResetDispatcher; import com.android.server.biometrics.sensors.LockoutTracker; -import com.android.server.biometrics.sensors.UserAwareBiometricScheduler; import com.android.server.biometrics.sensors.UserSwitchProvider; import org.junit.Before; @@ -75,12 +73,8 @@ public class SensorTest { @Mock private ISession mSession; @Mock - private UserAwareBiometricScheduler.UserSwitchCallback mUserSwitchCallback; - @Mock private UserSwitchProvider<IFace, ISession> mUserSwitchProvider; @Mock - private AidlResponseHandler.HardwareUnavailableCallback mHardwareUnavailableCallback; - @Mock private LockoutResetDispatcher mLockoutResetDispatcher; @Mock private BiometricLogger mBiometricLogger; @@ -94,6 +88,8 @@ public class SensorTest { private BaseClientMonitor mClientMonitor; @Mock private AidlSession mCurrentSession; + @Mock + private AidlResponseHandler.AidlResponseHandlerCallback mAidlResponseHandlerCallback; private final TestLooper mLooper = new TestLooper(); private final LockoutCache mLockoutCache = new LockoutCache(); @@ -108,27 +104,17 @@ public class SensorTest { when(mContext.getSystemService(Context.BIOMETRIC_SERVICE)).thenReturn(mBiometricService); when(mBiometricContext.getAuthSessionCoordinator()).thenReturn(mAuthSessionCoordinator); - if (Flags.deHidl()) { - mScheduler = new BiometricScheduler<>( - new Handler(mLooper.getLooper()), - BiometricScheduler.SENSOR_TYPE_FACE, - null /* gestureAvailabilityDispatcher */, - mBiometricService, - 2 /* recentOperationsLimit */, - () -> USER_ID, - mUserSwitchProvider); - } else { - mScheduler = new UserAwareBiometricScheduler<>(TAG, - new Handler(mLooper.getLooper()), - BiometricScheduler.SENSOR_TYPE_FACE, - null /* gestureAvailabilityDispatcher */, - mBiometricService, - () -> USER_ID, - mUserSwitchCallback); - } + mScheduler = new BiometricScheduler<>( + new Handler(mLooper.getLooper()), + BiometricScheduler.SENSOR_TYPE_FACE, + null /* gestureAvailabilityDispatcher */, + mBiometricService, + 2 /* recentOperationsLimit */, + () -> USER_ID, + mUserSwitchProvider); mHalCallback = new AidlResponseHandler(mContext, mScheduler, SENSOR_ID, USER_ID, mLockoutCache, mLockoutResetDispatcher, mAuthSessionCoordinator, - mHardwareUnavailableCallback); + mAidlResponseHandlerCallback); } @Test diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/Face10Test.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/Face10Test.java deleted file mode 100644 index 949d6ee800fa..000000000000 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/Face10Test.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import static junit.framework.Assert.assertEquals; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.content.Context; -import android.content.res.Resources; -import android.hardware.biometrics.ComponentInfoInternal; -import android.hardware.biometrics.SensorProperties; -import android.hardware.face.FaceSensorProperties; -import android.hardware.face.FaceSensorPropertiesInternal; -import android.hardware.face.IFaceServiceReceiver; -import android.os.Binder; -import android.os.Handler; -import android.os.IBinder; -import android.os.Looper; -import android.os.UserManager; -import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.flag.junit.CheckFlagsRule; -import android.platform.test.flag.junit.DeviceFlagsValueProvider; - -import androidx.test.InstrumentationRegistry; -import androidx.test.filters.SmallTest; - -import com.android.internal.R; -import com.android.server.biometrics.Flags; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.sensors.AuthenticationStateListeners; -import com.android.server.biometrics.sensors.BiometricScheduler; -import com.android.server.biometrics.sensors.BiometricStateCallback; -import com.android.server.biometrics.sensors.LockoutResetDispatcher; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.IntStream; - -@Presubmit -@SmallTest -public class Face10Test { - - private static final String TAG = "Face10Test"; - private static final int SENSOR_ID = 1; - private static final int USER_ID = 20; - private static final float FRR_THRESHOLD = 0.2f; - - @Rule - public final CheckFlagsRule mCheckFlagsRule = - DeviceFlagsValueProvider.createCheckFlagsRule(); - - @Mock - private Context mContext; - @Mock - private UserManager mUserManager; - @Mock - private Resources mResources; - @Mock - private BiometricScheduler mScheduler; - @Mock - private BiometricContext mBiometricContext; - @Mock - private BiometricStateCallback mBiometricStateCallback; - @Mock - private AuthenticationStateListeners mAuthenticationStateListeners; - - private final Handler mHandler = new Handler(Looper.getMainLooper()); - private LockoutResetDispatcher mLockoutResetDispatcher; - private com.android.server.biometrics.sensors.face.hidl.Face10 mFace10; - private IBinder mBinder; - - private static void waitForIdle() { - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager); - when(mUserManager.getAliveUsers()).thenReturn(new ArrayList<>()); - - when(mContext.getResources()).thenReturn(mResources); - when(mResources.getFraction(R.fraction.config_biometricNotificationFrrThreshold, 1, 1)) - .thenReturn(FRR_THRESHOLD); - - mLockoutResetDispatcher = new LockoutResetDispatcher(mContext); - - final int maxEnrollmentsPerUser = 1; - final List<ComponentInfoInternal> componentInfo = new ArrayList<>(); - final boolean supportsFaceDetection = false; - final boolean supportsSelfIllumination = false; - final boolean resetLockoutRequiresChallenge = false; - final FaceSensorPropertiesInternal sensorProps = new FaceSensorPropertiesInternal(SENSOR_ID, - SensorProperties.STRENGTH_STRONG, maxEnrollmentsPerUser, componentInfo, - FaceSensorProperties.TYPE_UNKNOWN, supportsFaceDetection, supportsSelfIllumination, - resetLockoutRequiresChallenge); - - Face10.sSystemClock = Clock.fixed( - Instant.ofEpochMilli(100), ZoneId.of("America/Los_Angeles")); - mFace10 = new Face10(mContext, mBiometricStateCallback, mAuthenticationStateListeners, - sensorProps, mLockoutResetDispatcher, mHandler, mScheduler, mBiometricContext); - mBinder = new Binder(); - } - - private void tick(long seconds) { - waitForIdle(); - Face10.sSystemClock = Clock.fixed(Instant.ofEpochSecond( - Face10.sSystemClock.instant().getEpochSecond() + seconds), - ZoneId.of("America/Los_Angeles")); - } - - @Test - public void getAuthenticatorId_doesNotCrashWhenIdNotFound() { - assertEquals(0, mFace10.getAuthenticatorId(0 /* sensorId */, 111 /* userId */)); - waitForIdle(); - } - - @Test - public void scheduleRevokeChallenge_doesNotCrash() { - mFace10.scheduleRevokeChallenge(0 /* sensorId */, 0 /* userId */, mBinder, TAG, - 0 /* challenge */); - waitForIdle(); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void scheduleGenerateChallenge_cachesResult() { - final IFaceServiceReceiver[] mocks = IntStream.range(0, 3) - .mapToObj(i -> mock(IFaceServiceReceiver.class)) - .toArray(IFaceServiceReceiver[]::new); - for (IFaceServiceReceiver mock : mocks) { - mFace10.scheduleGenerateChallenge(SENSOR_ID, USER_ID, mBinder, mock, TAG); - tick(10); - } - tick(120); - mFace10.scheduleGenerateChallenge( - SENSOR_ID, USER_ID, mBinder, mock(IFaceServiceReceiver.class), TAG); - waitForIdle(); - - verify(mScheduler, times(2)) - .scheduleClientMonitor(isA(FaceGenerateChallengeClient.class), any()); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void scheduleRevokeChallenge_waitsUntilEmpty() { - final long challenge = 22; - final IFaceServiceReceiver[] mocks = IntStream.range(0, 3) - .mapToObj(i -> mock(IFaceServiceReceiver.class)) - .toArray(IFaceServiceReceiver[]::new); - for (IFaceServiceReceiver mock : mocks) { - mFace10.scheduleGenerateChallenge(SENSOR_ID, USER_ID, mBinder, mock, TAG); - tick(10); - } - for (IFaceServiceReceiver mock : mocks) { - mFace10.scheduleRevokeChallenge(SENSOR_ID, USER_ID, mBinder, TAG, challenge); - tick(10); - } - waitForIdle(); - - verify(mScheduler).scheduleClientMonitor(isA(FaceRevokeChallengeClient.class), any()); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void scheduleRevokeChallenge_doesNotWaitForever() { - mFace10.scheduleGenerateChallenge( - SENSOR_ID, USER_ID, mBinder, mock(IFaceServiceReceiver.class), TAG); - mFace10.scheduleGenerateChallenge( - SENSOR_ID, USER_ID, mBinder, mock(IFaceServiceReceiver.class), TAG); - tick(10000); - mFace10.scheduleGenerateChallenge( - SENSOR_ID, USER_ID, mBinder, mock(IFaceServiceReceiver.class), TAG); - mFace10.scheduleRevokeChallenge( - SENSOR_ID, USER_ID, mBinder, TAG, 8 /* challenge */); - waitForIdle(); - - verify(mScheduler).scheduleClientMonitor(isA(FaceRevokeChallengeClient.class), any()); - } - - @Test - public void halServiceDied_resetsScheduler() { - // It's difficult to test the linkToDeath --> serviceDied path, so let's just invoke - // serviceDied directly. - mFace10.serviceDied(0 /* cookie */); - waitForIdle(); - verify(mScheduler).reset(); - } -} diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/FaceGenerateChallengeClientTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/FaceGenerateChallengeClientTest.java deleted file mode 100644 index ec083294c0bd..000000000000 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/FaceGenerateChallengeClientTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.face.hidl; - -import static junit.framework.Assert.assertEquals; - -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.content.Context; -import android.hardware.biometrics.face.V1_0.IBiometricsFace; -import android.hardware.biometrics.face.V1_0.OptionalUint64; -import android.hardware.face.IFaceServiceReceiver; -import android.os.Binder; -import android.platform.test.annotations.Presubmit; - -import androidx.test.core.app.ApplicationProvider; -import androidx.test.filters.SmallTest; - -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.log.BiometricLogger; -import com.android.server.biometrics.sensors.ClientMonitorCallback; -import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -@Presubmit -@SmallTest -public class FaceGenerateChallengeClientTest { - - private static final String TAG = "FaceGenerateChallengeClientTest"; - private static final int USER_ID = 2; - private static final int SENSOR_ID = 4; - private static final long START_TIME = 5000; - private static final long CHALLENGE = 200; - - private final Context mContext = ApplicationProvider.getApplicationContext(); - - @Mock - private IBiometricsFace mIBiometricsFace; - @Mock - private IFaceServiceReceiver mClientReceiver; - @Mock - private IFaceServiceReceiver mOtherReceiver; - @Mock - private ClientMonitorCallback mMonitorCallback; - @Mock - private BiometricLogger mBiometricLogger; - @Mock - private BiometricContext mBiometricContext; - - private FaceGenerateChallengeClient mClient; - - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); - - final OptionalUint64 challenge = new OptionalUint64(); - challenge.value = CHALLENGE; - when(mIBiometricsFace.generateChallenge(anyInt())).thenReturn(challenge); - - mClient = new FaceGenerateChallengeClient(mContext, () -> mIBiometricsFace, new Binder(), - new ClientMonitorCallbackConverter(mClientReceiver), USER_ID, - TAG, SENSOR_ID, mBiometricLogger, mBiometricContext , START_TIME); - } - - @Test - public void getCreatedAt() { - assertEquals(START_TIME, mClient.getCreatedAt()); - } - - @Test - public void reuseResult_whenNotReady() throws Exception { - mClient.reuseResult(mOtherReceiver); - verify(mOtherReceiver, never()).onChallengeGenerated(anyInt(), anyInt(), anyInt()); - } - - @Test - public void reuseResult_whenReady() throws Exception { - mClient.start(mMonitorCallback); - mClient.reuseResult(mOtherReceiver); - verify(mOtherReceiver).onChallengeGenerated(eq(SENSOR_ID), eq(USER_ID), eq(CHALLENGE)); - } - - @Test - public void reuseResult_whenReallyReady() throws Exception { - mClient.reuseResult(mOtherReceiver); - mClient.start(mMonitorCallback); - verify(mOtherReceiver).onChallengeGenerated(eq(SENSOR_ID), eq(USER_ID), eq(CHALLENGE)); - } -} diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSessionAdapterTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSessionAdapterTest.java index b5d73d256f7d..44da431ade82 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSessionAdapterTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/HidlToAidlSessionAdapterTest.java @@ -16,8 +16,8 @@ package com.android.server.biometrics.sensors.face.hidl; -import static com.android.server.biometrics.sensors.face.hidl.FaceGenerateChallengeClient.CHALLENGE_TIMEOUT_SEC; import static com.android.server.biometrics.sensors.face.hidl.HidlToAidlSessionAdapter.ENROLL_TIMEOUT_SEC; +import static com.android.server.biometrics.sensors.face.hidl.HidlToAidlSessionAdapter.CHALLENGE_TIMEOUT_SEC; import static com.google.common.truth.Truth.assertThat; diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/FingerprintServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/FingerprintServiceTest.java index 9a8cd48fb4cf..6126af59a7fe 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/FingerprintServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/FingerprintServiceTest.java @@ -51,7 +51,6 @@ import android.hardware.fingerprint.IFingerprintServiceReceiver; import android.os.Binder; import android.os.IBinder; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.provider.Settings; @@ -64,7 +63,6 @@ import com.android.internal.R; import com.android.internal.util.test.FakeSettingsProvider; import com.android.internal.util.test.FakeSettingsProviderRule; import com.android.server.LocalServices; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.sensors.fingerprint.aidl.FingerprintProvider; import com.android.server.companion.virtual.VirtualDeviceManagerInternal; @@ -90,8 +88,6 @@ public class FingerprintServiceTest { private static final int ID_VIRTUAL = 6; private static final String NAME_DEFAULT = "default"; private static final String NAME_VIRTUAL = "virtual"; - private static final List<FingerprintSensorPropertiesInternal> HIDL_AUTHENTICATORS = - List.of(); private static final String OP_PACKAGE_NAME = "FingerprintServiceTest/SystemUi"; @Rule @@ -185,7 +181,7 @@ public class FingerprintServiceTest { private void initServiceWithAndWait(String... aidlInstances) throws Exception { initServiceWith(aidlInstances); - mService.mServiceWrapper.registerAuthenticators(HIDL_AUTHENTICATORS); + mService.mServiceWrapper.registerAuthenticators(mFingerprintSensorConfigurations); waitForRegistration(); } @@ -193,18 +189,7 @@ public class FingerprintServiceTest { public void registerAuthenticators_defaultOnly() throws Exception { initServiceWith(NAME_DEFAULT, NAME_VIRTUAL); - mService.mServiceWrapper.registerAuthenticators(HIDL_AUTHENTICATORS); - waitForRegistration(); - - verify(mIBiometricService).registerAuthenticator(eq(ID_DEFAULT), anyInt(), anyInt(), any()); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) - public void registerAuthenticatorsLegacy_defaultOnly() throws Exception { - initServiceWith(NAME_DEFAULT, NAME_VIRTUAL); - - mService.mServiceWrapper.registerAuthenticatorsLegacy(mFingerprintSensorConfigurations); + mService.mServiceWrapper.registerAuthenticators(mFingerprintSensorConfigurations); waitForRegistration(); verify(mIBiometricService).registerAuthenticator(eq(ID_DEFAULT), anyInt(), anyInt(), any()); @@ -216,7 +201,7 @@ public class FingerprintServiceTest { Settings.Secure.putInt(mSettingsRule.mockContentResolver(mContext), Settings.Secure.BIOMETRIC_VIRTUAL_ENABLED, 1); - mService.mServiceWrapper.registerAuthenticators(HIDL_AUTHENTICATORS); + mService.mServiceWrapper.registerAuthenticators(mFingerprintSensorConfigurations); waitForRegistration(); verify(mIBiometricService).registerAuthenticator(eq(ID_VIRTUAL), anyInt(), anyInt(), any()); @@ -228,20 +213,7 @@ public class FingerprintServiceTest { Settings.Secure.putInt(mSettingsRule.mockContentResolver(mContext), Settings.Secure.BIOMETRIC_FINGERPRINT_VIRTUAL_ENABLED, 1); - mService.mServiceWrapper.registerAuthenticators(HIDL_AUTHENTICATORS); - waitForRegistration(); - - verify(mIBiometricService).registerAuthenticator(eq(ID_VIRTUAL), anyInt(), anyInt(), any()); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) - public void registerAuthenticatorsLegacy_virtualOnly() throws Exception { - initServiceWith(NAME_DEFAULT, NAME_VIRTUAL); - Settings.Secure.putInt(mSettingsRule.mockContentResolver(mContext), - Settings.Secure.BIOMETRIC_VIRTUAL_ENABLED, 1); - - mService.mServiceWrapper.registerAuthenticatorsLegacy(mFingerprintSensorConfigurations); + mService.mServiceWrapper.registerAuthenticators(mFingerprintSensorConfigurations); waitForRegistration(); verify(mIBiometricService).registerAuthenticator(eq(ID_VIRTUAL), anyInt(), anyInt(), any()); @@ -249,23 +221,12 @@ public class FingerprintServiceTest { @Test public void registerAuthenticators_virtualAlwaysWhenNoOther() throws Exception { - initServiceWith(NAME_VIRTUAL); - - mService.mServiceWrapper.registerAuthenticators(HIDL_AUTHENTICATORS); - waitForRegistration(); - - verify(mIBiometricService).registerAuthenticator(eq(ID_VIRTUAL), anyInt(), anyInt(), any()); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) - public void registerAuthenticatorsLegacy_virtualAlwaysWhenNoOther() throws Exception { mFingerprintSensorConfigurations = new FingerprintSensorConfigurations(true); mFingerprintSensorConfigurations.addAidlSensors(new String[]{NAME_VIRTUAL}); initServiceWith(NAME_VIRTUAL); - mService.mServiceWrapper.registerAuthenticatorsLegacy(mFingerprintSensorConfigurations); + mService.mServiceWrapper.registerAuthenticators(mFingerprintSensorConfigurations); waitForRegistration(); verify(mIBiometricService).registerAuthenticator(eq(ID_VIRTUAL), anyInt(), anyInt(), any()); diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintAuthenticationClientTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintAuthenticationClientTest.java index 7a77392c4fa3..db9fe7f2a0c7 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintAuthenticationClientTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintAuthenticationClientTest.java @@ -30,7 +30,6 @@ import static org.mockito.Mockito.anyFloat; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.anyLong; import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.same; @@ -42,7 +41,6 @@ import android.app.ActivityManager; import android.app.ActivityTaskManager; import android.content.ComponentName; import android.hardware.biometrics.BiometricManager; -import android.hardware.biometrics.common.AuthenticateReason; import android.hardware.biometrics.common.ICancellationSignal; import android.hardware.biometrics.common.OperationContext; import android.hardware.biometrics.fingerprint.ISession; @@ -52,13 +50,10 @@ import android.hardware.fingerprint.FingerprintAuthenticateOptions; import android.hardware.fingerprint.FingerprintSensorPropertiesInternal; import android.hardware.fingerprint.ISidefpsController; import android.hardware.fingerprint.IUdfpsOverlayController; -import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.os.test.TestLooper; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.platform.test.flag.junit.SetFlagsRule; @@ -67,7 +62,6 @@ import android.testing.TestableContext; import androidx.test.filters.SmallTest; import androidx.test.platform.app.InstrumentationRegistry; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.CallbackWithProbe; @@ -84,7 +78,6 @@ import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -180,33 +173,15 @@ public class FingerprintAuthenticationClientTest { public void authNoContext_v1() throws RemoteException { final FingerprintAuthenticationClient client = createClient(1); client.start(mCallback); - if (Flags.deHidl()) { - verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), - mStartHalConsumerCaptor.capture(), mContextInjector.capture(), any()); - mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor - .getValue().toAidlContext()); - } - verify(mHal).authenticate(eq(OP_ID)); - verify(mHal, never()).authenticateWithContext(anyLong(), any()); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void authWithContext_v2() throws RemoteException { - final FingerprintAuthenticationClient client = createClient(2); - client.start(mCallback); - - InOrder order = inOrder(mHal, mBiometricContext); - order.verify(mBiometricContext).updateContext( - mOperationContextCaptor.capture(), anyBoolean()); + verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), + mStartHalConsumerCaptor.capture(), mContextInjector.capture(), any()); - final OperationContext aidlContext = mOperationContextCaptor.getValue().toAidlContext(); - order.verify(mHal).authenticateWithContext(eq(OP_ID), same(aidlContext)); - assertThat(aidlContext.authenticateReason.getFingerprintAuthenticateReason()) - .isEqualTo(AuthenticateReason.Fingerprint.UNKNOWN); + mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor + .getValue().toAidlContext()); - verify(mHal, never()).authenticate(anyLong()); + verify(mHal).authenticate(eq(OP_ID)); + verify(mHal, never()).authenticateWithContext(anyLong(), any()); } @Test @@ -277,21 +252,18 @@ public class FingerprintAuthenticationClientTest { final FingerprintAuthenticationClient client = createClient(); client.start(mCallback); - if (Flags.deHidl()) { - verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), - mStartHalConsumerCaptor.capture(), mContextInjector.capture(), any()); - mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor - .getValue().toAidlContext()); - } + + verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), + mStartHalConsumerCaptor.capture(), mContextInjector.capture(), any()); + + mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor + .getValue().toAidlContext()); final ArgumentCaptor<OperationContext> captor = ArgumentCaptor.forClass(OperationContext.class); verify(mHal).authenticateWithContext(eq(OP_ID), captor.capture()); OperationContext opContext = captor.getValue(); - if (!Flags.deHidl()) { - verify(mBiometricContext).subscribe( - mOperationContextCaptor.capture(), mContextInjector.capture()); - } + assertThat(mOperationContextCaptor.getValue().toAidlContext()) .isSameInstanceAs(opContext); @@ -326,12 +298,12 @@ public class FingerprintAuthenticationClientTest { when(mBiometricContext.isAod()).thenReturn(false); final FingerprintAuthenticationClient client = createClient(); client.start(mCallback); - if (Flags.deHidl()) { - verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), - mStartHalConsumerCaptor.capture(), mContextInjector.capture(), any()); - mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor - .getValue().toAidlContext()); - } + + verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), + mStartHalConsumerCaptor.capture(), mContextInjector.capture(), any()); + + mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor + .getValue().toAidlContext()); verify(mLuxProbe, isAwake ? times(1) : never()).enable(); } @@ -342,21 +314,18 @@ public class FingerprintAuthenticationClientTest { when(mBiometricContext.isAod()).thenReturn(true); final FingerprintAuthenticationClient client = createClient(); client.start(mCallback); - if (Flags.deHidl()) { - verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), - mStartHalConsumerCaptor.capture(), mContextInjector.capture(), any()); - mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor - .getValue().toAidlContext()); - } + + verify(mBiometricContext).subscribe(mOperationContextCaptor.capture(), + mStartHalConsumerCaptor.capture(), mContextInjector.capture(), any()); + + mStartHalConsumerCaptor.getValue().accept(mOperationContextCaptor + .getValue().toAidlContext()); final ArgumentCaptor<OperationContext> captor = ArgumentCaptor.forClass(OperationContext.class); verify(mHal).authenticateWithContext(eq(OP_ID), captor.capture()); OperationContext opContext = captor.getValue(); - if (!Flags.deHidl()) { - verify(mBiometricContext).subscribe( - mOperationContextCaptor.capture(), mContextInjector.capture()); - } + assertThat(opContext).isSameInstanceAs( mOperationContextCaptor.getValue().toAidlContext()); @@ -380,30 +349,6 @@ public class FingerprintAuthenticationClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void notifyHalWhenContextChanges() throws RemoteException { - final FingerprintAuthenticationClient client = createClient(); - client.start(mCallback); - - final ArgumentCaptor<OperationContext> captor = - ArgumentCaptor.forClass(OperationContext.class); - verify(mHal).authenticateWithContext(eq(OP_ID), captor.capture()); - OperationContext opContext = captor.getValue(); - - // fake an update to the context - verify(mBiometricContext).subscribe( - mOperationContextCaptor.capture(), mContextInjector.capture()); - assertThat(opContext).isSameInstanceAs( - mOperationContextCaptor.getValue().toAidlContext()); - mContextInjector.getValue().accept(opContext); - verify(mHal).onContextChanged(same(opContext)); - - client.stopHalOperation(); - verify(mBiometricContext).unsubscribe(same(mOperationContextCaptor.getValue())); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void subscribeContextAndStartHal() throws RemoteException { final FingerprintAuthenticationClient client = createClient(); client.start(mCallback); @@ -603,7 +548,6 @@ public class FingerprintAuthenticationClientTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testLockoutTracker_authFailed() throws RemoteException { final FingerprintAuthenticationClient client = createClient(1 /* version */, true /* allowBackgroundAuthentication */, mClientMonitorCallbackConverter, @@ -658,8 +602,7 @@ public class FingerprintAuthenticationClientTest { null /* taskStackListener */, mUdfpsOverlayController, mSideFpsController, mAuthenticationStateListeners, allowBackgroundAuthentication, - mSensorProps, - new Handler(mLooper.getLooper()), 0 /* biometricStrength */, mClock, + mSensorProps, 0 /* biometricStrength */, lockoutTracker) { @Override protected ActivityTaskManager getActivityTaskManager() { diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintDetectClientTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintDetectClientTest.java index 9edb8dde182a..6b8c3cde849b 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintDetectClientTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintDetectClientTest.java @@ -21,13 +21,11 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.hardware.biometrics.common.AuthenticateReason; import android.hardware.biometrics.common.OperationContext; import android.hardware.biometrics.fingerprint.ISession; import android.hardware.fingerprint.FingerprintAuthenticateOptions; @@ -35,8 +33,6 @@ import android.hardware.fingerprint.IUdfpsOverlayController; import android.os.IBinder; import android.os.RemoteException; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.testing.TestableContext; @@ -44,7 +40,6 @@ import android.testing.TestableContext; import androidx.test.filters.SmallTest; import androidx.test.platform.app.InstrumentationRegistry; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.OperationContextExt; @@ -56,7 +51,6 @@ import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -119,49 +113,6 @@ public class FingerprintDetectClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void detectNoContext_v2() throws RemoteException { - final FingerprintDetectClient client = createClient(2); - - client.start(mCallback); - - InOrder order = inOrder(mHal, mBiometricContext); - order.verify(mBiometricContext).updateContext( - mOperationContextCaptor.capture(), anyBoolean()); - - final OperationContext aidlContext = mOperationContextCaptor.getValue().toAidlContext(); - order.verify(mHal).detectInteractionWithContext(same(aidlContext)); - assertThat(aidlContext.authenticateReason.getFingerprintAuthenticateReason()) - .isEqualTo(AuthenticateReason.Fingerprint.UNKNOWN); - - verify(mHal, never()).detectInteraction(); - } - - @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void notifyHalWhenContextChanges() throws RemoteException { - final FingerprintDetectClient client = createClient(); - client.start(mCallback); - - final ArgumentCaptor<OperationContext> captor = - ArgumentCaptor.forClass(OperationContext.class); - verify(mHal).detectInteractionWithContext(captor.capture()); - OperationContext opContext = captor.getValue(); - - // fake an update to the context - verify(mBiometricContext).subscribe( - mOperationContextCaptor.capture(), mContextInjector.capture()); - assertThat(opContext).isSameInstanceAs( - mOperationContextCaptor.getValue().toAidlContext()); - mContextInjector.getValue().accept(opContext); - verify(mHal).onContextChanged(same(opContext)); - - client.stopHalOperation(); - verify(mBiometricContext).unsubscribe(same(mOperationContextCaptor.getValue())); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void subscribeContextAndStartHal() throws RemoteException { final FingerprintDetectClient client = createClient(); client.start(mCallback); diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClientTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClientTest.java index 916f6960efc9..d2e1c3c896ab 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClientTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClientTest.java @@ -24,7 +24,6 @@ import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.same; import static org.mockito.Mockito.times; @@ -44,8 +43,6 @@ import android.hardware.fingerprint.IUdfpsOverlayController; import android.os.IBinder; import android.os.RemoteException; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsDisabled; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; import android.platform.test.flag.junit.SetFlagsRule; @@ -54,7 +51,6 @@ import android.testing.TestableContext; import androidx.test.filters.SmallTest; import androidx.test.platform.app.InstrumentationRegistry; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.log.CallbackWithProbe; @@ -70,7 +66,6 @@ import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -156,21 +151,6 @@ public class FingerprintEnrollClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void enrollWithContext_v2() throws RemoteException { - final FingerprintEnrollClient client = createClient(2); - - client.start(mCallback); - - InOrder order = inOrder(mHal, mBiometricContext); - order.verify(mBiometricContext).updateContext( - mOperationContextCaptor.capture(), anyBoolean()); - order.verify(mHal).enrollWithContext(any(), - same(mOperationContextCaptor.getValue().toAidlContext())); - verify(mHal, never()).enroll(any()); - } - - @Test public void pointerUp_v1() throws RemoteException { final FingerprintEnrollClient client = createClient(1); client.start(mCallback); @@ -253,29 +233,6 @@ public class FingerprintEnrollClientTest { } @Test - @RequiresFlagsDisabled(Flags.FLAG_DE_HIDL) - public void notifyHalWhenContextChanges() throws RemoteException { - final FingerprintEnrollClient client = createClient(); - client.start(mCallback); - - final ArgumentCaptor<OperationContext> captor = - ArgumentCaptor.forClass(OperationContext.class); - verify(mHal).enrollWithContext(any(), captor.capture()); - OperationContext opContext = captor.getValue(); - - // fake an update to the context - verify(mBiometricContext).subscribe( - mOperationContextCaptor.capture(), mContextInjector.capture()); - mContextInjector.getValue().accept( - mOperationContextCaptor.getValue().toAidlContext()); - verify(mHal).onContextChanged(same(opContext)); - - client.stopHalOperation(); - verify(mBiometricContext).unsubscribe(same(mOperationContextCaptor.getValue())); - } - - @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void subscribeContextAndStartHal() throws RemoteException { final FingerprintEnrollClient client = createClient(); client.start(mCallback); diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProviderTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProviderTest.java index 0a35037762bd..1f288b2a0a3d 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProviderTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProviderTest.java @@ -47,21 +47,17 @@ import android.hardware.fingerprint.FingerprintAuthenticateOptions; import android.hardware.fingerprint.HidlFingerprintSensorConfig; import android.os.Handler; import android.os.IBinder; -import android.os.Looper; import android.os.Message; import android.os.RemoteException; import android.os.UserManager; import android.os.test.TestLooper; import android.platform.test.annotations.Presubmit; -import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; import com.android.server.biometrics.BiometricHandlerProvider; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.sensors.AuthSessionCoordinator; import com.android.server.biometrics.sensors.AuthenticationStateListeners; @@ -136,13 +132,8 @@ public class FingerprintProviderTest { when(mBiometricContext.getAuthSessionCoordinator()).thenReturn(mAuthSessionCoordinator); when(mBiometricHandlerProvider.getBiometricCallbackHandler()).thenReturn( mBiometricCallbackHandler); - if (Flags.deHidl()) { - when(mBiometricHandlerProvider.getFingerprintHandler()).thenReturn( - new Handler(mLooper.getLooper())); - } else { - when(mBiometricHandlerProvider.getFingerprintHandler()).thenReturn( - new Handler(Looper.getMainLooper())); - } + when(mBiometricHandlerProvider.getFingerprintHandler()).thenReturn( + new Handler(mLooper.getLooper())); final SensorProps sensor1 = new SensorProps(); sensor1.commonProps = new CommonProps(); @@ -176,7 +167,6 @@ public class FingerprintProviderTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testAddingHidlSensors() { when(mResources.getIntArray(anyInt())).thenReturn(new int[]{}); when(mResources.getBoolean(anyInt())).thenReturn(false); @@ -252,7 +242,6 @@ public class FingerprintProviderTest { } @Test - @RequiresFlagsEnabled(Flags.FLAG_DE_HIDL) public void testScheduleAuthenticate() { waitForIdle(); @@ -302,10 +291,6 @@ public class FingerprintProviderTest { } private void waitForIdle() { - if (Flags.deHidl()) { - mLooper.dispatchAll(); - } else { - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); - } + mLooper.dispatchAll(); } } diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/SensorTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/SensorTest.java index b4c2ee8f89bf..698db2e19661 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/SensorTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/aidl/SensorTest.java @@ -42,7 +42,6 @@ import android.platform.test.annotations.Presubmit; import androidx.test.filters.SmallTest; -import com.android.server.biometrics.Flags; import com.android.server.biometrics.log.BiometricContext; import com.android.server.biometrics.log.BiometricLogger; import com.android.server.biometrics.sensors.AuthSessionCoordinator; @@ -51,7 +50,6 @@ import com.android.server.biometrics.sensors.BiometricScheduler; import com.android.server.biometrics.sensors.LockoutCache; import com.android.server.biometrics.sensors.LockoutResetDispatcher; import com.android.server.biometrics.sensors.LockoutTracker; -import com.android.server.biometrics.sensors.UserAwareBiometricScheduler; import com.android.server.biometrics.sensors.UserSwitchProvider; import com.android.server.biometrics.sensors.fingerprint.GestureAvailabilityDispatcher; @@ -77,12 +75,8 @@ public class SensorTest { @Mock private ISession mSession; @Mock - private UserAwareBiometricScheduler.UserSwitchCallback mUserSwitchCallback; - @Mock private UserSwitchProvider<IFingerprint, ISession> mUserSwitchProvider; @Mock - private AidlResponseHandler.HardwareUnavailableCallback mHardwareUnavailableCallback; - @Mock private LockoutResetDispatcher mLockoutResetDispatcher; @Mock private BiometricLogger mLogger; @@ -100,6 +94,8 @@ public class SensorTest { private BaseClientMonitor mClientMonitor; @Mock private HandlerThread mThread; + @Mock + AidlResponseHandler.AidlResponseHandlerCallback mAidlResponseHandlerCallback; private final TestLooper mLooper = new TestLooper(); private final LockoutCache mLockoutCache = new LockoutCache(); @@ -115,27 +111,17 @@ public class SensorTest { when(mBiometricContext.getAuthSessionCoordinator()).thenReturn(mAuthSessionCoordinator); when(mThread.getLooper()).thenReturn(mLooper.getLooper()); - if (Flags.deHidl()) { - mScheduler = new BiometricScheduler<>( - new Handler(mLooper.getLooper()), - BiometricScheduler.SENSOR_TYPE_FP_OTHER, - null /* gestureAvailabilityDispatcher */, - mBiometricService, - 2 /* recentOperationsLimit */, - () -> USER_ID, - mUserSwitchProvider); - } else { - mScheduler = new UserAwareBiometricScheduler<>(TAG, - new Handler(mLooper.getLooper()), - BiometricScheduler.SENSOR_TYPE_FP_OTHER, - null /* gestureAvailabilityDispatcher */, - mBiometricService, - () -> USER_ID, - mUserSwitchCallback); - } + mScheduler = new BiometricScheduler<>( + new Handler(mLooper.getLooper()), + BiometricScheduler.SENSOR_TYPE_FP_OTHER, + null /* gestureAvailabilityDispatcher */, + mBiometricService, + 2 /* recentOperationsLimit */, + () -> USER_ID, + mUserSwitchProvider); mHalCallback = new AidlResponseHandler(mContext, mScheduler, SENSOR_ID, USER_ID, mLockoutCache, mLockoutResetDispatcher, mAuthSessionCoordinator, - mHardwareUnavailableCallback); + mAidlResponseHandlerCallback); } @Test diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21Test.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21Test.java deleted file mode 100644 index 0d3f1921c947..000000000000 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21Test.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.biometrics.sensors.fingerprint.hidl; - -import static junit.framework.Assert.assertEquals; - -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.content.Context; -import android.content.res.Resources; -import android.hardware.biometrics.ComponentInfoInternal; -import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint; -import android.hardware.fingerprint.FingerprintSensorProperties; -import android.hardware.fingerprint.FingerprintSensorPropertiesInternal; -import android.os.Handler; -import android.os.Looper; -import android.os.UserManager; -import android.platform.test.annotations.Presubmit; - -import androidx.annotation.NonNull; -import androidx.test.InstrumentationRegistry; -import androidx.test.filters.SmallTest; - -import com.android.internal.R; -import com.android.server.biometrics.log.BiometricContext; -import com.android.server.biometrics.sensors.AuthenticationStateListeners; -import com.android.server.biometrics.sensors.BiometricScheduler; -import com.android.server.biometrics.sensors.BiometricStateCallback; -import com.android.server.biometrics.sensors.LockoutResetDispatcher; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.ArrayList; -import java.util.List; - -@Presubmit -@SmallTest -public class Fingerprint21Test { - - private static final String TAG = "Fingerprint21Test"; - private static final int SENSOR_ID = 1; - - @Mock - private Context mContext; - @Mock - private Resources mResources; - @Mock - private UserManager mUserManager; - @Mock - Fingerprint21.HalResultController mHalResultController; - @Mock - private BiometricScheduler mScheduler; - @Mock - private AuthenticationStateListeners mAuthenticationStateListeners; - @Mock - private BiometricStateCallback mBiometricStateCallback; - @Mock - private BiometricContext mBiometricContext; - - private LockoutResetDispatcher mLockoutResetDispatcher; - private Fingerprint21 mFingerprint21; - - private static void waitForIdle() { - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager); - when(mUserManager.getAliveUsers()).thenReturn(new ArrayList<>()); - when(mContext.getResources()).thenReturn(mResources); - when(mResources.getInteger(eq(R.integer.config_fingerprintMaxTemplatesPerUser))) - .thenReturn(5); - - mLockoutResetDispatcher = new LockoutResetDispatcher(mContext); - - final int maxEnrollmentsPerUser = 1; - final List<ComponentInfoInternal> componentInfo = new ArrayList<>(); - final boolean resetLockoutRequiresHardwareAuthToken = false; - final FingerprintSensorPropertiesInternal sensorProps = - new FingerprintSensorPropertiesInternal(SENSOR_ID, - FingerprintSensorProperties.STRENGTH_WEAK, maxEnrollmentsPerUser, - componentInfo, FingerprintSensorProperties.TYPE_UNKNOWN, - resetLockoutRequiresHardwareAuthToken); - - mFingerprint21 = new TestableFingerprint21(mContext, mBiometricStateCallback, - mAuthenticationStateListeners, sensorProps, mScheduler, - new Handler(Looper.getMainLooper()), mLockoutResetDispatcher, mHalResultController, - mBiometricContext); - } - - @Test - public void getAuthenticatorId_doesNotCrashWhenIdNotFound() { - assertEquals(0, mFingerprint21.getAuthenticatorId(0 /* sensorId */, 111 /* userId */)); - waitForIdle(); - } - - @Test - public void halServiceDied_resetsScheduler() { - // It's difficult to test the linkToDeath --> serviceDied path, so let's just invoke - // serviceDied directly. - mFingerprint21.serviceDied(0 /* cookie */); - waitForIdle(); - verify(mScheduler).reset(); - } - - private static class TestableFingerprint21 extends Fingerprint21 { - - TestableFingerprint21(@NonNull Context context, - @NonNull BiometricStateCallback biometricStateCallback, - @NonNull AuthenticationStateListeners authenticationStateListeners, - @NonNull FingerprintSensorPropertiesInternal sensorProps, - @NonNull BiometricScheduler scheduler, @NonNull Handler handler, - @NonNull LockoutResetDispatcher lockoutResetDispatcher, - @NonNull HalResultController controller, - @NonNull BiometricContext biometricContext) { - super(context, biometricStateCallback, authenticationStateListeners, sensorProps, - scheduler, handler, lockoutResetDispatcher, controller, biometricContext); - } - - @Override - synchronized IBiometricsFingerprint getDaemon() { - return mock(IBiometricsFingerprint.class); - } - } -} |