Merge "Migrate Test Targets to New Android Ownership Model" into main
diff --git a/FsCrypt.cpp b/FsCrypt.cpp
index 7fe8be4..3eb4599 100644
--- a/FsCrypt.cpp
+++ b/FsCrypt.cpp
@@ -44,8 +44,6 @@
 
 #include "android/os/IVold.h"
 
-#define MANAGE_MISC_DIRS 0
-
 #include <cutils/fs.h>
 #include <cutils/properties.h>
 
@@ -677,26 +675,13 @@
     return success;
 }
 
-static bool parse_hex(const std::string& hex, std::string* result) {
-    if (hex == "!") {
-        *result = "";
-        return true;
-    }
-    if (android::vold::HexToStr(hex, *result) != 0) {
-        LOG(ERROR) << "Invalid FBE hex string";  // Don't log the string for security reasons
-        return false;
-    }
-    return true;
-}
-
-static std::optional<android::vold::KeyAuthentication> authentication_from_hex(
-        const std::string& secret_hex) {
-    std::string secret;
-    if (!parse_hex(secret_hex, &secret)) return std::optional<android::vold::KeyAuthentication>();
-    if (secret.empty()) {
+static android::vold::KeyAuthentication authentication_from_secret(
+        const std::vector<uint8_t>& secret) {
+    std::string secret_str(secret.begin(), secret.end());
+    if (secret_str.empty()) {
         return kEmptyAuthentication;
     } else {
-        return android::vold::KeyAuthentication(secret);
+        return android::vold::KeyAuthentication(secret_str);
     }
 }
 
@@ -745,12 +730,11 @@
 // re-encrypting the CE key upon upgrade from an Android version where the CE
 // key was stored with kEmptyAuthentication when the user didn't have an LSKF.
 // See the comments below for the different cases handled.
-bool fscrypt_set_ce_key_protection(userid_t user_id, const std::string& secret_hex) {
+bool fscrypt_set_ce_key_protection(userid_t user_id, const std::vector<uint8_t>& secret) {
     LOG(DEBUG) << "fscrypt_set_ce_key_protection " << user_id;
     if (!IsFbeEnabled()) return true;
-    auto auth = authentication_from_hex(secret_hex);
-    if (!auth) return false;
-    if (auth->secret.empty()) {
+    auto auth = authentication_from_secret(secret);
+    if (auth.secret.empty()) {
         LOG(ERROR) << "fscrypt_set_ce_key_protection: secret must be nonempty";
         return false;
     }
@@ -778,7 +762,7 @@
             // with the given secret.  This isn't expected, but in theory it
             // could happen if an upgrade is requested for a user more than once
             // due to a power-off or other interruption.
-            if (read_and_fixate_user_ce_key(user_id, *auth, &ce_key)) {
+            if (read_and_fixate_user_ce_key(user_id, auth, &ce_key)) {
                 LOG(WARNING) << "CE key is already protected by given secret";
                 return true;
             }
@@ -804,7 +788,7 @@
     auto const paths = get_ce_key_paths(directory_path);
     std::string ce_key_path;
     if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
-    if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, *auth, ce_key)) return false;
+    if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
 
     // Fixate the key, i.e. delete all other bindings of it.  (In practice this
     // just means the kEmptyAuthentication binding, if there is one.)  However,
@@ -847,17 +831,16 @@
 // Unlocks internal CE storage for the given user.  This only unlocks internal storage, since
 // fscrypt_prepare_user_storage() has to be called for each adoptable storage volume anyway (since
 // the volume might have been absent when the user was created), and that handles the unlocking.
-bool fscrypt_unlock_ce_storage(userid_t user_id, const std::string& secret_hex) {
+bool fscrypt_unlock_ce_storage(userid_t user_id, const std::vector<uint8_t>& secret) {
     LOG(DEBUG) << "fscrypt_unlock_ce_storage " << user_id;
     if (!IsFbeEnabled()) return true;
     if (s_ce_policies.count(user_id) != 0) {
         LOG(WARNING) << "CE storage for user " << user_id << " is already unlocked";
         return true;
     }
-    auto auth = authentication_from_hex(secret_hex);
-    if (!auth) return false;
+    auto auth = authentication_from_secret(secret);
     KeyBuffer ce_key;
-    if (!read_and_fixate_user_ce_key(user_id, *auth, &ce_key)) return false;
+    if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
     EncryptionPolicy ce_policy;
     if (!install_storage_key(DATA_MNT_POINT, s_data_options, ce_key, &ce_policy)) return false;
     s_ce_policies[user_id].internal = ce_policy;
@@ -907,7 +890,6 @@
     if (flags & android::os::IVold::STORAGE_FLAG_DE) {
         // DE_sys key
         auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
-        auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
         auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
 
         // DE_n key
@@ -937,11 +919,6 @@
 
         if (volume_uuid.empty()) {
             if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
-#if MANAGE_MISC_DIRS
-            if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
-                             multiuser_get_uid(user_id, AID_EVERYBODY)))
-                return false;
-#endif
             if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
 
             if (!prepare_dir_with_policy(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM, de_policy))
@@ -1050,7 +1027,6 @@
     if (flags & android::os::IVold::STORAGE_FLAG_DE) {
         // DE_sys key
         auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
-        auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
         auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
 
         // DE_n key
@@ -1063,9 +1039,6 @@
         res &= destroy_dir(misc_de_path);
         if (volume_uuid.empty()) {
             res &= destroy_dir(system_legacy_path);
-#if MANAGE_MISC_DIRS
-            res &= destroy_dir(misc_legacy_path);
-#endif
             res &= destroy_dir(profiles_de_path);
             res &= destroy_dir(system_de_path);
             res &= destroy_dir(vendor_de_path);
diff --git a/FsCrypt.h b/FsCrypt.h
index afcedfb..be21fba 100644
--- a/FsCrypt.h
+++ b/FsCrypt.h
@@ -25,11 +25,11 @@
 extern bool fscrypt_init_user0_done;
 bool fscrypt_create_user_keys(userid_t user_id, bool ephemeral);
 bool fscrypt_destroy_user_keys(userid_t user_id);
-bool fscrypt_set_ce_key_protection(userid_t user_id, const std::string& secret);
+bool fscrypt_set_ce_key_protection(userid_t user_id, const std::vector<uint8_t>& secret);
 void fscrypt_deferred_fixate_ce_keys();
 
 std::vector<int> fscrypt_get_unlocked_users();
-bool fscrypt_unlock_ce_storage(userid_t user_id, const std::string& secret);
+bool fscrypt_unlock_ce_storage(userid_t user_id, const std::vector<uint8_t>& secret);
 bool fscrypt_lock_ce_storage(userid_t user_id);
 
 bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int flags);
diff --git a/TEST_MAPPING b/TEST_MAPPING
index a535181..93938b6 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -10,6 +10,15 @@
       "name": "CtsScopedStorageDeviceOnlyTest"
     },
     {
+      "name": "CtsScopedStorageBypassDatabaseOperationsTest"
+    },
+    {
+      "name": "CtsScopedStorageGeneralTest"
+    },
+    {
+      "name": "CtsScopedStorageRedactUriTest"
+    },
+    {
       "name": "AdoptableHostTest"
     }
   ],
@@ -24,6 +33,15 @@
       "name": "CtsScopedStorageDeviceOnlyTest"
     },
     {
+      "name": "CtsScopedStorageBypassDatabaseOperationsTest"
+    },
+    {
+      "name": "CtsScopedStorageGeneralTest"
+    },
+    {
+      "name": "CtsScopedStorageRedactUriTest"
+    },
+    {
       "name": "AdoptableHostTest"
     }
   ]
diff --git a/Utils.cpp b/Utils.cpp
index 40a182b..696b0b4 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -1116,10 +1116,6 @@
     return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
 }
 
-std::string BuildDataMiscLegacyPath(userid_t userId) {
-    return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
-}
-
 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
 std::string BuildDataProfilesDePath(userid_t userId) {
     return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
diff --git a/Utils.h b/Utils.h
index fbd0f30..690f79e 100644
--- a/Utils.h
+++ b/Utils.h
@@ -148,7 +148,6 @@
 std::string BuildDataSystemLegacyPath(userid_t userid);
 std::string BuildDataSystemCePath(userid_t userid);
 std::string BuildDataSystemDePath(userid_t userid);
-std::string BuildDataMiscLegacyPath(userid_t userid);
 std::string BuildDataProfilesDePath(userid_t userid);
 std::string BuildDataVendorCePath(userid_t userid);
 std::string BuildDataVendorDePath(userid_t userid);
diff --git a/VoldNativeService.cpp b/VoldNativeService.cpp
index 96f4eaf..b36856a 100644
--- a/VoldNativeService.cpp
+++ b/VoldNativeService.cpp
@@ -630,7 +630,7 @@
 }
 
 binder::Status VoldNativeService::setCeStorageProtection(int32_t userId,
-                                                         const std::string& secret) {
+                                                         const std::vector<uint8_t>& secret) {
     ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
@@ -645,7 +645,8 @@
     return Ok();
 }
 
-binder::Status VoldNativeService::unlockCeStorage(int32_t userId, const std::string& secret) {
+binder::Status VoldNativeService::unlockCeStorage(int32_t userId,
+                                                  const std::vector<uint8_t>& secret) {
     ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
diff --git a/VoldNativeService.h b/VoldNativeService.h
index bb00d35..a4fbf00 100644
--- a/VoldNativeService.h
+++ b/VoldNativeService.h
@@ -116,10 +116,10 @@
     binder::Status createUserStorageKeys(int32_t userId, bool ephemeral);
     binder::Status destroyUserStorageKeys(int32_t userId);
 
-    binder::Status setCeStorageProtection(int32_t userId, const std::string& secret);
+    binder::Status setCeStorageProtection(int32_t userId, const std::vector<uint8_t>& secret);
 
     binder::Status getUnlockedUsers(std::vector<int>* _aidl_return);
-    binder::Status unlockCeStorage(int32_t userId, const std::string& secret);
+    binder::Status unlockCeStorage(int32_t userId, const std::vector<uint8_t>& secret);
     binder::Status lockCeStorage(int32_t userId);
 
     binder::Status prepareUserStorage(const std::optional<std::string>& uuid, int32_t userId,
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index c981f2d..a1ac20d 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -921,25 +921,34 @@
 int VolumeManager::reset() {
     // Tear down all existing disks/volumes and start from a blank slate so
     // newly connected framework hears all events.
+
+    // Destroy StubVolume disks. This needs to be done before destroying
+    // EmulatedVolumes because in ARC (Android on ChromeOS), ChromeOS Downloads
+    // directory (which is in a StubVolume) is bind-mounted to
+    // /data/media/0/Download.
+    // We do not recreate StubVolumes here because they are managed from outside
+    // Android (e.g. from ChromeOS) and their disk recreation on reset events
+    // should be handled from outside by calling createStubVolume() again.
+    for (const auto& disk : mDisks) {
+        if (disk->isStub()) {
+            disk->destroy();
+        }
+    }
+    // Remove StubVolume from both mDisks and mPendingDisks.
+    const auto isStub = [](const auto& disk) { return disk->isStub(); };
+    mDisks.remove_if(isStub);
+    mPendingDisks.remove_if(isStub);
+
     for (const auto& vol : mInternalEmulatedVolumes) {
         vol->destroy();
     }
     mInternalEmulatedVolumes.clear();
 
-    // Destroy and recreate all disks except that StubVolume disks are just
-    // destroyed and removed from both mDisks and mPendingDisks.
-    // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
-    // their disk recreation on reset events should be handled from outside by
-    // calling createStubVolume() again.
+    // Destroy and recreate non-StubVolume disks.
     for (const auto& disk : mDisks) {
         disk->destroy();
-        if (!disk->isStub()) {
-            disk->create();
-        }
+        disk->create();
     }
-    const auto isStub = [](const auto& disk) { return disk->isStub(); };
-    mDisks.remove_if(isStub);
-    mPendingDisks.remove_if(isStub);
 
     updateVirtualDisk();
     mAddedUsers.clear();
@@ -958,11 +967,20 @@
         return 0;  // already shutdown
     }
     android::vold::sSleepOnUnmount = false;
+    // Destroy StubVolume disks before destroying EmulatedVolumes (see the
+    // comment in VolumeManager::reset()).
+    for (const auto& disk : mDisks) {
+        if (disk->isStub()) {
+            disk->destroy();
+        }
+    }
     for (const auto& vol : mInternalEmulatedVolumes) {
         vol->destroy();
     }
     for (const auto& disk : mDisks) {
-        disk->destroy();
+        if (!disk->isStub()) {
+            disk->destroy();
+        }
     }
 
     mInternalEmulatedVolumes.clear();
@@ -978,11 +996,20 @@
     ATRACE_NAME("VolumeManager::unmountAll()");
 
     // First, try gracefully unmounting all known devices
+    // Unmount StubVolume disks before unmounting EmulatedVolumes (see the
+    // comment in VolumeManager::reset()).
+    for (const auto& disk : mDisks) {
+        if (disk->isStub()) {
+            disk->unmountAll();
+        }
+    }
     for (const auto& vol : mInternalEmulatedVolumes) {
         vol->unmount();
     }
     for (const auto& disk : mDisks) {
-        disk->unmountAll();
+        if (!disk->isStub()) {
+            disk->unmountAll();
+        }
     }
 
     // Worst case we might have some stale mounts lurking around, so
diff --git a/binder/android/os/IVold.aidl b/binder/android/os/IVold.aidl
index d121dee..d37697b 100644
--- a/binder/android/os/IVold.aidl
+++ b/binder/android/os/IVold.aidl
@@ -22,6 +22,7 @@
 import android.os.IVoldTaskListener;
 
 /** {@hide} */
+@SensitiveData
 interface IVold {
     void setListener(IVoldListener listener);
 
@@ -90,10 +91,10 @@
     void createUserStorageKeys(int userId, boolean ephemeral);
     void destroyUserStorageKeys(int userId);
 
-    void setCeStorageProtection(int userId, @utf8InCpp String secret);
+    void setCeStorageProtection(int userId, in byte[] secret);
 
     int[] getUnlockedUsers();
-    void unlockCeStorage(int userId, @utf8InCpp String secret);
+    void unlockCeStorage(int userId, in byte[] secret);
     void lockCeStorage(int userId);
 
     void prepareUserStorage(@nullable @utf8InCpp String uuid, int userId, int storageFlags);
diff --git a/model/Disk.cpp b/model/Disk.cpp
index 4df4e9d..01cd0c3 100644
--- a/model/Disk.cpp
+++ b/model/Disk.cpp
@@ -365,7 +365,6 @@
                 continue;
             }
         } else if (*it == "PART") {
-            foundParts = true;
 
             if (++it == split.end()) continue;
             int i = 0;
@@ -390,6 +389,7 @@
                     case 0x0c:  // W95 FAT32 (LBA)
                     case 0x0e:  // W95 FAT16 (LBA)
                         createPublicVolume(partDevice);
+                        foundParts = true;
                         break;
                 }
             } else if (table == Table::kGpt) {
@@ -400,8 +400,10 @@
 
                 if (android::base::EqualsIgnoreCase(typeGuid, kGptBasicData)) {
                     createPublicVolume(partDevice);
+                    foundParts = true;
                 } else if (android::base::EqualsIgnoreCase(typeGuid, kGptAndroidExpand)) {
                     createPrivateVolume(partDevice, partGuid);
+                    foundParts = true;
                 }
             }
         }