Add on-device signing end-to-end test.

This adds a host-driven test that verifies that installing an ART apex
with a newer version generates artifacts and ensures they are signed
with fs-verity. To that end, add a new ART test APEX which is identical
to the regular ART APEX, except it carries a different version number.

Bug: 165630556
Bug: 167516462
Test: atest odsign_e2e_tests
Change-Id: If12f3922bbaafd875cb3120d01540e0b73d012be
diff --git a/build/apex/Android.bp b/build/apex/Android.bp
index 5897585..4e9dca8 100644
--- a/build/apex/Android.bp
+++ b/build/apex/Android.bp
@@ -306,6 +306,15 @@
     },
 }
 
+apex_test {
+    name: "test_com.android.art",
+    defaults: ["com.android.art-devel-defaults"],
+    manifest: "test_apex_manifest.json",
+    file_contexts: ":com.android.art.debug-file_contexts",
+    certificate: ":com.android.art.certificate",
+    installable: false,
+}
+
 // Release version of the ART APEX module (not containing debug
 // variants nor tools), included in user builds. Also used for
 // storage-constrained devices in userdebug and eng builds.
diff --git a/build/apex/test_apex_manifest.json b/build/apex/test_apex_manifest.json
new file mode 100644
index 0000000..b432c90
--- /dev/null
+++ b/build/apex/test_apex_manifest.json
@@ -0,0 +1,4 @@
+{
+  "name": "com.android.art",
+  "version": 2147483647
+}
diff --git a/test/odsign/Android.bp b/test/odsign/Android.bp
new file mode 100644
index 0000000..0df6687
--- /dev/null
+++ b/test/odsign/Android.bp
@@ -0,0 +1,70 @@
+// 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 {
+    default_applicable_licenses: ["art_license"],
+}
+
+java_test_host {
+    name: "odsign_e2e_tests",
+    srcs: ["test-src/**/*.java"],
+    libs: ["tradefed"],
+    static_libs: [
+        "cts-install-lib-host",
+        "frameworks-base-hostutils",
+    ],
+    data: [
+        ":test_com.android.art",
+        ":odsign_e2e_test_app",
+    ],
+    test_config: "odsign-e2e-tests.xml",
+    test_suites: ["device-tests"],
+}
+
+cc_library_shared {
+    name: "libOdsignTestAppJni",
+    srcs: ["jni/**/*.cc"],
+    shared_libs: [
+        "libnativehelper_compat_libc++",
+        "liblog",
+    ],
+    static_libs: [
+        "libbase_ndk",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+    stl: "c++_static",
+    sdk_version: "current",
+}
+
+android_test_helper_app {
+    name: "odsign_e2e_test_app",
+    manifest: "AndroidManifest.xml",
+    srcs: ["src/**/*.java"],
+    jni_libs: [
+        "libOdsignTestAppJni",
+    ],
+    compile_multilib: "both",
+    libs: [
+        "junit",
+    ],
+    static_libs: [
+        "androidx.test.runner",
+        "ctstestrunner-axt",
+    ],
+    sdk_version: "system_current",
+    min_sdk_version: "30",
+}
diff --git a/test/odsign/AndroidManifest.xml b/test/odsign/AndroidManifest.xml
new file mode 100644
index 0000000..b9936fc
--- /dev/null
+++ b/test/odsign/AndroidManifest.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.tests.odsign">
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="com.android.tests.odsign"
+                     android:label="test app for on-device signing">
+        <meta-data android:name="listener"
+                   android:value="com.android.cts.runner.CtsTestRunListener" />
+    </instrumentation>/>
+</manifest>
diff --git a/test/odsign/jni/android_tests_odsign_ArtifactsSignedTest.cc b/test/odsign/jni/android_tests_odsign_ArtifactsSignedTest.cc
new file mode 100644
index 0000000..a22b967
--- /dev/null
+++ b/test/odsign/jni/android_tests_odsign_ArtifactsSignedTest.cc
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "ArtifactsSignedTest"
+
+#include "jni.h"
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedUtfChars.h>
+
+#include <android/log.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
+
+extern "C" JNIEXPORT jboolean JNICALL
+Java_com_android_tests_odsign_ArtifactsSignedTest_hasFsverityNative(
+    JNIEnv *env, jobject /*thiz*/, jstring filePath) {
+  ScopedUtfChars path(env, filePath);
+
+  struct statx out = {};
+  if (statx(AT_FDCWD, path.c_str(), /*flags=*/ 0, STATX_ALL, &out) != 0) {
+    ALOGE("statx failed at %s", path.c_str());
+    return JNI_FALSE;
+  }
+
+  // Make sure we actually support ATTR_VERITY
+  if ((out.stx_attributes_mask & STATX_ATTR_VERITY) == 0) {
+    ALOGE("STATX_ATTR_VERITY not supported by kernel");
+    return JNI_FALSE;
+  }
+
+  return (out.stx_attributes & STATX_ATTR_VERITY) != 0 ? JNI_TRUE : JNI_FALSE;
+}
diff --git a/test/odsign/odsign-e2e-tests.xml b/test/odsign/odsign-e2e-tests.xml
new file mode 100644
index 0000000..2ed7b09
--- /dev/null
+++ b/test/odsign/odsign-e2e-tests.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<configuration description="Config for on-device signing ART e2e test cases">
+    <option name="test-suite-tag" value="odsign_e2e_tests" />
+    <option name="test-suite-tag" value="apct" />
+
+    <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer"/>
+    <test class="com.android.tradefed.testtype.HostTest" >
+        <option name="jar" value="odsign_e2e_tests.jar" />
+    </test>
+</configuration>
diff --git a/test/odsign/src/com/android/tests/odsign/ArtifactsSignedTest.java b/test/odsign/src/com/android/tests/odsign/ArtifactsSignedTest.java
new file mode 100644
index 0000000..46bd474
--- /dev/null
+++ b/test/odsign/src/com/android/tests/odsign/ArtifactsSignedTest.java
@@ -0,0 +1,66 @@
+/*
+ * 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.tests.odsign;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class ArtifactsSignedTest {
+    private static final String TAG = "VerifyArtArtifactsSignedTest";
+    private static final String ARTIFACTS_DIR = "/data/misc/apexdata/com.android.art/dalvik-cache";
+    private static final String FS_VERITY_PROC_PATH = "/proc/sys/fs/verity";
+
+    static {
+        System.loadLibrary("OdsignTestAppJni");
+    }
+
+    private static native boolean hasFsverityNative(@NonNull String path);
+
+    public boolean isFsVeritySupported() {
+        return new File(FS_VERITY_PROC_PATH).exists();
+    }
+
+    @Test
+    public void testArtArtifactsHaveFsverity() throws Exception {
+        assumeTrue("fs-verity is not supported on this device.", isFsVeritySupported());
+        List<File> files = Files.walk(Paths.get(ARTIFACTS_DIR), Integer.MAX_VALUE).
+            map(Path::toFile)
+            .collect(Collectors.toList());
+
+        for (File file : files) {
+            if (file.isFile()) {
+                assertTrue(file.getPath() + " is not in fs-verity",
+                        hasFsverityNative(file.getPath()));
+                Log.i(TAG, file.getPath() + " is in fs-verity");
+            }
+        }
+    }
+}
diff --git a/test/odsign/test-src/com/android/tests/odsign/OnDeviceSigningHostTest.java b/test/odsign/test-src/com/android/tests/odsign/OnDeviceSigningHostTest.java
new file mode 100644
index 0000000..4144e00
--- /dev/null
+++ b/test/odsign/test-src/com/android/tests/odsign/OnDeviceSigningHostTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.tests.odsign;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.junit.Assume.assumeTrue;
+
+import android.cts.install.lib.host.InstallUtilsHost;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.device.ITestDevice.ApexInfo;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import com.android.tradefed.testtype.junit4.DeviceTestRunOptions;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.time.Duration;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class OnDeviceSigningHostTest extends BaseHostJUnit4Test {
+
+    private static final String APEX_FILENAME = "test_com.android.art.apex";
+
+    private static final String TEST_APP_PACKAGE_NAME = "com.android.tests.odsign";
+    private static final String TEST_APP_APK = "odsign_e2e_test_app.apk";
+
+    private final InstallUtilsHost mInstallUtils = new InstallUtilsHost(this);
+
+    private static final Duration BOOT_COMPLETE_TIMEOUT = Duration.ofMinutes(2);
+
+    @Before
+    public void setUp() throws Exception {
+        assumeTrue("Updating APEX is not supported", mInstallUtils.isApexUpdateSupported());
+    }
+
+    @Before // Generally not needed, but local test devices are sometimes in a "bad" start state.
+    @After
+    public void cleanup() throws Exception {
+        ApexInfo apex = mInstallUtils.getApexInfo(mInstallUtils.getTestFile(APEX_FILENAME));
+        getDevice().uninstallPackage(apex.name);
+        reboot();
+    }
+
+    @Test
+    public void verifyArtUpgradeSignsFiles() throws Exception {
+        installPackage(TEST_APP_APK);
+        mInstallUtils.installApexes(APEX_FILENAME);
+        reboot();
+        DeviceTestRunOptions options = new DeviceTestRunOptions(TEST_APP_PACKAGE_NAME);
+        options.setTestClassName(TEST_APP_PACKAGE_NAME + ".ArtifactsSignedTest");
+        options.setTestMethodName("testArtArtifactsHaveFsverity");
+        runDeviceTests(options);
+    }
+
+    private void reboot() throws Exception {
+        getDevice().reboot();
+        boolean success = getDevice().waitForBootComplete(BOOT_COMPLETE_TIMEOUT.toMillis());
+        assertWithMessage("Device didn't boot in %s", BOOT_COMPLETE_TIMEOUT).that(success).isTrue();
+    }
+}