Add tests for MEDIA_ROUTING_CONTROL enforcement

Bug: 305919655
Bug: 192657812
Test: atest ProxyMediaRouter2HostSideTest
Change-Id: I5d669f6ebeb24ed7b03f90b7029cbba3a5f15c11
diff --git a/hostsidetests/media/Android.bp b/hostsidetests/media/Android.bp
index 5fa5e26..86d064c 100644
--- a/hostsidetests/media/Android.bp
+++ b/hostsidetests/media/Android.bp
@@ -46,6 +46,7 @@
         ":CtsMediaMetricsHostTestApp",
         ":CtsMediaRouterHostSideTestBluetoothPermissionsApp",
         ":CtsMediaRouterHostSideTestModifyAudioRoutingApp",
+        ":CtsMediaRouterHostSideTestMediaRoutingControlApp",
         ":CtsMediaRouterHostSideTestProviderApp1",
         ":CtsMediaRouterHostSideTestProviderApp2",
         ":CtsMediaRouterHostSideTestProviderApp3",
diff --git a/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/Android.bp b/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/Android.bp
new file mode 100644
index 0000000..65e02b8
--- /dev/null
+++ b/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/Android.bp
@@ -0,0 +1,41 @@
+// Copyright 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CtsMediaRouterHostSideTestMediaRoutingControlApp",
+    defaults: ["cts_defaults"],
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+    srcs: [
+        "src/**/*.java",
+    ],
+    platform_apis: true, // This test uses private APIs.
+    libs: [
+        "CtsMediaHostTestCommon",
+    ],
+    static_libs: [
+        "androidx.test.core",
+        "androidx.test.ext.junit",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
+        "flag-junit",
+        "com.android.media.flags.bettertogether-aconfig-java",
+    ],
+}
diff --git a/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/AndroidManifest.xml b/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/AndroidManifest.xml
new file mode 100644
index 0000000..b77e5a3
--- /dev/null
+++ b/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/AndroidManifest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.media.router.cts.proxyroutingapp"
+          android:targetSandboxVersion="2">
+
+    <uses-permission android:name="android.permission.MEDIA_ROUTING_CONTROL" />
+
+    <application android:testOnly="true">
+        <uses-library android:name="android.test.runner"/>
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.media.router.cts.proxyroutingapp"
+                     android:label="Proxy routing app for MediaRouter2 hostside tests."/>
+</manifest>
diff --git a/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/src/android/media/router/cts/proxyroutingapp/MediaRouter2DeviceTest.java b/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/src/android/media/router/cts/proxyroutingapp/MediaRouter2DeviceTest.java
new file mode 100644
index 0000000..ca0a9c4
--- /dev/null
+++ b/hostsidetests/media/app/ProxyMediaRouterMediaRoutingControl/src/android/media/router/cts/proxyroutingapp/MediaRouter2DeviceTest.java
@@ -0,0 +1,101 @@
+/*
+ * 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 android.media.router.cts.proxyroutingapp;
+
+import static android.media.cts.MediaRouterTestConstants.MEDIA_ROUTER_PROVIDER_1_PACKAGE;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.assertThrows;
+
+import android.Manifest;
+import android.annotation.SuppressLint;
+import android.app.Instrumentation;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.media.MediaRouter2;
+import android.platform.test.annotations.LargeTest;
+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 androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.media.flags.Flags;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+/** Device-side test for privileged {@link MediaRouter2} functionality. */
+@LargeTest
+public class MediaRouter2DeviceTest {
+
+    @Rule
+    public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
+
+    private Instrumentation mInstrumentation;
+    private Context mContext;
+
+    @Before
+    public void setUp() {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @SuppressLint("MissingPermission")
+    @Test
+    @RequiresFlagsDisabled(Flags.FLAG_ENABLE_PRIVILEGED_ROUTING_FOR_MEDIA_ROUTING_CONTROL)
+    public void getInstance_withMediaRoutingControl_flagDisabled_throwsSecurityException() {
+        mInstrumentation
+                .getUiAutomation()
+                .adoptShellPermissionIdentity(Manifest.permission.MEDIA_ROUTING_CONTROL);
+        try {
+            assertThrows(
+                    SecurityException.class,
+                    () -> MediaRouter2.getInstance(mContext, MEDIA_ROUTER_PROVIDER_1_PACKAGE));
+        } finally {
+            mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
+        }
+    }
+
+    @SuppressLint("MissingPermission")
+    @Test
+    @RequiresFlagsEnabled(Flags.FLAG_ENABLE_PRIVILEGED_ROUTING_FOR_MEDIA_ROUTING_CONTROL)
+    public void getInstance_withMediaRoutingControl_flagEnabled_doesNotThrow() {
+        mInstrumentation
+                .getUiAutomation()
+                .adoptShellPermissionIdentity(Manifest.permission.MEDIA_ROUTING_CONTROL);
+        try {
+            MediaRouter2.getInstance(mContext, MEDIA_ROUTER_PROVIDER_1_PACKAGE);
+        } finally {
+            mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
+        }
+    }
+
+    @SuppressLint("MissingPermission")
+    @Test
+    public void getInstance_withoutMediaRoutingControl_throwsSecurityException() {
+        assertThat(mContext.checkCallingOrSelfPermission(Manifest.permission.MEDIA_ROUTING_CONTROL))
+                .isEqualTo(PackageManager.PERMISSION_DENIED);
+
+        assertThrows(
+                SecurityException.class,
+                () -> MediaRouter2.getInstance(mContext, MEDIA_ROUTER_PROVIDER_1_PACKAGE));
+    }
+}
diff --git a/hostsidetests/media/common/android/media/cts/MediaRouterTestConstants.java b/hostsidetests/media/common/android/media/cts/MediaRouterTestConstants.java
index 641956b..795d19d 100644
--- a/hostsidetests/media/common/android/media/cts/MediaRouterTestConstants.java
+++ b/hostsidetests/media/common/android/media/cts/MediaRouterTestConstants.java
@@ -51,6 +51,14 @@
     public static final String DEVICE_SIDE_TEST_CLASS_WITH_MODIFY_AUDIO_ROUTING =
             "android.media.router.cts.modifyaudioroutingapp"
                     + ".MediaRouter2DeviceTestWithModifyAudioRouting";
+    public static final String PROXY_MEDIA_ROUTER_APP_PACKAGE =
+            "android.media.router.cts.proxyroutingapp";
+
+    public static final String PROXY_MEDIA_ROUTER_APP_APK =
+            "CtsMediaRouterHostSideTestMediaRoutingControlApp.apk";
+
+    public static final String PROXY_MEDIA_ROUTER_APP_TEST_CLASS =
+            "android.media.router.cts.proxyroutingapp.MediaRouter2DeviceTest";
 
     public static final String ROUTE_ID_APP_1_ROUTE_1 = "route_1-1";
     public static final String ROUTE_ID_APP_1_ROUTE_2 = "route_1-2";
diff --git a/hostsidetests/media/src/android/media/router/cts/ProxyMediaRouter2HostSideTest.java b/hostsidetests/media/src/android/media/router/cts/ProxyMediaRouter2HostSideTest.java
new file mode 100644
index 0000000..b67ed95
--- /dev/null
+++ b/hostsidetests/media/src/android/media/router/cts/ProxyMediaRouter2HostSideTest.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2023 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 android.media.router.cts;
+
+import static android.media.cts.MediaRouterTestConstants.MEDIA_ROUTER_PROVIDER_1_APK;
+import static android.media.cts.MediaRouterTestConstants.MEDIA_ROUTER_PROVIDER_1_PACKAGE;
+import static android.media.cts.MediaRouterTestConstants.PROXY_MEDIA_ROUTER_APP_APK;
+import static android.media.cts.MediaRouterTestConstants.PROXY_MEDIA_ROUTER_APP_PACKAGE;
+import static android.media.cts.MediaRouterTestConstants.PROXY_MEDIA_ROUTER_APP_TEST_CLASS;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.RequiresDevice;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.invoker.TestInformation;
+import com.android.tradefed.log.LogUtil;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.AfterClassWithInfo;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import com.android.tradefed.testtype.junit4.BeforeClassWithInfo;
+
+import com.google.common.truth.Expect;
+
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.FileNotFoundException;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class ProxyMediaRouter2HostSideTest extends BaseHostJUnit4Test {
+
+    @ClassRule public static final Expect expect = Expect.create();
+
+    @BeforeClassWithInfo
+    public static void installTestApps(TestInformation testInfo)
+            throws DeviceNotAvailableException, FileNotFoundException {
+        installTestApp(testInfo, PROXY_MEDIA_ROUTER_APP_APK);
+        installTestApp(testInfo, MEDIA_ROUTER_PROVIDER_1_APK);
+    }
+
+    @AfterClassWithInfo
+    public static void uninstallTestApps(TestInformation testInformation)
+            throws DeviceNotAvailableException {
+        ITestDevice device = testInformation.getDevice();
+        expect.that(device.uninstallPackage(MEDIA_ROUTER_PROVIDER_1_PACKAGE)).isNull();
+        expect.that(device.uninstallPackage(PROXY_MEDIA_ROUTER_APP_PACKAGE)).isNull();
+    }
+
+    @Test
+    @AppModeFull
+    @RequiresDevice
+    public void getInstance_withMediaRoutingControl_flagEnabled_doesNotThrow()
+            throws DeviceNotAvailableException {
+        runDeviceTests(
+                PROXY_MEDIA_ROUTER_APP_PACKAGE,
+                PROXY_MEDIA_ROUTER_APP_TEST_CLASS,
+                "getInstance_withMediaRoutingControl_flagEnabled_doesNotThrow");
+    }
+
+    @Test
+    @AppModeFull
+    @RequiresDevice
+    public void getInstance_withMediaRoutingControl_flagDisabled_throwsSecurityException()
+            throws DeviceNotAvailableException {
+        runDeviceTests(
+                PROXY_MEDIA_ROUTER_APP_PACKAGE,
+                PROXY_MEDIA_ROUTER_APP_TEST_CLASS,
+                "getInstance_withMediaRoutingControl_flagDisabled_throwsSecurityException");
+    }
+
+    @Test
+    @AppModeFull
+    @RequiresDevice
+    public void getInstance_withoutMediaRoutingControl_throwsSecurityException()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        runDeviceTests(
+                PROXY_MEDIA_ROUTER_APP_PACKAGE,
+                PROXY_MEDIA_ROUTER_APP_TEST_CLASS,
+                "getInstance_withoutMediaRoutingControl_throwsSecurityException");
+    }
+
+    private static void installTestApp(TestInformation testInfo, String apkName)
+            throws FileNotFoundException, DeviceNotAvailableException {
+        LogUtil.CLog.d("Installing app " + apkName);
+        CompatibilityBuildHelper buildHelper =
+                new CompatibilityBuildHelper(testInfo.getBuildInfo());
+        final String result =
+                testInfo.getDevice()
+                        .installPackage(
+                                buildHelper.getTestFile(apkName),
+                                /* reinstall= */ true,
+                                /* grantPermissions= */ true,
+                                /*allow test apps*/ "-t");
+        assertWithMessage("Failed to install " + apkName + ": " + result).that(result).isNull();
+    }
+}