Modern Apps git

← Modern-Apps.git

library/image: ByteArray cache keys hash the whole payload, not a 16-byte prefix

Commit
e59c148944c3369978e2a743eaf24547b1ac07df
Author
Vayun Mathur <[email protected]>
When
2026-12-01 10:04 UTC (5 days ago)
Parents
17b6f51
dataKey for ByteArray was length plus the hash of only the
first 16 bytes. Encoded formats share prefixes by
construction (PNG signature + IHDR, JPEG SOI/quant headers,
SVG prologues) and lengths routinely match, so two distinct
payloads shared the memory cache, disk key and in-flight
coalescing: the second execute() returned the first
payload's bitmap from memory, and a fresh loader returned
its bytes from disk. The regression test's two 137-byte
SVGs differ only in a fill colour past the prefix.

The key is now size plus SHA-256 of the full payload (the
helper added beside the existing String.sha256; disk
filenames already SHA-256 the key string, so naming is
unchanged in kind). Identical payloads still hit memory and
disk (asserted as positive controls); both collision tests
failed against the temporarily restored prefix key.
Transform folding, disk locking and fetch ordering were
audited and cleared. Verified: :library:image:
testDebugUnitTest 59 tests pass; lint no issues.

Diff

library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt b/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.ktindex cdbfb40ee2..f1059e851d 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt@@ -13,6 +13,7 @@ import com.vayunmathur.library.image.fetchers.ContentResolverFetcher import com.vayunmathur.library.image.fetchers.FetchResult import com.vayunmathur.library.image.fetchers.Fetcher import com.vayunmathur.library.image.fetchers.FileFetcher+import com.vayunmathur.library.image.util.sha256 import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred@@ -22,8 +23,6 @@ import kotlinx.coroutines.async import kotlinx.coroutines.withContext import java.io.File -private const val DATA_KEY_SAMPLE_BYTES = 16- /**  * Replacement for `coil.ImageLoader`. Uses:  * - [MemoryCache] (LruCache<String, Bitmap>)@@ -76,7 +75,12 @@ class ImageLoader private constructor(     private fun dataKey(request: ImageRequest): String = when (val d = request.data) {         null -> "null"         is String -> d-        is ByteArray -> "bytes_${d.size}_${d.take(DATA_KEY_SAMPLE_BYTES).hashCode()}"+        // Hash the whole payload: sampling only a prefix collides for real+        // images, whose headers are byte-identical (PNG signature + IHDR,+        // JPEG SOI/quant tables, "<svg xmlns=\"http" …) and whose encoded+        // lengths routinely match, so a second image was served the first+        // image's memory/disk entry under the shared key.+        is ByteArray -> "bytes_${d.size}_${d.sha256()}"         is Bitmap -> "bitmap_${d.width}x${d.height}_${d.hashCode()}"         else -> d.toString()     }
library/image/src/main/java/com/vayunmathur/library/image/util/Sha256.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/util/Sha256.kt b/library/image/src/main/java/com/vayunmathur/library/image/util/Sha256.ktindex 14814b0e01..5a54734648 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/util/Sha256.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/util/Sha256.kt@@ -7,3 +7,9 @@ fun String.sha256(): String {     val bytes = md.digest(toByteArray(Charsets.UTF_8))     return bytes.joinToString("") { "%02x".format(it) } }++fun ByteArray.sha256(): String {+    val md = MessageDigest.getInstance("SHA-256")+    val bytes = md.digest(this)+    return bytes.joinToString("") { "%02x".format(it) }+}
library/image/src/test/java/com/vayunmathur/library/image/ByteArrayCacheKeyCollisionTest.kt
diff --git a/library/image/src/test/java/com/vayunmathur/library/image/ByteArrayCacheKeyCollisionTest.kt b/library/image/src/test/java/com/vayunmathur/library/image/ByteArrayCacheKeyCollisionTest.ktnew file mode 100644index 0000000000..3118174c10--- /dev/null+++ b/library/image/src/test/java/com/vayunmathur/library/image/ByteArrayCacheKeyCollisionTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.library.image++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.image.util.ensureExists+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Regression: two [ByteArray] payloads with the same encoded length and the+ * same first 16 bytes must not share a cache key. Real images satisfy both+ * conditions routinely (identical format headers, equal lengths), so the old+ * prefix-sampled key served the first image for the second.+ */+@RunWith(RobolectricTestRunner::class)+class ByteArrayCacheKeyCollisionTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    private fun svgBytes(fill: String) =+        ("""<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10" viewBox="0 0 20 10">""" ++            """<rect width="20" height="10" fill="$fill"/></svg>""")+            .toByteArray()++    private fun freshDisk(name: String): DiskCache {+        val dir = File(ctx.cacheDir, "bytes-key-$name-${System.nanoTime()}").ensureExists()+        return DiskCache(dir, 4 * 1024 * 1024)+    }++    private fun request(data: ByteArray) =+        ImageRequest.Builder(ctx).data(data).size(Size(20, 10)).build()++    @Test fun `distinct byte arrays sharing prefix and length do not collide in memory cache`(): Unit = runBlocking {+        val first = svgBytes("#101010")+        val second = svgBytes("#202020")+        // Preconditions of the old collision: equal length, equal 16-byte prefix, different payloads.+        assertEquals(first.size, second.size)+        assertTrue(first.take(16).toByteArray().contentEquals(second.take(16).toByteArray()))+        assertFalse(first.contentEquals(second))++        val loader = ImageLoader.Builder(ctx)+            .diskCache(freshDisk("memory"))+            .memoryCache(MemoryCache.Builder().build())+            .build()++        val firstResult = loader.execute(request(first))+        assertTrue(firstResult is ImageResult.Success)++        val secondResult = loader.execute(request(second))+        assertTrue(secondResult is ImageResult.Success)+        assertFalse(+            secondResult.isFromMemory,+            "second payload must not be served from the first payload's memory entry",+        )+        assertTrue(+            secondResult.bitmap !== firstResult.bitmap,+            "second payload must decode its own bitmap, not reuse the first payload's",+        )++        // The identical payload still hits its own entry.+        val againResult = loader.execute(request(first.copyOf()))+        assertTrue(againResult is ImageResult.Success)+        assertTrue(againResult.isFromMemory)+        assertTrue(againResult.bitmap === firstResult.bitmap)+    }++    @Test fun `distinct byte arrays sharing prefix and length do not collide on disk cache`(): Unit = runBlocking {+        val first = svgBytes("#101010")+        val second = svgBytes("#202020")+        val disk = freshDisk("disk")++        val writer = ImageLoader.Builder(ctx)+            .diskCache(disk)+            .memoryCache(MemoryCache.Builder().build())+            .build()+        assertTrue(writer.execute(request(first)) is ImageResult.Success)++        // A fresh loader (empty memory) over the same disk cache must not be+        // handed the first payload's raw bytes for the second payload.+        val reader = ImageLoader.Builder(ctx)+            .diskCache(disk)+            .memoryCache(MemoryCache.Builder().build())+            .build()+        val result = reader.execute(request(second))+        assertTrue(result is ImageResult.Success)+        assertEquals(ImageResult.DataSource.NETWORK, result.dataSource)++        // And the first payload is still served from disk by that reader.+        val diskResult = reader.execute(request(first))+        assertTrue(diskResult is ImageResult.Success)+        assertEquals(ImageResult.DataSource.DISK, diskResult.dataSource)+    }+}