CTS tests to verify multi-user emulated storage.

Verifies that each user has its own isolated emulated storage, minus
shared storage for OBB files.  Also tests to verify that legacy
filesystem paths like "/sdcard" continue working.

Adds early support for multi-user CTS tests, should eventually be
moved into ITestDevice and RemoteAndroidTestRunner.

Bug: 7048947
Change-Id: I0573b9236b267ab798676926910ec4e1890fe7cb
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk
index c93fafb..8c2b798 100644
--- a/CtsTestCaseList.mk
+++ b/CtsTestCaseList.mk
@@ -25,7 +25,8 @@
 	CtsSimpleAppInstallDiffCert \
 	CtsTargetInstrumentationApp \
 	CtsUsePermissionDiffCert \
-	CtsWriteExternalStorageApp
+	CtsWriteExternalStorageApp \
+	CtsMultiUserStorageApp
 
 cts_support_packages := \
 	CtsAccelerationTestStubs \
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
index 5c28a4f..7e65be3 100644
--- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
@@ -19,15 +19,17 @@
 import com.android.cts.tradefed.build.CtsBuildHelper;
 import com.android.ddmlib.IDevice;
 import com.android.ddmlib.Log;
+import com.android.ddmlib.testrunner.InstrumentationResultParser;
 import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
 import com.android.ddmlib.testrunner.TestIdentifier;
 import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.CollectingOutputReceiver;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.result.CollectingTestListener;
 import com.android.tradefed.result.TestResult;
-import com.android.tradefed.result.TestRunResult;
 import com.android.tradefed.result.TestResult.TestStatus;
+import com.android.tradefed.result.TestRunResult;
 import com.android.tradefed.testtype.DeviceTestCase;
 import com.android.tradefed.testtype.IBuildReceiver;
 
@@ -94,6 +96,11 @@
 
     private static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";
 
+    private static final String MULTIUSER_STORAGE_APK = "CtsMultiUserStorageApp.apk";
+    private static final String MULTIUSER_STORAGE_PKG = "com.android.cts.multiuserstorageapp";
+    private static final String MULTIUSER_STORAGE_CLASS = MULTIUSER_STORAGE_PKG
+            + ".MultiUserStorageTest";
+
     private static final String LOG_TAG = "AppSecurityTests";
 
     private CtsBuildHelper mCtsBuild;
