Merge changes from topic "nearby_stopXXX_permission" into tm-dev

* changes:
  Enable the integration test for NearbyManager.stopXXX.
  Add log for stopXXX methods when the callback never registered
  Enforce permissions in stopBroadcast and unregisterScanListener methods
diff --git a/nearby/framework/java/android/nearby/INearbyManager.aidl b/nearby/framework/java/android/nearby/INearbyManager.aidl
index 3fd5ecc..0291fff 100644
--- a/nearby/framework/java/android/nearby/INearbyManager.aidl
+++ b/nearby/framework/java/android/nearby/INearbyManager.aidl
@@ -31,10 +31,10 @@
     int registerScanListener(in ScanRequest scanRequest, in IScanListener listener,
             String packageName, @nullable String attributionTag);
 
-    void unregisterScanListener(in IScanListener listener);
+    void unregisterScanListener(in IScanListener listener, String packageName, @nullable String attributionTag);
 
     void startBroadcast(in BroadcastRequestParcelable broadcastRequest,
             in IBroadcastListener callback, String packageName, @nullable String attributionTag);
 
-    void stopBroadcast(in IBroadcastListener callback);
+    void stopBroadcast(in IBroadcastListener callback, String packageName, @nullable String attributionTag);
 }
\ No newline at end of file
diff --git a/nearby/framework/java/android/nearby/NearbyManager.java b/nearby/framework/java/android/nearby/NearbyManager.java
index 9073f78..106c290 100644
--- a/nearby/framework/java/android/nearby/NearbyManager.java
+++ b/nearby/framework/java/android/nearby/NearbyManager.java
@@ -70,6 +70,8 @@
         int ERROR = 2;
     }
 
