Revert "[DO NOT MERGE] Do not clear calling identify when using BiometricPrompt from FingerprintService."

This reverts commit 2d60fb3647a838c4c7f10c6f98bf98be4508b119.

Reason for revert: CTS failure functional regression. More info can be found in this bug: b/214261879

Change-Id: I596ba36f6bd433cb9457c21b0bc2294baafc21b2
(cherry picked from commit 12d48b137afc9a678e597ccb3d9978db775a4f1b)
Merged-In: I596ba36f6bd433cb9457c21b0bc2294baafc21b2
diff --git a/core/java/android/hardware/biometrics/BiometricPrompt.java b/core/java/android/hardware/biometrics/BiometricPrompt.java
index 520234b..6b5bec9 100644
--- a/core/java/android/hardware/biometrics/BiometricPrompt.java
+++ b/core/java/android/hardware/biometrics/BiometricPrompt.java
@@ -421,18 +421,6 @@
         }
 
         /**
-         * Set if BiometricPrompt is being used by the legacy fingerprint manager API.
-         * @param sensorId sensor id
-         * @return This builder.
-         * @hide
-         */
-        @NonNull
-        public Builder setIsForLegacyFingerprintManager(int sensorId) {
-            mPromptInfo.setIsForLegacyFingerprintManager(sensorId);
-            return this;
-        }
-
-        /**
          * Creates a {@link BiometricPrompt}.
          *
          * @return An instance of {@link BiometricPrompt}.
@@ -873,36 +861,28 @@
             @NonNull @CallbackExecutor Executor executor,
             @NonNull AuthenticationCallback callback,
             int userId) {
-        if (cancel == null) {
-            throw new IllegalArgumentException("Must supply a cancellation signal");
-        }
-        if (executor == null) {
-            throw new IllegalArgumentException("Must supply an executor");
-        }
-        if (callback == null) {
-            throw new IllegalArgumentException("Must supply a callback");
-        }
-
-        authenticateInternal(0 /* operationId */, cancel, executor, callback, userId);
+        authenticateUserForOperation(cancel, executor, callback, userId, 0 /* operationId */);
     }
 
     /**
-     * Authenticates for the given keystore operation.
+     * Authenticates for the given user and keystore operation.
      *
      * @param cancel An object that can be used to cancel authentication
      * @param executor An executor to handle callback events
      * @param callback An object to receive authentication events
+     * @param userId The user to authenticate
      * @param operationId The keystore operation associated with authentication
      *
      * @return A requestId that can be used to cancel this operation.
      *
      * @hide
      */