@@ -242,6 +249,25 @@
     }
 
     /**
+     * Verify that legacy filesystem paths continue working, and that they all
+     * point to same location.
+     */
+    public void testExternalStorageLegacyPaths() throws Exception {
+        try {
+            getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG);
+            assertNull(getDevice()
+                    .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false));
+
+            assertTrue("Failed to verify legacy filesystem paths", runDeviceTests(
+                    WRITE_EXTERNAL_STORAGE_APP_PKG, WRITE_EXTERNAL_STORAGE_APP_CLASS,
+                    "testLegacyPaths"));
+
+        } finally {
+            getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG);
+        }
+    }
+
+    /**
      * Test that uninstall of an app removes its private data.
      */
     public void testUninstallRemovesData() throws Exception {
@@ -346,6 +372,73 @@
     }
 
     /**
+     * Test multi-user emulated storage environment, ensuring that each user has
+     * isolated storage minus shared OBB directory.
+     */
+    public void testMultiUserStorage() throws Exception {
+        final String PACKAGE = MULTIUSER_STORAGE_PKG;
+        final String CLAZZ = MULTIUSER_STORAGE_CLASS;
+
+        if (!isMultiUserSupportedOnDevice(getDevice())) {
+            Log.d(LOG_TAG, "Single user device; skipping isolated storage tests");
+            return;
+        }
+
+        int owner = 0;
+        int secondary = -1;
+        try {
+            // Create secondary user
+            secondary = createUserOnDevice(getDevice());
+
+            // Install our test app
+            getDevice().uninstallPackage(MULTIUSER_STORAGE_PKG);
+            final String installResult = getDevice()
+                    .installPackage(getTestAppFile(MULTIUSER_STORAGE_APK), false);
+            assertNull("Failed to install: " + installResult, installResult);
+
+            // Clear data from previous tests
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "cleanIsolatedStorage", owner));
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "cleanIsolatedStorage", secondary));
+
+            // Have both users try writing into isolated storage
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "writeIsolatedStorage", owner));
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "writeIsolatedStorage", secondary));
+
+            // Verify they both have isolated view of storage
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "readIsolatedStorage", owner));
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "readIsolatedStorage", secondary));
+
+            // Clear data from previous tests
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "cleanObbStorage", owner));
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "cleanObbStorage", secondary));
+
+            // Only write data as owner
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "writeObbStorage", owner));
+
+            // Verify that both users can see shared OBB data
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "readObbStorage", owner));
+            assertDeviceTestsPass(
+                    doRunTestsAsUser(PACKAGE, CLAZZ, "readObbStorage", secondary));
+
+        } finally {
+            getDevice().uninstallPackage(MULTIUSER_STORAGE_PKG);
+            if (secondary != -1) {
+                removeUserOnDevice(getDevice(), secondary);
+            }
+        }
+    }
+
+    /**
      * Helper method that checks that all tests in given result passed, and attempts to generate
      * a meaningful error message if they failed.
      *
@@ -415,6 +508,58 @@
         return listener.getCurrentRunResults();
     }
 
+    private static boolean isMultiUserSupportedOnDevice(ITestDevice device)
+            throws DeviceNotAvailableException {
+        // TODO: move this to ITestDevice once it supports users
+        final String output = device.executeShellCommand("pm get-max-users");
+        try {
+            return Integer.parseInt(output.substring(output.lastIndexOf(" ")).trim()) > 1;
+        } catch (NumberFormatException e) {
+            fail("Failed to parse result: " + output);
+        }
+        return false;
+    }
+
+    private static int createUserOnDevice(ITestDevice device) throws DeviceNotAvailableException {
+        // TODO: move this to ITestDevice once it supports users
+        final String name = "CTS_" + System.currentTimeMillis();
+        final String output = device.executeShellCommand("pm create-user " + name);
+        if (output.startsWith("Success")) {
+            try {
+                return Integer.parseInt(output.substring(output.lastIndexOf(" ")).trim());
+            } catch (NumberFormatException e) {
+                fail("Failed to parse result: " + output);
+            }
+        } else {
+            fail("Failed to create user: " + output);
+        }
+        throw new IllegalStateException();
+    }
+
+    private static void removeUserOnDevice(ITestDevice device, int userId)
+            throws DeviceNotAvailableException {
+        // TODO: move this to ITestDevice once it supports users
+        final String output = device.executeShellCommand("pm remove-user " + userId);
+        if (output.startsWith("Error")) {
+            fail("Failed to remove user: " + output);
+        }
+    }
+
+    private TestRunResult doRunTestsAsUser(
+            String pkgName, String testClassName, String testMethodName, int userId)
+            throws DeviceNotAvailableException {
+        // TODO: move this to RemoteAndroidTestRunner once it supports users
+        final String cmd = "am instrument --user " + userId + " -w -r -e class " + testClassName
+                + "#" + testMethodName + " " + pkgName + "/android.test.InstrumentationTestRunner";
+        Log.i(LOG_TAG, "Running " + cmd + " on " + getDevice().getSerialNumber());
+
+        CollectingTestListener listener = new CollectingTestListener();
+        InstrumentationResultParser parser = new InstrumentationResultParser(pkgName, listener);
+
+        getDevice().executeShellCommand(cmd, parser);
+        return listener.getCurrentRunResults();
+    }
+
     private static void setPermissionEnforced(
             ITestDevice device, String permission, boolean enforced)
             throws DeviceNotAvailableException {
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
new file mode 100644
index 0000000..8781e8b
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
@@ -0,0 +1,27 @@
+# Copyright (C) 2012 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := 16
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_PACKAGE_NAME := CtsMultiUserStorageApp
+
+LOCAL_DEX_PREOPT := false
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/AndroidManifest.xml
new file mode 100644
index 0000000..6ace31b
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/AndroidManifest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2012 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.cts.multiuserstorageapp">
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="android.test.InstrumentationTestRunner"
+        android:targetPackage="com.android.cts.multiuserstorageapp" />
+
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
new file mode 100644
index 0000000..7e2d3ed
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2012 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.cts.multiuserstorageapp;
+
+import android.os.Environment;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+/**
+ * Test multi-user emulated storage environment, ensuring that each user has
+ * isolated storage minus shared OBB directory.
+ */
+public class MultiUserStorageTest extends AndroidTestCase {
+    private static final String TAG = "MultiUserStorageTest";
+
+    private static final String FILE_PREFIX = "MUST_";
+
+    private static final int MAGIC_VALUE = 16785407;
+
+    private final File mTargetSame = new File(
+            Environment.getExternalStorageDirectory(), FILE_PREFIX + "same");
+    private final File mTargetUid = new File(
+            Environment.getExternalStorageDirectory(), FILE_PREFIX + android.os.Process.myUid());
+
+    private File getFileObbSame() {
+        return new File(getContext().getObbDir(), FILE_PREFIX + "obb_same");
+    }
+
+    private void wipeTestFiles(File dir) {
+        dir.mkdirs();
+        for (File file : dir.listFiles()) {
+            if (file.getName().startsWith(FILE_PREFIX)) {
+                Log.d(TAG, "Wiping " + file);
+                file.delete();
+            }
+        }
+    }
+
+    public void cleanIsolatedStorage() throws Exception {
+        wipeTestFiles(Environment.getExternalStorageDirectory());
+    }
+
+    public void writeIsolatedStorage() throws Exception {
+        writeInt(mTargetSame, android.os.Process.myUid());
+        writeInt(mTargetUid, android.os.Process.myUid());
+    }
+
+    public void readIsolatedStorage() throws Exception {
+        // Expect that the value we wrote earlier is still valid and wasn't
+        // overwritten by us running as another user.
+        assertEquals(android.os.Process.myUid(), readInt(mTargetSame));
+        assertEquals(android.os.Process.myUid(), readInt(mTargetUid));
+    }
+
+    public void cleanObbStorage() throws Exception {
+        wipeTestFiles(getContext().getObbDir());
+    }
+
+    public void writeObbStorage() throws Exception {
+        writeInt(getFileObbSame(), MAGIC_VALUE);
+    }
+
+    public void readObbStorage() throws Exception {
+        assertEquals(MAGIC_VALUE, readInt(getFileObbSame()));
+    }
+
+    private static void writeInt(File file, int value) throws IOException {
+        final DataOutputStream os = new DataOutputStream(new FileOutputStream(file));
+        try {
+            os.writeInt(value);
+        } finally {
+            os.close();
+        }
+    }
+
+    private static int readInt(File file) throws IOException {
+        final DataInputStream is = new DataInputStream(new FileInputStream(file));
+        try {
+            return is.readInt();
+        } finally {
+            is.close();
+        }
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java
index b899bb0..075fe2e 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java
@@ -19,48 +19,49 @@
 import android.os.Environment;
 import android.test.AndroidTestCase;
 
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
+import java.util.Random;
 
 /**
  * Test if {@link Environment#getExternalStorageDirectory()} is writable.
  */
 public class WriteExternalStorageTest extends AndroidTestCase {
 
-    private static final String TEST_FILE = "meow";
+    private static final File TEST_FILE = new File(
+            Environment.getExternalStorageDirectory(), "meow");
 
-    private void assertExternalStorageMounted() {
-        assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState());
-    }
+    /**
+     * Set of file paths that should all refer to the same location to verify
+     * support for legacy paths.
+     */
+    private static final File[] IDENTICAL_FILES = {
+            new File("/sdcard/caek"),
+            new File("/mnt/sdcard/caek"),
+            new File("/storage/sdcard0/caek"),
+            new File(Environment.getExternalStorageDirectory(), "caek"),
+    };
 
-    private void readExternalStorage() throws IOException {
-        final File file = new File(Environment.getExternalStorageDirectory(), TEST_FILE);
-        final InputStream is = new FileInputStream(file);
+    @Override
+    protected void tearDown() throws Exception {
         try {
-            is.read();
+            TEST_FILE.delete();
+            for (File file : IDENTICAL_FILES) {
+                file.delete();
+            }
         } finally {
-            is.close();
-        }
-    }
-
-    private void writeExternalStorage() throws IOException {
-        final File file = new File(Environment.getExternalStorageDirectory(), TEST_FILE);
-        final OutputStream os = new FileOutputStream(file);
-        try {
-            os.write(32);
-        } finally {
-            os.close();
+            super.tearDown();
         }
     }
 
     public void testReadExternalStorage() throws Exception {
         assertExternalStorageMounted();
         try {
-            readExternalStorage();
+            writeInt(TEST_FILE, 32);
         } catch (IOException e) {
             fail("unable to read external file");
         }
@@ -69,10 +70,54 @@
     public void testWriteExternalStorage() throws Exception {
         assertExternalStorageMounted();
         try {
-            writeExternalStorage();
+            assertEquals(readInt(TEST_FILE), 32);
         } catch (IOException e) {
             fail("unable to read external file");
         }
     }
 
+    /**
+     * Verify that legacy filesystem paths continue working, and that they all
+     * point to same location.
+     */
+    public void testLegacyPaths() throws Exception {
+        final Random r = new Random();
+        for (File target : IDENTICAL_FILES) {
+            // Ensure we're starting with clean slate
+            for (File file : IDENTICAL_FILES) {
+                file.delete();
+            }
+
+            // Write value to our current target
+            final int value = r.nextInt();
+            writeInt(target, value);
+
+            // Ensure that identical files all contain the value
+            for (File file : IDENTICAL_FILES) {
+                assertEquals(readInt(file), value);
+            }
+        }
+    }
+
+    private static void assertExternalStorageMounted() {
+        assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState());
+    }
+
+    private static void writeInt(File file, int value) throws IOException {
+        final DataOutputStream os = new DataOutputStream(new FileOutputStream(file));
+        try {
+            os.writeInt(value);
+        } finally {
+            os.close();
+        }
+    }
+
+    private static int readInt(File file) throws IOException {
+        final DataInputStream is = new DataInputStream(new FileInputStream(file));
+        try {
+            return is.readInt();
+        } finally {
+            is.close();
+        }
+    }
 }
diff --git a/tests/tests/provider/src/android/provider/cts/SettingsTest.java b/tests/tests/provider/src/android/provider/cts/SettingsTest.java
index 601efce..3ea47d4 100644
--- a/tests/tests/provider/src/android/provider/cts/SettingsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/SettingsTest.java
@@ -180,8 +180,8 @@
         // Test that the secure table can be read from.
         Cursor cursor = null;
         try {
-            cursor = provider.query(Settings.Secure.CONTENT_URI, SECURE_PROJECTION,
-                    Settings.Secure.NAME + "=\"" + Settings.Secure.ADB_ENABLED + "\"",
+            cursor = provider.query(Settings.Global.CONTENT_URI, SECURE_PROJECTION,
+                    Settings.Global.NAME + "=\"" + Settings.Global.ADB_ENABLED + "\"",
                     null, null, null);
             assertNotNull(cursor);
         } finally {