+    private static final String TAG = "NearbyManager";
+
     /**
      * Whether allows Fast Pair to scan.
      *
@@ -204,7 +206,11 @@
                 ScanListenerTransport transport = reference != null ? reference.get() : null;
                 if (transport != null) {
                     transport.unregister();
-                    mService.unregisterScanListener(transport);
+                    mService.unregisterScanListener(transport, mContext.getPackageName(),
+                            mContext.getAttributionTag());
+                } else {
+                    Log.e(TAG, "Cannot stop scan with this callback "
+                            + "because it is never registered.");
                 }
             }
         } catch (RemoteException e) {
@@ -259,7 +265,11 @@
                 BroadcastListenerTransport transport = reference != null ? reference.get() : null;
                 if (transport != null) {
                     transport.unregister();
-                    mService.stopBroadcast(transport);
+                    mService.stopBroadcast(transport, mContext.getPackageName(),
+                            mContext.getAttributionTag());
+                } else {
+                    Log.e(TAG, "Cannot stop broadcast with this callback "
+                            + "because it is never registered.");
                 }
             }
         } catch (RemoteException e) {
diff --git a/nearby/service/java/com/android/server/nearby/NearbyService.java b/nearby/service/java/com/android/server/nearby/NearbyService.java
index 2dee835..b9e98a2 100644
--- a/nearby/service/java/com/android/server/nearby/NearbyService.java
+++ b/nearby/service/java/com/android/server/nearby/NearbyService.java
@@ -110,22 +110,36 @@
     }
 
     @Override
-    public void unregisterScanListener(IScanListener listener) {
+    public void unregisterScanListener(IScanListener listener, String packageName,
+            @Nullable String attributionTag) {
+        // Permissions check
+        enforceBluetoothPrivilegedPermission(mContext);
+        CallerIdentity identity = CallerIdentity.fromBinder(mContext, packageName, attributionTag);
+        DiscoveryPermissions.enforceDiscoveryPermission(mContext, identity);
+
         mProviderManager.unregisterScanListener(listener);
     }
 
     @Override
     public void startBroadcast(BroadcastRequestParcelable broadcastRequestParcelable,
             IBroadcastListener listener, String packageName, @Nullable String attributionTag) {
+        // Permissions check
         enforceBluetoothPrivilegedPermission(mContext);
         BroadcastPermissions.enforceBroadcastPermission(
                 mContext, CallerIdentity.fromBinder(mContext, packageName, attributionTag));
+
         mBroadcastProviderManager.startBroadcast(
                 broadcastRequestParcelable.getBroadcastRequest(), listener);
     }
 
     @Override
-    public void stopBroadcast(IBroadcastListener listener) {
+    public void stopBroadcast(IBroadcastListener listener, String packageName,
+            @Nullable String attributionTag) {
+        // Permissions check
+        enforceBluetoothPrivilegedPermission(mContext);
+        CallerIdentity identity = CallerIdentity.fromBinder(mContext, packageName, attributionTag);
+        BroadcastPermissions.enforceBroadcastPermission(mContext, identity);
+
         mBroadcastProviderManager.stopBroadcast(listener);
     }
 
diff --git a/nearby/tests/cts/fastpair/src/android/nearby/cts/NearbyManagerTest.java b/nearby/tests/cts/fastpair/src/android/nearby/cts/NearbyManagerTest.java
index 6824ca6..483bfe8 100644
--- a/nearby/tests/cts/fastpair/src/android/nearby/cts/NearbyManagerTest.java
+++ b/nearby/tests/cts/fastpair/src/android/nearby/cts/NearbyManagerTest.java
@@ -128,6 +128,13 @@
 
     @Test
     @SdkSuppress(minSdkVersion = 32, codeName = "T")
+    public void test_stopScan_noPrivilegedPermission() {
+        mUiAutomation.dropShellPermissionIdentity();
+        assertThrows(SecurityException.class, () -> mNearbyManager.stopScan(mScanCallback));
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 32, codeName = "T")
     public void testStartStopBroadcast() throws InterruptedException {
         PrivateCredential credential = new PrivateCredential.Builder(SECRETE_ID, AUTHENTICITY_KEY,
                 META_DATA_ENCRYPTION_KEY, DEVICE_NAME)
diff --git a/nearby/tests/integration/untrusted/Android.bp b/nearby/tests/integration/untrusted/Android.bp
index 53dbfb7..57499e4 100644
--- a/nearby/tests/integration/untrusted/Android.bp
+++ b/nearby/tests/integration/untrusted/Android.bp
@@ -21,10 +21,14 @@
     defaults: ["mts-target-sdk-version-current"],
     sdk_version: "test_current",
 
-    srcs: ["src/**/*.kt"],
+    srcs: [
+        "src/**/*.java",
+        "src/**/*.kt",
+    ],
     static_libs: [
         "androidx.test.ext.junit",
         "androidx.test.rules",
+        "androidx.test.uiautomator_uiautomator",
         "junit",
         "kotlin-test",
         "truth-prebuilt",
diff --git a/nearby/tests/integration/untrusted/src/android/nearby/integration/untrusted/NearbyManagerTest.kt b/nearby/tests/integration/untrusted/src/android/nearby/integration/untrusted/NearbyManagerTest.kt
index 3bfac6d..7bf9f63 100644
--- a/nearby/tests/integration/untrusted/src/android/nearby/integration/untrusted/NearbyManagerTest.kt
+++ b/nearby/tests/integration/untrusted/src/android/nearby/integration/untrusted/NearbyManagerTest.kt
@@ -28,12 +28,14 @@
 import android.nearby.ScanRequest
 import androidx.test.core.app.ApplicationProvider
 import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.uiautomator.LogcatWaitMixin
 import com.google.common.truth.Truth.assertThat
 import org.junit.Assert.assertThrows
 import org.junit.Before
-import org.junit.Ignore
 import org.junit.Test
 import org.junit.runner.RunWith
+import java.time.Duration
+import java.util.Calendar
 
 @RunWith(AndroidJUnit4::class)
 class NearbyManagerTest {
@@ -75,13 +77,9 @@
         }
     }
 
