Set sticky bit on encryptedstore

Also move this & the previous change behind a cfg, to preserve
existing behavior until we're ready. Wire the cfg up to the
new flag.

Bug: 296395087
Test: Run VM, examine directory
Test: Override flag locally, atest MicrodroidTests
Change-Id: If4ddf3384ee7324768ba4adb6e426e31032e5b32
diff --git a/encryptedstore/Android.bp b/encryptedstore/Android.bp
index 8ba5016..aa46c35 100644
--- a/encryptedstore/Android.bp
+++ b/encryptedstore/Android.bp
@@ -4,6 +4,7 @@
 
 rust_defaults {
     name: "encryptedstore.defaults",
+    defaults: ["avf_build_flags_rust"],
     srcs: ["src/main.rs"],
     edition: "2021",
     prefer_rlib: true,
diff --git a/encryptedstore/src/main.rs b/encryptedstore/src/main.rs
index 2a698ea..db3d4f6 100644
--- a/encryptedstore/src/main.rs
+++ b/encryptedstore/src/main.rs
@@ -94,13 +94,21 @@
     }
     mount(&crypt_device, mountpoint)
         .with_context(|| format!("Unable to mount {:?}", crypt_device))?;
-    if needs_formatting {
-        std::fs::set_permissions(mountpoint, PermissionsExt::from_mode(0o770))
-            .context("Failed to chmod root directory")?;
+    if cfg!(payload_not_root) && needs_formatting {
+        set_root_dir_permissions(mountpoint)?;
     }
     Ok(())
 }
 
+fn set_root_dir_permissions(mountpoint: &Path) -> Result<()> {
+    // mke2fs hardwires the root dir permissions as 0o755 which doesn't match what we want.
+    // We want to allow full access by both root and the payload group, and no access by anything
+    // else. And we want the sticky bit set, so different payload UIDs can create sub-directories
+    // that other payloads can't delete.
+    let permissions = PermissionsExt::from_mode(0o770 | libc::S_ISVTX);
+    std::fs::set_permissions(mountpoint, permissions).context("Failed to chmod root directory")
+}
+
 fn enable_crypt(data_device: &Path, key: &str, name: &str) -> Result<PathBuf> {
     let dev_size = util::blkgetsize64(data_device)?;
     let key = hex::decode(key).context("Unable to decode hex key")?;