feat(android): serve cover files to media browsers read-only

Android Auto loads browse item artwork from the item's icon URI in its
own process, so it cannot open the app's private cover files and local
covers were left out of every browse list.

CoverContentProvider serves them as content://<applicationId>.covers/
<folder>/<file>. A car cannot hold a permission, so the provider is
exported, and in exchange it only reads: openFile accepts mode "r" only,
insert/update/delete throw, query lists nothing. CoverProviderFiles
resolves a URI to a file only when its path is an allowed folder name
and a plain file name, the canonical file sits directly in the
canonical folder (no "..", encoded "/" or symbolic link out), and it is
a regular file starting with a known image signature.

The allowed folders are the ones browse lists name: the cover store
(files/covers), Library thumbnails (files/library_covers) and embedded
artwork extracted from downloads (cache/embedded_cover_previews). The
covers channel hands Dart the authority and folder paths, registered on
the shared engine so a car-started engine has it too.
This commit is contained in:
zarzet committed 2026-10-30 18:53:55 +07:00
1 parent 08d524eba4
commit 8b36e856ef
5 files changed
+299

No files matched your search

+9
View File
@@ -220,6 +220,15 @@
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<!-- Cover images Android Auto loads for browse lists. A car cannot
hold a permission, so it is exported and serves read-only cover
files of the app's cover folders (see CoverProviderFiles). -->
<provider
android:name=".CoverContentProvider"
android:authorities="${applicationId}.covers"
android:exported="true"
android:grantUriPermissions="false" />
</application>
<queries>
@@ -0,0 +1,73 @@
package com.zarz.mornye
import android.content.ContentProvider
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import java.io.File
import java.io.FileNotFoundException
/**
* Cover images for media browsers such as Android Auto, which run in
* another process and load list artwork from the item's URI. A car cannot
* hold a permission, so the provider is exported, and in exchange it only
* reads: regular image files directly in the folders [CoverProviderFiles]
* allows, named as `content://<authority>/<folder>/<file>`, with no
* listing and no writes.
*/
class CoverContentProvider : ContentProvider() {
private val folders: Map<String, File> by lazy { coverFolders(requireNotNull(context)) }
override fun onCreate() = true
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
if (mode != "r") throw SecurityException("Covers are read-only")
val file = coverFile(uri) ?: throw FileNotFoundException("No cover at this URI")
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
}
override fun getType(uri: Uri): String? = coverFile(uri)?.let(CoverProviderFiles::imageType)
override fun query(
uri: Uri,
projection: Array<out String>?,
selection: String?,
selectionArgs: Array<out String>?,
sortOrder: String?,
): Cursor? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = readOnly()
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<out String>?,
): Int = readOnly()
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = readOnly()
private fun readOnly(): Nothing = throw UnsupportedOperationException("Covers are read-only")
private fun coverFile(uri: Uri): File? {
val context = context ?: return null
if (uri.scheme != ContentResolver.SCHEME_CONTENT || uri.authority != authority(context)) return null
return CoverProviderFiles.resolve(folders, uri.pathSegments)
}
companion object {
private fun authority(context: Context) = "${context.packageName}.covers"
private fun coverFolders(context: Context) =
CoverProviderFiles.folders(context.filesDir, context.cacheDir)
/** The authority and folder paths Dart builds cover URIs from. */
fun describe(context: Context): Map<String, Any> = mapOf(
"authority" to authority(context),
"folders" to coverFolders(context).mapValues { it.value.path },
)
}
}
@@ -0,0 +1,78 @@
package com.zarz.mornye
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
/**
* Which file a [CoverContentProvider] URI names. Its path is two segments:
* the name of an allowed folder, then the name of a regular image file
* directly in that folder. Anything else names nothing, including a name
* that leaves the folder through `..`, an encoded `/` or a symbolic link.
*/
internal object CoverProviderFiles {
/**
* The app's cover folders that media browser lists name: covers the
* cover store fetched, Library thumbnails, and embedded artwork read
* from downloaded songs.
*/
fun folders(files: File, cache: File): Map<String, File> = mapOf(
"covers" to File(files, "covers"),
"library_covers" to File(files, "library_covers"),
"embedded_cover_previews" to File(cache, "embedded_cover_previews"),
)
/** The image file [segments] name in [folders], or null. */
fun resolve(folders: Map<String, File>, segments: List<String>): File? {
if (segments.size != 2) return null
val folder = folders[segments[0]] ?: return null
val name = segments[1]
if (name.isEmpty() || name.startsWith('.') || name.any { it == '/' || it == '\u0000' }) {
return null
}
return try {
val root = folder.canonicalFile
val file = File(root, name).canonicalFile
file.takeIf { it.parentFile == root && it.isFile && imageType(it) != null }
} catch (_: IOException) {
null
} catch (_: SecurityException) {
null
}
}
/** The MIME type of the image [file] holds, or null when it holds none. */
fun imageType(file: File): String? = try {
RandomAccessFile(file, "r").use { input ->
val head = ByteArray(12)
val count = input.read(head)
imageType(if (count > 0) head.copyOf(count) else ByteArray(0))
}
} catch (_: IOException) {
null
}
/** The MIME type of the image whose first 12 bytes are [head], or null. */
fun imageType(head: ByteArray): String? {
fun has(offset: Int, magic: String) =
head.size >= offset + magic.length &&
magic.indices.all { head[offset + it] == magic[it].code.toByte() }
return when {
has(0, "ÿØÿ") -> "image/jpeg"
has(0, "\u0089PNG\r\n\u001A\n") -> "image/png"
has(0, "GIF8") -> "image/gif"
has(0, "RIFF") && has(8, "WEBP") -> "image/webp"
has(0, "BM") -> "image/bmp"
has(4, "ftyp") && head.size >= 12 -> when (String(head, 8, 4, Charsets.ISO_8859_1)) {
"avif", "avis" -> "image/avif"
in heifBrands -> "image/heif"
else -> null
}
else -> null
}
}
private val heifBrands = setOf(
"heic", "heim", "heis", "heix", "hevc", "hevm", "hevs", "hevx", "mif1", "msf1",
)
}
@@ -23,6 +23,13 @@ internal object SharedEngineChannels {
engine.plugins.add(MusicHapticsPlugin())
PlayerWidgetBridge.attach(context, engine)
registerPlaybackBackend(context, MethodChannel(engine.dartExecutor.binaryMessenger, BACKEND_CHANNEL))
MethodChannel(engine.dartExecutor.binaryMessenger, COVERS_CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "provider") {
result.success(CoverContentProvider.describe(context))
} else {
result.notImplemented()
}
}
}
/**
@@ -50,4 +57,5 @@ internal object SharedEngineChannels {
}
private const val BACKEND_CHANNEL = "com.zarz.mornye/backend"
private const val COVERS_CHANNEL = "com.zarz.mornye/covers"
}
@@ -0,0 +1,131 @@
package com.zarz.mornye
import java.io.File
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
class CoverProviderFilesTest {
private lateinit var app: File
private lateinit var folders: Map<String, File>
private val jpeg = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte(), 0xE0.toByte(), 0, 16)
@Before
fun createFolders() {
app = Files.createTempDirectory("cover-provider-test").toFile().canonicalFile
folders = CoverProviderFiles.folders(File(app, "files"), File(app, "cache"))
folders.values.forEach { it.mkdirs() }
}
@After
fun deleteFolders() {
app.deleteRecursively()
}
private fun write(path: String, bytes: ByteArray = jpeg) =
File(app, path).also {
it.parentFile!!.mkdirs()
it.writeBytes(bytes)
}
private fun resolve(vararg segments: String) = CoverProviderFiles.resolve(folders, segments.toList())
@Test
fun servesTheCoverFoldersBrowseListsName() {
assertEquals(
mapOf(
"covers" to File(app, "files/covers"),
"library_covers" to File(app, "files/library_covers"),
"embedded_cover_previews" to File(app, "cache/embedded_cover_previews"),
),
folders,
)
val stored = write("files/covers/0123_abcd.image")
val thumbnail = write("files/library_covers/thumb.jpg")
val embedded = write("cache/embedded_cover_previews/v1_hash_0.jpg")
assertEquals(stored, resolve("covers", "0123_abcd.image"))
assertEquals(thumbnail, resolve("library_covers", "thumb.jpg"))
assertEquals(embedded, resolve("embedded_cover_previews", "v1_hash_0.jpg"))
}
@Test
fun namesNothingOutsideItsFolders() {
write("files/shared_prefs/settings.jpg")
write("files/playlist_covers/list.jpg")
write("files/library_covers/sub/nested.jpg")
assertNull(resolve("playlist_covers", "list.jpg"))
assertNull(resolve("files", "covers"))
assertNull(resolve("library_covers"))
assertNull(resolve("library_covers", "sub", "nested.jpg"))
assertNull(resolve("library_covers", "sub/nested.jpg"))
assertNull(resolve("library_covers", "../shared_prefs/settings.jpg"))
assertNull(resolve("library_covers", ".."))
assertNull(resolve("library_covers", "."))
assertNull(resolve("library_covers", ""))
assertNull(resolve("library_covers", "sub"))
assertNull(resolve("library_covers", "missing.jpg"))
assertNull(resolve("library_covers", "thumb.jpg\u0000.png"))
}
@Test
fun followsNoLinkOutOfAFolder() {
val secret = write("files/shared_prefs/settings.jpg")
val thumbnail = write("files/library_covers/thumb.jpg")
Files.createSymbolicLink(File(app, "files/library_covers/link.jpg").toPath(), secret.toPath())
Files.createSymbolicLink(File(app, "files/covers/linked.jpg").toPath(), thumbnail.toPath())
Files.createSymbolicLink(File(app, "files/library_covers/folder").toPath(), secret.parentFile!!.toPath())
assertNull(resolve("library_covers", "link.jpg"))
assertNull(resolve("covers", "linked.jpg"))
assertNull(resolve("library_covers", "folder"))
}
@Test
fun servesOnlyImagesThatAreNotHidden() {
write("files/library_covers/.staged.jpg")
write("files/library_covers/notes.txt", "not an image".toByteArray())
write("files/library_covers/empty.jpg", ByteArray(0))
write("files/library_covers/regenerate.marker", "2026-10-30T00:00:00".toByteArray())
assertNull(resolve("library_covers", ".staged.jpg"))
assertNull(resolve("library_covers", "notes.txt"))
assertNull(resolve("library_covers", "empty.jpg"))
assertNull(resolve("library_covers", "regenerate.marker"))
}
@Test
fun aFolderReachedThroughALinkStillServesItsOwnFiles() {
val real = File(app, "real").also { it.mkdirs() }
val cover = File(real, "thumb.jpg").also { it.writeBytes(jpeg) }
val linked = File(app, "linked_files")
Files.createSymbolicLink(linked.toPath(), real.toPath())
assertEquals(
cover,
CoverProviderFiles.resolve(mapOf("library_covers" to linked), listOf("library_covers", "thumb.jpg")),
)
}
@Test
fun recognizesTheImageFormatsTheCoverStoreKeeps() {
fun type(vararg bytes: Int) = CoverProviderFiles.imageType(ByteArray(bytes.size) { bytes[it].toByte() })
fun type(text: String) = CoverProviderFiles.imageType(text.toByteArray(Charsets.ISO_8859_1))
assertEquals("image/jpeg", type(0xFF, 0xD8, 0xFF, 0xDB))
assertEquals("image/png", type(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A))
assertEquals("image/gif", type("GIF89a"))
assertEquals("image/webp", type("RIFF\u0000\u0000\u0000\u0000WEBP"))
assertEquals("image/bmp", type("BM\u0000\u0000"))
assertEquals("image/avif", type("\u0000\u0000\u0000 ftypavif"))
assertEquals("image/heif", type("\u0000\u0000\u0000 ftypheic"))
assertNull(type("\u0000\u0000\u0000 ftypisom"))
assertNull(type("<svg"))
assertNull(type(0xFF, 0xD8))
assertNull(CoverProviderFiles.imageType(ByteArray(0)))
}
}