-    /**
-     * Verify untrusted app can't stop scan because it needs BLUETOOTH_PRIVILEGED
-     * permission which is not for use by third-party applications.
-     */
+    /** Verify untrusted app can't stop scan because it never successfully registers a callback. */
     @Test
-    @Ignore("Permission check for stopXXX not yet implement: b/229338477#comment24")
-    fun testNearbyManagerStopScan_fromUnTrustedApp_throwsException() {
+    fun testNearbyManagerStopScan_fromUnTrustedApp_logsError() {
         val nearbyManager = appContext.getSystemService(Context.NEARBY_SERVICE) as NearbyManager
         val scanCallback = object : ScanCallback {
             override fun onDiscovered(device: NearbyDevice) {}
@@ -90,10 +88,17 @@
 
             override fun onLost(device: NearbyDevice) {}
         }
+        val startTime = Calendar.getInstance().time
 
-        assertThrows(SecurityException::class.java) {
-            nearbyManager.stopScan(scanCallback)
-        }
+        nearbyManager.stopScan(scanCallback)
+
+        assertThat(
+            LogcatWaitMixin().waitForSpecificLog(
+                "Cannot stop scan with this callback because it is never registered.",
+                startTime,
+                WAIT_INVALID_OPERATIONS_LOGS_TIMEOUT
+            )
+        ).isTrue()
     }
 
     /**
@@ -127,17 +132,26 @@
     }
 
     /**
-     * Verify untrusted app can't stop broadcast because it needs BLUETOOTH_PRIVILEGED
-     * permission which is not for use by third-party applications.
+     * Verify untrusted app can't stop broadcast because it never successfully registers a callback.
      */
     @Test
-    @Ignore("Permission check for stopXXX not yet implement: b/229338477#comment24")
-    fun testNearbyManagerStopBroadcast_fromUnTrustedApp_throwsException() {
+    fun testNearbyManagerStopBroadcast_fromUnTrustedApp_logsError() {
         val nearbyManager = appContext.getSystemService(Context.NEARBY_SERVICE) as NearbyManager
         val broadcastCallback = BroadcastCallback { }
+        val startTime = Calendar.getInstance().time
 
-        assertThrows(SecurityException::class.java) {
-            nearbyManager.stopBroadcast(broadcastCallback)
-        }
+        nearbyManager.stopBroadcast(broadcastCallback)
+
+        assertThat(
+            LogcatWaitMixin().waitForSpecificLog(
+                "Cannot stop broadcast with this callback because it is never registered.",
+                startTime,
+                WAIT_INVALID_OPERATIONS_LOGS_TIMEOUT
+            )
+        ).isTrue()
+    }
+
+    companion object {
+        private val WAIT_INVALID_OPERATIONS_LOGS_TIMEOUT = Duration.ofSeconds(5)
     }
 }
diff --git a/nearby/tests/integration/untrusted/src/androidx/test/uiautomator/LogcatParser.kt b/nearby/tests/integration/untrusted/src/androidx/test/uiautomator/LogcatParser.kt
new file mode 100644
index 0000000..604e6df
--- /dev/null
+++ b/nearby/tests/integration/untrusted/src/androidx/test/uiautomator/LogcatParser.kt
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2022 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 androidx.test.uiautomator
+
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+/** A parser for logcat logs processing. */
+object LogcatParser {
+    private val LOGCAT_LOGS_PATTERN = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.\\d{3} ".toRegex()
+    private const val LOGCAT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"
+
+    /**
+     * Filters out the logcat logs which contains specific log and appears not before specific time.
+     *
+     * @param logcatLogs the concatenated logcat logs to filter
+     * @param specificLog the log string expected to appear
+     * @param startTime the time point to start finding the specific log
+     * @return a list of logs that match the condition
+     */
+    fun findSpecificLogAfter(
+        logcatLogs: String,
+        specificLog: String,
+        startTime: Date
+    ): List<String> = logcatLogs.split("\n")
+        .filter { it.contains(specificLog) && !parseLogTime(it)!!.before(startTime) }
+
+    /**
+     * Parses the logcat log string to extract the timestamp.
+     *
+     * @param logString the log string to parse
+     * @return the timestamp of the log
+     */
+    private fun parseLogTime(logString: String): Date? =
+        SimpleDateFormat(LOGCAT_DATE_FORMAT, Locale.US)
+            .parse(LOGCAT_LOGS_PATTERN.find(logString)!!.value)
+}
diff --git a/nearby/tests/integration/untrusted/src/androidx/test/uiautomator/LogcatWaitMixin.java b/nearby/tests/integration/untrusted/src/androidx/test/uiautomator/LogcatWaitMixin.java
new file mode 100644
index 0000000..86e39dc
--- /dev/null
+++ b/nearby/tests/integration/untrusted/src/androidx/test/uiautomator/LogcatWaitMixin.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2022 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 androidx.test.uiautomator;
+
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Date;
+
+/** A helper class to wait the specific log appear in the logcat logs. */
+public class LogcatWaitMixin extends WaitMixin<UiDevice> {
+
+    private static final String LOG_TAG = LogcatWaitMixin.class.getSimpleName();
+
+    public LogcatWaitMixin() {
+        this(UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()));
+    }
+
+    public LogcatWaitMixin(UiDevice device) {
+        super(device);
+    }
+
+    /**
+     * Waits the {@code specificLog} appear in the logcat logs after the specific {@code startTime}.
+     *
+     * @param waitTime the maximum time for waiting
+     * @return true if the specific log appear within timeout and after the startTime
+     */
+    public boolean waitForSpecificLog(
+            @NonNull String specificLog, @NonNull Date startTime, @NonNull Duration waitTime) {
+        return wait(createWaitCondition(specificLog, startTime), waitTime.toMillis());
+    }
+
+    @NonNull
+    Condition<UiDevice, Boolean> createWaitCondition(
+            @NonNull String specificLog, @NonNull Date startTime) {
+        return new Condition<UiDevice, Boolean>() {
+            @Override
+            Boolean apply(UiDevice device) {
+                String logcatLogs;
+                try {
+                    logcatLogs = device.executeShellCommand("logcat -v time -v year -d");
+                } catch (IOException e) {
+                    Log.e(LOG_TAG, "Fail to dump logcat logs on the device!", e);
+                    return Boolean.FALSE;
+                }
+                return !LogcatParser.INSTANCE
+                        .findSpecificLogAfter(logcatLogs, specificLog, startTime)
+                        .isEmpty();
+            }
+        };
+    }
+}
diff --git a/nearby/tests/unit/src/com/android/server/nearby/NearbyServiceTest.java b/nearby/tests/unit/src/com/android/server/nearby/NearbyServiceTest.java
index e250254..8a18cca 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/NearbyServiceTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/NearbyServiceTest.java
@@ -87,8 +87,19 @@
     }
 
     @Test
+    public void test_unregister_noPrivilegedPermission_throwsException() {
+        mUiAutomation.dropShellPermissionIdentity();
+        assertThrows(java.lang.SecurityException.class,
+                () -> mService.unregisterScanListener(mScanListener, PACKAGE_NAME,
+                        /* attributionTag= */ null));
+    }
+
+    @Test
     public void test_unregister() {
-        mService.unregisterScanListener(mScanListener);
+        setMockInjector(/* isMockOpsAllowed= */ true);
+        mService.registerScanListener(mScanRequest, mScanListener, PACKAGE_NAME,
+                /* attributionTag= */ null);
+        mService.unregisterScanListener(mScanListener,  PACKAGE_NAME, /* attributionTag= */ null);
     }
 
     private ScanRequest createScanRequest() {