Add tests for preload and APEX measurement

A new host-side test "BinaryTransparencyHostTest" is added to drive the
actual test on device. The host can be used to set up the testing
environment (e.g. update a preload, or later install MBA), then ask the
helper app "BinaryTransparencyTestApp" to verify returned value of
private APIs in the main service.

Since the APIs are private (@hide, because we're not ready to make
anything public yet), the (bundled) helper app needs to be compiled with
`platform_apis: true`.

Plus, since the service is not accessible to apps by sepolicy, the test
has to run with SELinux disabled. An alternative is to add a
userdebug_or_eng rule in sepolicy, but it's better to avoid adding rule
for one specific test, and isolate the setup here (in AndroidTest.xml).

The test is not yet added to TEST_MAPPING/presubmit. Once it runs
successfully for a few runs in postsubmit, we should graduate it to
presubmit.

Test: atest BinaryTransparencyHostTest
Test: atest BinaryTransparencyServiceTest
Bug: 265244016
Change-Id: Ibd87f4cf6a2ae989ddfa8eaf9494cff5d34005ed
diff --git a/tests/BinaryTransparencyHostTest/test-app/Android.bp b/tests/BinaryTransparencyHostTest/test-app/Android.bp
new file mode 100644
index 0000000..b5193dd
--- /dev/null
+++ b/tests/BinaryTransparencyHostTest/test-app/Android.bp
@@ -0,0 +1,40 @@
+// 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 {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_base_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_base_license"],
+}
+
+android_test_helper_app {
+    name: "BinaryTransparencyTestApp",
+    manifest: "AndroidManifest.xml",
+    srcs: ["src/**/*.java"],
+    static_libs: [
+        "androidx.test.core",
+        "compatibility-device-util-axt",
+        "junit",
+    ],
+    test_suites: [
+        "general-tests",
+    ],
+    platform_apis: true,
+    dex_preopt: {
+        enabled: false,
+    },
+}
diff --git a/tests/BinaryTransparencyHostTest/test-app/AndroidManifest.xml b/tests/BinaryTransparencyHostTest/test-app/AndroidManifest.xml
new file mode 100644
index 0000000..42e616e
--- /dev/null
+++ b/tests/BinaryTransparencyHostTest/test-app/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.transparency.test.app">
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:label="APCT tests for binary transparency"
+        android:targetPackage="android.transparency.test.app" />
+</manifest>
diff --git a/tests/BinaryTransparencyHostTest/test-app/src/android/transparency/test/app/BinaryTransparencyTest.java b/tests/BinaryTransparencyHostTest/test-app/src/android/transparency/test/app/BinaryTransparencyTest.java
new file mode 100644
index 0000000..aedb366
--- /dev/null
+++ b/tests/BinaryTransparencyHostTest/test-app/src/android/transparency/test/app/BinaryTransparencyTest.java
@@ -0,0 +1,112 @@
+/*
+ * 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.transparency.test.app;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.transparency.BinaryTransparencyManager;
+import android.util.Log;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.os.IBinaryTransparencyService.AppInfo;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.HashSet;
+import java.util.HexFormat;
+import java.util.stream.Collectors;
+
+@RunWith(AndroidJUnit4.class)
+public class BinaryTransparencyTest {
+    private static final String TAG = "BinaryTransparencyTest";
+
+    private BinaryTransparencyManager mBt;
+
+    @Before
+    public void setUp() {
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        mBt = context.getSystemService(BinaryTransparencyManager.class);
+    }
+
+    @Test
+    public void testCollectAllApexInfo() {
+        // Prepare the expectation received from host's shell command
+        Bundle args = InstrumentationRegistry.getArguments();
+        assertThat(args).isNotNull();
+        int number = Integer.valueOf(args.getString("apex-number"));
+        assertThat(number).isGreaterThan(0);
+        var expectedApexNames = new HashSet<String>();
+        for (var i = 0; i < number; i++) {
+            String moduleName = args.getString("apex-" + Integer.toString(i));
+            expectedApexNames.add(moduleName);
+        }
+
+        // Action
+        var apexInfoList = mBt.collectAllApexInfo(/* includeTestOnly */ true);
+
+        // Verify actual apex names
+        var actualApexesNames = apexInfoList.stream().map((apex) -> apex.moduleName)
+                .collect(Collectors.toList());
+        assertThat(actualApexesNames).containsExactlyElementsIn(expectedApexNames);
+
+        // Perform more valitidy checks
+        var digestsSeen = new HashSet<String>();
+        var hexFormatter = HexFormat.of();
+        for (var apex : apexInfoList) {
+            Log.d(TAG, "Verifying " + apex.packageName + " / " + apex.moduleName);
+
+            assertThat(apex.longVersion).isGreaterThan(0);
+            assertThat(apex.digestAlgorithm).isGreaterThan(0);
+            assertThat(apex.signerDigests).asList().containsNoneOf(null, "");
+
+            assertThat(apex.digest).isNotNull();
+            String digestHex = hexFormatter.formatHex(apex.digest);
+            boolean isNew = digestsSeen.add(digestHex);
+            assertWithMessage(
+                    "Digest should be unique, but received a dup: " + digestHex)
+                    .that(isNew).isTrue();
+        }
+    }
+
+    @Test
+    public void testCollectAllUpdatedPreloadInfo() {
+        var preloadInfoList = mBt.collectAllUpdatedPreloadInfo(new Bundle());
+        assertThat(preloadInfoList).isNotEmpty();  // because we just installed from the host side
+        AppInfo updatedPreload = null;
+        for (var preload : preloadInfoList) {
+            Log.d(TAG, "Received " + preload.packageName);
+            if (preload.packageName.equals("com.android.egg")) {
+                assertWithMessage("Received the same package").that(updatedPreload).isNull();
+                updatedPreload = preload;
+            }
+        }
+
+        // Verify
+        assertThat(updatedPreload.longVersion).isGreaterThan(0);
+        assertThat(updatedPreload.digestAlgorithm).isGreaterThan(0);
+        assertThat(updatedPreload.digest).isNotEmpty();
+        assertThat(updatedPreload.mbaStatus).isEqualTo(/* MBA_STATUS_UPDATED_PRELOAD */ 2);
+        assertThat(updatedPreload.signerDigests).asList().containsNoneOf(null, "");
+    }
+}