-    @RequiresPermission(USE_BIOMETRIC)
-    public long authenticateForOperation(
+    @RequiresPermission(USE_BIOMETRIC_INTERNAL)
+    public long authenticateUserForOperation(
             @NonNull CancellationSignal cancel,
             @NonNull @CallbackExecutor Executor executor,
             @NonNull AuthenticationCallback callback,
+            int userId,
             long operationId) {
         if (cancel == null) {
             throw new IllegalArgumentException("Must supply a cancellation signal");
@@ -914,7 +894,7 @@
             throw new IllegalArgumentException("Must supply a callback");
         }
 
-        return authenticateInternal(operationId, cancel, executor, callback, mContext.getUserId());
+        return authenticateInternal(operationId, cancel, executor, callback, userId);
     }
 
     /**
@@ -1048,7 +1028,7 @@
     private void cancelAuthentication(long requestId) {
         if (mService != null) {
             try {
-                mService.cancelAuthentication(mToken, mContext.getPackageName(), requestId);
+                mService.cancelAuthentication(mToken, mContext.getOpPackageName(), requestId);
             } catch (RemoteException e) {
                 Log.e(TAG, "Unable to cancel authentication", e);
             }
@@ -1107,7 +1087,7 @@
             }
 
             final long authId = mService.authenticate(mToken, operationId, userId,
-                    mBiometricServiceReceiver, mContext.getPackageName(), promptInfo);
+                    mBiometricServiceReceiver, mContext.getOpPackageName(), promptInfo);
             cancel.setOnCancelListener(new OnAuthenticationCancelListener(authId));
             return authId;
         } catch (RemoteException e) {
diff --git a/core/java/android/hardware/biometrics/ITestSessionCallback.aidl b/core/java/android/hardware/biometrics/ITestSessionCallback.aidl
index b336a9f..3d9517f 100644
--- a/core/java/android/hardware/biometrics/ITestSessionCallback.aidl
+++ b/core/java/android/hardware/biometrics/ITestSessionCallback.aidl
@@ -19,7 +19,7 @@
  * ITestSession callback for FingerprintManager and BiometricManager.
  * @hide
  */
-oneway interface ITestSessionCallback {
+interface ITestSessionCallback {
     void onCleanupStarted(int userId);
     void onCleanupFinished(int userId);
 }
diff --git a/core/java/android/hardware/biometrics/PromptInfo.java b/core/java/android/hardware/biometrics/PromptInfo.java
index 2742f0e..e6b762a 100644
--- a/core/java/android/hardware/biometrics/PromptInfo.java
+++ b/core/java/android/hardware/biometrics/PromptInfo.java
@@ -46,7 +46,6 @@
     @NonNull private List<Integer> mAllowedSensorIds = new ArrayList<>();
     private boolean mAllowBackgroundAuthentication;
     private boolean mIgnoreEnrollmentState;
-    private boolean mIsForLegacyFingerprintManager = false;
 
     public PromptInfo() {
 
@@ -69,7 +68,6 @@
         mAllowedSensorIds = in.readArrayList(Integer.class.getClassLoader());
         mAllowBackgroundAuthentication = in.readBoolean();
         mIgnoreEnrollmentState = in.readBoolean();
-        mIsForLegacyFingerprintManager = in.readBoolean();
     }
 
     public static final Creator<PromptInfo> CREATOR = new Creator<PromptInfo>() {
@@ -107,15 +105,10 @@
         dest.writeList(mAllowedSensorIds);
         dest.writeBoolean(mAllowBackgroundAuthentication);
         dest.writeBoolean(mIgnoreEnrollmentState);
-        dest.writeBoolean(mIsForLegacyFingerprintManager);
     }
 
     public boolean containsTestConfigurations() {
-        if (mIsForLegacyFingerprintManager
-                && mAllowedSensorIds.size() == 1
-                && !mAllowBackgroundAuthentication) {
-            return false;
-        } else if (!mAllowedSensorIds.isEmpty()) {
+        if (!mAllowedSensorIds.isEmpty()) {
             return true;
         } else if (mAllowBackgroundAuthentication) {
             return true;
@@ -195,8 +188,7 @@
     }
 
     public void setAllowedSensorIds(@NonNull List<Integer> sensorIds) {
-        mAllowedSensorIds.clear();
-        mAllowedSensorIds.addAll(sensorIds);
+        mAllowedSensorIds = sensorIds;
     }
 
     public void setAllowBackgroundAuthentication(boolean allow) {
@@ -207,12 +199,6 @@
         mIgnoreEnrollmentState = ignoreEnrollmentState;
     }
 
-    public void setIsForLegacyFingerprintManager(int sensorId) {
-        mIsForLegacyFingerprintManager = true;
-        mAllowedSensorIds.clear();
-        mAllowedSensorIds.add(sensorId);
-    }
-
     // Getters
 
     public CharSequence getTitle() {
@@ -286,8 +272,4 @@
     public boolean isIgnoreEnrollmentState() {
         return mIgnoreEnrollmentState;
     }
-
-    public boolean isForLegacyFingerprintManager() {
-        return mIsForLegacyFingerprintManager;
-    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
index 7ab214e..df20b83 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
@@ -134,7 +134,7 @@
     private class BiometricTaskStackListener extends TaskStackListener {
         @Override
         public void onTaskStackChanged() {
-            mHandler.post(AuthController.this::cancelIfOwnerIsNotInForeground);
+            mHandler.post(AuthController.this::handleTaskStackChanged);
         }
     }
 
@@ -181,7 +181,7 @@
         }
     };
 
-    private void cancelIfOwnerIsNotInForeground() {
+    private void handleTaskStackChanged() {
         mExecution.assertIsMainThread();
         if (mCurrentDialog != null) {
             try {
@@ -193,7 +193,7 @@
                     final String topPackage = runningTasks.get(0).topActivity.getPackageName();
                     if (!topPackage.contentEquals(clientPackage)
                             && !Utils.isSystem(mContext, clientPackage)) {
-                        Log.e(TAG, "Evicting client due to: " + topPackage);
+                        Log.w(TAG, "Evicting client due to: " + topPackage);
                         mCurrentDialog.dismissWithoutCallback(true /* animate */);
                         mCurrentDialog = null;
                         mOrientationListener.disable();
@@ -814,10 +814,6 @@
         mCurrentDialog = newDialog;
         mCurrentDialog.show(mWindowManager, savedState);
         mOrientationListener.enable();
-
-        if (!promptInfo.isAllowBackgroundAuthentication()) {
-            mHandler.post(this::cancelIfOwnerIsNotInForeground);
-        }
     }
 
     private void onDialogDismissed(@DismissedReason int reason) {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
index 2b7c984..08c7714 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
@@ -555,25 +555,15 @@
     }
 
     @Test
-    public void testClientNotified_whenTaskStackChangesDuringShow() throws Exception {
-        switchTask("other_package");
-        showDialog(new int[] {1} /* sensorIds */, false /* credentialAllowed */);
-
-        mTestableLooper.processAllMessages();
-
-        assertNull(mAuthController.mCurrentDialog);
-        assertNull(mAuthController.mReceiver);
-        verify(mDialog1).dismissWithoutCallback(true /* animate */);
-        verify(mReceiver).onDialogDismissed(
-                eq(BiometricPrompt.DISMISSED_REASON_USER_CANCEL),
-                eq(null) /* credentialAttestation */);
-    }
-
-    @Test
     public void testClientNotified_whenTaskStackChangesDuringAuthentication() throws Exception {
         showDialog(new int[] {1} /* sensorIds */, false /* credentialAllowed */);
 
-        switchTask("other_package");
+        List<ActivityManager.RunningTaskInfo> tasks = new ArrayList<>();
+        ActivityManager.RunningTaskInfo taskInfo = mock(ActivityManager.RunningTaskInfo.class);
+        taskInfo.topActivity = mock(ComponentName.class);
+        when(taskInfo.topActivity.getPackageName()).thenReturn("other_package");
+        tasks.add(taskInfo);
+        when(mActivityTaskManager.getTasks(anyInt())).thenReturn(tasks);
 
         mAuthController.mTaskStackListener.onTaskStackChanged();
         mTestableLooper.processAllMessages();
@@ -650,16 +640,6 @@
                 BIOMETRIC_MULTI_SENSOR_FACE_THEN_FINGERPRINT);
     }
 
-    private void switchTask(String packageName) {
-        final List<ActivityManager.RunningTaskInfo> tasks = new ArrayList<>();
-        final ActivityManager.RunningTaskInfo taskInfo =
-                mock(ActivityManager.RunningTaskInfo.class);
-        taskInfo.topActivity = mock(ComponentName.class);
-        when(taskInfo.topActivity.getPackageName()).thenReturn(packageName);
-        tasks.add(taskInfo);
-        when(mActivityTaskManager.getTasks(anyInt())).thenReturn(tasks);
-    }
-
     private PromptInfo createTestPromptInfo() {
         PromptInfo promptInfo = new PromptInfo();
 
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 92c8c9b..358263d 100644
--- a/services/core/java/com/android/server/biometrics/sensors/AuthenticationClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/AuthenticationClient.java
@@ -118,7 +118,7 @@
         mIsStrongBiometric = isStrongBiometric;
         mOperationId = operationId;
         mRequireConfirmation = requireConfirmation;
-        mActivityTaskManager = getActivityTaskManager();
+        mActivityTaskManager = ActivityTaskManager.getInstance();
         mBiometricManager = context.getSystemService(BiometricManager.class);
         mTaskStackListener = taskStackListener;
         mLockoutTracker = lockoutTracker;
@@ -146,10 +146,6 @@
         return mStartTimeMs;
     }
 
-    protected ActivityTaskManager getActivityTaskManager() {
-        return ActivityTaskManager.getInstance();
-    }
-
     @Override
     public void binderDied() {
         final boolean clearListener = !isBiometricPrompt();
@@ -326,50 +322,45 @@
                     sendCancelOnly(listener);
                 }
             });
-        } else { // not authenticated
-            if (isBackgroundAuth) {
-                Slog.e(TAG, "cancelling due to background auth");
-                cancel();
-            } else {
-                // Allow system-defined limit of number of attempts before giving up
-                final @LockoutTracker.LockoutMode int lockoutMode =
-                        handleFailedAttempt(getTargetUserId());
-                if (lockoutMode != LockoutTracker.LOCKOUT_NONE) {
-                    markAlreadyDone();
+        } else {
+            // Allow system-defined limit of number of attempts before giving up
+            final @LockoutTracker.LockoutMode int lockoutMode =
+                    handleFailedAttempt(getTargetUserId());
+            if (lockoutMode != LockoutTracker.LOCKOUT_NONE) {
+                markAlreadyDone();
+            }
+
+            final CoexCoordinator coordinator = CoexCoordinator.getInstance();
+            coordinator.onAuthenticationRejected(SystemClock.uptimeMillis(), this, lockoutMode,
+                    new CoexCoordinator.Callback() {
+                @Override
+                public void sendAuthenticationResult(boolean addAuthTokenIfStrong) {
+                    if (listener != null) {
+                        try {
+                            listener.onAuthenticationFailed(getSensorId());
+                        } catch (RemoteException e) {
+                            Slog.e(TAG, "Unable to notify listener", e);
+                        }
+                    }
                 }
 
-                final CoexCoordinator coordinator = CoexCoordinator.getInstance();
-                coordinator.onAuthenticationRejected(SystemClock.uptimeMillis(), this, lockoutMode,
-                        new CoexCoordinator.Callback() {
-                            @Override
-                            public void sendAuthenticationResult(boolean addAuthTokenIfStrong) {
-                                if (listener != null) {
-                                    try {
-                                        listener.onAuthenticationFailed(getSensorId());
-                                    } catch (RemoteException e) {
-                                        Slog.e(TAG, "Unable to notify listener", e);
-                                    }
-                                }
-                            }
+                @Override
+                public void sendHapticFeedback() {
+                    if (listener != null && mShouldVibrate) {
+                        vibrateError();
+                    }
+                }
 
-                            @Override
-                            public void sendHapticFeedback() {
-                                if (listener != null && mShouldVibrate) {
-                                    vibrateError();
-                                }
-                            }
+                @Override
+                public void handleLifecycleAfterAuth() {
+                    AuthenticationClient.this.handleLifecycleAfterAuth(false /* authenticated */);
+                }
 
-                            @Override
-                            public void handleLifecycleAfterAuth() {
-                                AuthenticationClient.this.handleLifecycleAfterAuth(false /* authenticated */);
-                            }
-
-                            @Override
-                            public void sendAuthenticationCanceled() {
-                                sendCancelOnly(listener);
-                            }
-                        });
-            }
+                @Override
+                public void sendAuthenticationCanceled() {
+                    sendCancelOnly(listener);
+                }
+            });
         }
     }
 
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 3a93d82..b44f4dc 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
@@ -331,12 +331,12 @@
                     provider.second.getSensorProperties(sensorId);
             if (!isKeyguard && !Utils.isSettings(getContext(), opPackageName)
                     && sensorProps != null && sensorProps.isAnyUdfpsType()) {
+                identity = Binder.clearCallingIdentity();
                 try {
                     return authenticateWithPrompt(operationId, sensorProps, userId, receiver,
-                            opPackageName, ignoreEnrollmentState);
-                } catch (PackageManager.NameNotFoundException e) {
-                    Slog.e(TAG, "Invalid package", e);
-                    return -1;
+                            ignoreEnrollmentState);
+                } finally {
+                    Binder.restoreCallingIdentity(identity);
                 }
             }
             return provider.second.scheduleAuthenticate(provider.first, token, operationId, userId,
@@ -349,15 +349,12 @@
                 @NonNull final FingerprintSensorPropertiesInternal props,
                 final int userId,
                 final IFingerprintServiceReceiver receiver,
-                final String opPackageName,
-                boolean ignoreEnrollmentState) throws PackageManager.NameNotFoundException {
+                boolean ignoreEnrollmentState) {
 
             final Context context = getUiContext();
-            final Context promptContext = context.createPackageContextAsUser(
-                    opPackageName, 0 /* flags */, UserHandle.getUserHandleForUid(userId));
             final Executor executor = context.getMainExecutor();
 
-            final BiometricPrompt biometricPrompt = new BiometricPrompt.Builder(promptContext)
+            final BiometricPrompt biometricPrompt = new BiometricPrompt.Builder(context)
                     .setTitle(context.getString(R.string.biometric_dialog_default_title))
                     .setSubtitle(context.getString(R.string.fingerprint_dialog_default_subtitle))
                     .setNegativeButton(
@@ -371,7 +368,8 @@
                                     Slog.e(TAG, "Remote exception in negative button onClick()", e);
                                 }
                             })
-                    .setIsForLegacyFingerprintManager(props.sensorId)
+                    .setAllowedSensorIds(new ArrayList<>(
+                            Collections.singletonList(props.sensorId)))
                     .setIgnoreEnrollmentState(ignoreEnrollmentState)
                     .build();
 
@@ -425,8 +423,8 @@
                         }
                     };
 
-            return biometricPrompt.authenticateForOperation(
-                    new CancellationSignal(), executor, promptCallback, operationId);
+            return biometricPrompt.authenticateUserForOperation(
+                    new CancellationSignal(), executor, promptCallback, userId, operationId);
         }
 
         @Override