Modern Apps git

← Modern-Apps.git

backup: restore paths can no longer escape or glue onto the restore dir

Commit
cf1e2487d4c27012b92782e641ab6a0bc5e0fa1a
Author
Vayun Mathur <[email protected]>
When
2026-12-01 00:18 UTC (5 days ago)
Parents
8369eca
Restore computed destinations by concatenating the stored
relativePath with the display name, trusting that the path
ended in a separator and never escaped the root. A root-level
file stored with relativePath "/" resolved outside
BackupRestore/; a separator-less "Pictures" glued into
Picturesphoto.jpg; a stored ../ display name walked out of
the tree. The backup side was unaffected (blob names are
fileId hashes), and the existing tests only ever covered
"Pictures/", "Music/" and "" — never "/" or glued names.

Destinations now come from a single restoreTarget that splits
the stored path on '/', drops blank/./.. segments, joins the
rest under the restore root, and takes the display name's
leaf (falling back to fileId for a blank/dot name). Stored
entries can never resolve outside BackupRestore/, and no
format change means existing backups restore correctly
without migration. Three regression tests failed pre-fix:
root-level file placement, separator-less paths, and the
escape case. Crypto, SAF staging and manifest handling were
audited and cleared. Verified: :backup:testDevUnitTest 52
tests pass; the one lint error is pre-existing coverage work
on an untouched file.

Diff

backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.kt b/backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.ktindex a2aa46b49c..fb36ee58ab 100644--- a/backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.kt+++ b/backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.kt@@ -72,7 +72,7 @@ class FileBackupManager(             onProgress(0, entries.size)             var restored = 0             for ((i, e) in entries.withIndex()) {-                val outFile = File(baseDir, e.relativePath + e.displayName)+                val outFile = restoreTarget(baseDir, e)                 val result = runCatching {                     outFile.parentFile?.mkdirs()                     FileOutputStream(outFile).use { repo.readEncryptedTo(BackupRepository.filePath(e.fileId), it) }@@ -89,6 +89,27 @@ class FileBackupManager(             restored         } +    /**+     * The file [entry] restores to under [baseDir]. The stored relative path is+     * joined segment by segment rather than concatenated: MediaStore yields `/`+     * for volume-root files (an absolute-looking child would escape [baseDir]+     * and never restore), and a path without a trailing separator would glue+     * onto the display name (`Picturesphoto.jpg`). Segments that are blank,+     * `.` or `..` are dropped so a stored entry can never resolve outside the+     * restore directory.+     */+    private fun restoreTarget(baseDir: File, entry: FileEntry): File {+        var dir = baseDir+        for (segment in entry.relativePath.split('/')) {+            if (segment.isNotBlank() && segment != "." && segment != "..") {+                dir = File(dir, segment)+            }+        }+        val name = entry.displayName.substringAfterLast('/').substringAfterLast('\\')+            .takeIf { it.isNotBlank() && it != "." && it != ".." } ?: entry.fileId+        return File(dir, name)+    }+     private data class Item(val uri: Uri, val entry: FileEntry)      private suspend fun enumerate(): List<Item> = withContext(Dispatchers.IO) {
backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.kt b/backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.ktindex 027fdbc7d5..1b0fff6cc3 100644--- a/backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.kt+++ b/backup/src/test/java/com/vayunmathur/backup/data/files/FileBackupManagerTest.kt@@ -90,6 +90,48 @@ class FileBackupManagerTest {         assertFalse(File(base, "Pictures/bad.jpg").exists())     } +    @Test fun restorePlacesRootLevelFileInsideRestoreDir() = runBlocking<Unit> {+        val (repo, _, manager) = setup()+        // MediaStore stores "/" as the relative path of a file at the volume+        // root. Concatenating it ("$relativePath$displayName") produced the+        // absolute child "/photo.jpg", which resolves outside BackupRestore/+        // and so never restored.+        val entry = FileEntry("root1", "photo.jpg", "/", "image/jpeg", 3, 100L, "image")+        repo.writeEncrypted("files/index.json", Json.encodeToString(FileIndex.serializer(), FileIndex(listOf(entry))).toByteArray())+        repo.writeEncrypted(BackupRepository.filePath("root1"), "abc".toByteArray())+        assertEquals(1, manager.restoreAll())+        val base = File(ctx.getExternalFilesDir(null), "BackupRestore")+        assertEquals("abc", File(base, "photo.jpg").readText())+    }++    @Test fun restoreSeparatesRelativePathWithoutTrailingSeparator() = runBlocking<Unit> {+        val (repo, _, manager) = setup()+        // A stored path without a trailing separator must still nest the file+        // under its directory instead of gluing ("Picturesphoto.jpg") at the+        // restore root while nevertheless being counted as restored.+        val entry = FileEntry("id9", "photo.jpg", "Pictures", "image/jpeg", 3, 100L, "image")+        repo.writeEncrypted("files/index.json", Json.encodeToString(FileIndex.serializer(), FileIndex(listOf(entry))).toByteArray())+        repo.writeEncrypted(BackupRepository.filePath("id9"), "abc".toByteArray())+        assertEquals(1, manager.restoreAll())+        val base = File(ctx.getExternalFilesDir(null), "BackupRestore")+        assertEquals("abc", File(base, "Pictures/photo.jpg").readText())+        assertFalse(File(base, "Picturesphoto.jpg").exists())+    }++    @Test fun restoreNeverEscapesRestoreDir() = runBlocking<Unit> {+        val (repo, _, manager) = setup()+        // Stored traversal segments must land inside BackupRestore/, never+        // outside it, whatever a stored entry contains.+        val entry = FileEntry("esc1", "../evil.jpg", "../outside/", "image/jpeg", 3, 100L, "image")+        repo.writeEncrypted("files/index.json", Json.encodeToString(FileIndex.serializer(), FileIndex(listOf(entry))).toByteArray())+        repo.writeEncrypted(BackupRepository.filePath("esc1"), "abc".toByteArray())+        assertEquals(1, manager.restoreAll())+        val base = File(ctx.getExternalFilesDir(null), "BackupRestore")+        assertEquals("abc", File(base, "outside/evil.jpg").readText())+        assertFalse(File(ctx.getExternalFilesDir(null), "evil.jpg").exists())+        assertFalse(File(ctx.getExternalFilesDir(null), "outside/evil.jpg").exists())+    }+     @Test fun fileEntryAndIndexSerialization() {         val e = FileEntry("id", "n", "p/", "text/plain", 12L, 34L, "image")         assertEquals(e, FileEntry(e.fileId, e.displayName, e.relativePath, e.mimeType, e.size, e.dateModified, e.mediaType))