Modern Apps git

← Modern-Apps.git

photos: handle revoked read grants when moving to the secure folder

Commit
bbc3927ce12587cf73a28b9f1b20fde1a3f6b8de
Author
Vayun Mathur <[email protected]>
When
2026-11-08 02:32 UTC (28 days ago)
Parents
ee29ecf
Moving a photo whose read grant was revoked after the gallery indexed
it (a cloud document whose permission expired) crashed the app: opening
the full stream throws the raw SecurityException, which neither
SecureFolderManager.encryptAndMove nor the per-photo loop in
SecureFolderViewModel.moveToSecure caught. The exception escaped
viewModelScope, killing the move, and the already-written encrypted
thumbnail partial was left orphaned in the vault directory.

Route SecurityException through encryptFailure in encryptAndMove so
partials are deleted before rethrow, and catch it per photo in
moveToSecure so the denied photo is skipped like any other per-photo
failure instead of crashing the whole batch.

Verified with two new regression tests using a mocked ContentResolver
whose thumbnail loads but whose openInputStream throws SecurityException
(the expired-grant shape on a device): the manager test asserts the
exception type and that no vault partials remain, and the ViewModel test
asserts the photo is skipped with no crash and no orphans. Both failed
before the fix (escaped SecurityException plus a leftover .enc thumb
partial) and pass after.

Diff

photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.kt b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.ktindex 5caa7d68ad..e7ed1186c7 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.kt@@ -216,6 +216,12 @@ class SecureFolderManager(val context: Context) {             encryptFailure(outputFile, thumbFile, e)         } catch (e: GeneralSecurityException) {             encryptFailure(outputFile, thumbFile, e)+        } catch (e: SecurityException) {+            // Revoked/expired read grant mid-move: openInputStream throws the+            // raw SecurityException (never wrapped). Clean up partials and+            // rethrow so the per-photo caller skips this photo, same as any+            // other per-photo failure.+            encryptFailure(outputFile, thumbFile, e)         }     } 
photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.ktindex 912c49d93b..a4cb1cde8a 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt@@ -295,6 +295,12 @@ class SecureFolderViewModel(application: Application) : AndroidViewModel(applica                         Log.error(TAG, "encryptAndMove failed for ${photo.uri}", e)                     } catch (e: GeneralSecurityException) {                         Log.error(TAG, "encryptAndMove failed for ${photo.uri}", e)+                    } catch (e: SecurityException) {+                        // Revoked/expired read grant: encryptAndMove rethrows+                        // the raw SecurityException after deleting partials.+                        // Skip the photo like any other per-photo failure —+                        // leaking it out of viewModelScope would crash the app.+                        Log.error(TAG, "encryptAndMove failed for ${photo.uri}", e)                     }                 }                 collected
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultManager2Test.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultManager2Test.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultManager2Test.ktindex 012a823fea..f1675b3660 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultManager2Test.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultManager2Test.kt@@ -1,5 +1,7 @@ package com.vayunmathur.photos.util +import android.content.ContentResolver+import android.content.ContextWrapper import android.graphics.Bitmap import android.net.Uri import androidx.test.core.app.ApplicationProvider@@ -11,11 +13,15 @@ import javax.crypto.Cipher import javax.crypto.spec.SecretKeySpec import kotlin.test.AfterTest import kotlin.test.Test+import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.runner.RunWith+import org.mockito.ArgumentMatchers.any+import org.mockito.Mockito.`when`+import org.mockito.Mockito.mock import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @@ -161,4 +167,33 @@ class PhotosSlice1VaultManager2Test {         manager.clearViewerCache(dir) // must not throw         assertTrue(!File(dir, "vault_view").exists())     }++    @Test+    fun encryptAndMoveWithDeniedStreamThrowsWithoutLeavingPartials() {+        // Simulate an expired read grant: the thumbnail still loads, but+        // opening the full stream throws SecurityException — the raw exception+        // a device delivers when a cloud document's grant is revoked after the+        // gallery indexed it. (Mockito's inline maker stubs the final+        // openInputStream; subclassing cannot — every stream API on+        // ContentResolver is final in the compile SDK.)+        val resolver = mock(ContentResolver::class.java)+        `when`(resolver.loadThumbnail(any(), any(), any()))+            .thenReturn(Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888))+        `when`(resolver.openInputStream(any()))+            .thenThrow(SecurityException("denied-open"))+        val denyingManager = SecureFolderManager(object : ContextWrapper(context) {+            override fun getContentResolver(): ContentResolver = resolver+        })+        val vaultDir = File(context.filesDir, "secure_vault")+        val before = vaultDir.listFiles()?.map { it.name }?.toSet() ?: emptySet()+        assertFailsWith<SecurityException> {+            denyingManager.encryptAndMove(+                Uri.parse("content://denied/photo1"),+                "grant-expired.jpg",+                password,+            )+        }+        val after = vaultDir.listFiles()?.map { it.name }?.toSet() ?: emptySet()+        assertEquals(before, after, "orphaned partial vault files")+    } }
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultVm3Test.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultVm3Test.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultVm3Test.ktindex 201ce7feb5..1e5d256436 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultVm3Test.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1VaultVm3Test.kt@@ -1,6 +1,7 @@ package com.vayunmathur.photos.util  import android.app.Application+import android.content.ContentResolver import android.graphics.Bitmap import androidx.test.core.app.ApplicationProvider import com.vayunmathur.photos.data.Photo@@ -14,21 +15,25 @@ import javax.crypto.Cipher import javax.crypto.spec.SecretKeySpec import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import org.junit.runner.RunWith+import org.mockito.ArgumentMatchers.any+import org.mockito.Mockito.`when`+import org.mockito.Mockito.mock import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows import org.robolectric.annotation.Config  /** Slice 1/3 second pass: SecureFolderViewModel restore/move coroutine bodies. */ @RunWith(RobolectricTestRunner::class)-@Config(sdk = [34])+@Config(sdk = [34], application = DenyingApp::class) class PhotosSlice1VaultVm3Test { +    private val app = ApplicationProvider.getApplicationContext<DenyingApp>()     private val context = ApplicationProvider.getApplicationContext<android.content.Context>()-    private val app = context.applicationContext as Application     private val password = "correct horse battery staple"      private class FakeDao(rows: List<VaultPhoto> = emptyList()) : VaultPhotoDao {@@ -153,4 +158,75 @@ class PhotosSlice1VaultVm3Test {         assertTrue(dao.store.isEmpty())         assertEquals(false, called)     }++    @Test+    fun moveToSecureWithStreamDeniedSkipsPhotoWithoutCrashingOrOrphans() {+        // Simulate an expired read grant: the thumbnail still loads, but+        // opening the full stream throws SecurityException — the raw exception+        // a device delivers when a cloud document's grant is revoked after the+        // gallery indexed it. (Mockito's inline maker stubs the final+        // openInputStream; subclassing cannot — every stream API on+        // ContentResolver is final in the compile SDK.)+        val resolver = mock(ContentResolver::class.java)+        `when`(resolver.loadThumbnail(any(), any(), any()))+            .thenReturn(Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888))+        `when`(resolver.openInputStream(any()))+            .thenThrow(SecurityException("denied-open"))+        app.resolverOverride = resolver+        try {+            val vaultDir = File(context.filesDir, "secure_vault")+            val before = vaultDir.listFiles()?.map { it.name }?.toSet() ?: emptySet()+            val vm = SecureFolderViewModel(app)+            val dao = FakeDao()+            vm.setVault(dao, password)+            val source = Photo(+                name = "grant-expired.jpg", uri = "content://denied/photo1",+                date = 1L, width = 10, height = 10, dateModified = 1L,+                exifSet = false, lat = null, long = null, videoData = null,+                panoData = null, isTrashed = false,+            )+            var called = false+            // An exception escaping viewModelScope lands on the thread's uncaught+            // handler (on a device: an app crash). Capture it to prove the scope+            // contains the denial instead of leaking it.+            val crashed = mutableListOf<Throwable>()+            val prev = Thread.getDefaultUncaughtExceptionHandler()+            Thread.setDefaultUncaughtExceptionHandler { _, e ->+                synchronized(crashed) { crashed += e }+            }+            try {+                vm.moveToSecure(listOf(source), FakePhotos(context)) { called = true }+                // Give the IO coroutine a chance to run. The per-photo denial must+                // be swallowed like any other per-photo failure: nothing is+                // upserted, the success callback never fires, no exception escapes+                // the scope, and no partial vault file is left behind.+                val deadline = System.currentTimeMillis() + 3_000+                while (System.currentTimeMillis() < deadline) {+                    Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+                    Thread.sleep(20)+                }+            } finally {+                Thread.setDefaultUncaughtExceptionHandler(prev)+            }+            assertTrue(crashed.isEmpty(), "exception escaped moveToSecure scope: $crashed")+            assertTrue(dao.store.isEmpty())+            assertFalse(called)+            val after = vaultDir.listFiles()?.map { it.name }?.toSet() ?: emptySet()+            assertEquals(before, after, "orphaned partial vault files")+        } finally {+            app.resolverOverride = null+        }+    }+}++/**+ * Application whose ContentResolver can be swapped for a stub. Properly+ * attached by Robolectric (unlike a manually-registered provider), and a+ * pass-through when [resolverOverride] is unset, so existing tests are+ * unaffected.+ */+class DenyingApp : Application() {+    var resolverOverride: ContentResolver? = null+    override fun getContentResolver(): ContentResolver =+        resolverOverride ?: super.getContentResolver() }