Modern Apps git

← Modern-Apps.git

appstore: list only developer-signed F-Droid apps

Commit
3b849c4092b3f51699779d25de0365f40aec93d0
Author
Vayun Mathur <[email protected]>
When
2026-12-03 15:25 UTC (2 days ago)
Parents
171abb0
The F-Droid source claimed reproducible-builds only, but the
catalogue imported every app in the signed index-v2 and used
reproducibility only as a badge. Install verification checked the
download against whatever signer index-v2 published, so an app
signed by F-Droid itself listed and installed like any other.

index-v2 cannot tell the two apart: f-droid.org signs most apps
with a per-app key it generates, which looks exactly like a
developer key. The distinguishing data is the build metadata's
AllowedAPKSigningKeys, republished as apps[].allowedAPKSigningKeys
in the signed index-v1.jar (2,086 of 5,085 current packages; their
advertised signers all match). When a package lists allowed keys,
f-droid.org publishes the developer-signed reproducible APK;
otherwise the APK is F-Droid-signed.

FDroidAllowedSigners now streams the verified index-v1 (same pinned
fingerprint, via a new streaming SignedJarIndex read so the 79 MB
JSON is never held whole) and FDroidAppProvider drops, before any
row is written, every F-Droid app whose advertised signer is not an
allowed developer key. A failed allowed-keys fetch fails the sync
and keeps the previous catalogue instead of importing unfiltered.
Successful syncs replace the repo's rows, so apps an earlier
unfiltered sync cached are evicted. The gate is F-Droid-only; the
other sources' trust rules are untouched, and install-time
verification is unchanged as defence in depth. Trust strings and
appstore/AGENTS.md updated to match.

Tests: FDroidAllowedSignersTest joins allowed keys against
advertised signers (developer key admitted; F-Droid key, missing
signer and unlisted package rejected; malformed entries skipped).
FDroidAppProviderSyncTest now serves a signed index-v1 fixture and
proves at import level that a developer-signed app reaches the DB
while an F-Droid-signed one does not, and that a later sync evicts
a row the gate drops.

Verified: :appstore:lint, :appstore:lintVitalRelease and
:appstore:compileDevKotlin green. :appstore:testDevUnitTest runs
525 tests with one failure, TvMainActivityTest rail renders,
which reproduces identically on the unmodified base commit, so
it predates this change.

Diff

appstore/AGENTS.md
diff --git a/appstore/AGENTS.md b/appstore/AGENTS.mdindex 76e186c265..4a4b271fd1 100644--- a/appstore/AGENTS.md+++ b/appstore/AGENTS.md@@ -13,12 +13,12 @@ _Install: ./install appstore (dev by default)._ ## Overview **Purpose:** Security-first app store — six sources (own repo, curated mirror, F-Droid, GrapheneOS, Accrescent, Play) with every download signature-checked and a plain-language security tier per app (who could push a malicious update). **Key features:**-- Multi-source catalogs: F-Droid (reproducible-builds only), Accrescent (Signify trust), anonymous Play (no Google account), GrapheneOS bundle one-tap+- Multi-source catalogs: F-Droid (developer-signed reproducible builds only — apps signed with an F-Droid-held per-app key are never imported), Accrescent (Signify trust), anonymous Play (no Google account), GrapheneOS bundle one-tap - Top filters filter by source (search/library) or category (home); there is no TV filter chip — catalogue results are limited to TV-compatible apps only when the device itself is a TV (`DeviceAttributesProvider.isTv`, applied by `CatalogRepository` on every read) - Install pipeline: `InstallCoordinator` → `SessionInstaller` → `InstallStatusReceiver`, verified by `InstallVerifier` (APK certs, signed-jar index, source stamps) before the system installer sees anything - `UpdateCheckWorker` background checks; outdated-target-API apps refused, not hidden - OpenAssistant tools (read-only, in `intents/` behind the signature `ACCESS_APPSTORE` permission): `appstore_search_apps` searches the local catalogue (query, limit clamped to 10, summary capped at 120 chars) and `appstore_get_updates` returns an update count plus at most 10 app names; no install/update/uninstall action is exposed-**Architecture / data-flow:** `ui/` home/search/detail/library/updates/sources/trust (+ `ui/dialogs/` stateless dialog contents for the `Route.UninstallDialog` / TV `UninstallDialog` routes) → `platform/AppStoreViewModel` (+ per-area `*Ops`, `AppStoreUiContract`) → `data/` providers per source (`*Repository`, Play/F-Droid/Accrescent clients) + `data/installer/` + `data/security/`; `domain/SearchRanking` is pure ranking.+**Architecture / data-flow:** `ui/` home/search/detail/library/updates/sources/trust (+ `ui/dialogs/` stateless dialog contents for the `Route.UninstallDialog` / TV `UninstallDialog` routes) → `platform/AppStoreViewModel` (+ per-area `*Ops`, `AppStoreUiContract`) → `data/` providers per source (`*Repository`, Play/F-Droid/Accrescent clients) + `data/installer/` + `data/security/`; `domain/SearchRanking` is pure ranking. The F-Droid provider additionally downloads the same repo's signed `index-v1.jar` (`FDroidAllowedSigners` in `data/FDroidVerification.kt`, verified against the descriptor's pinned fingerprint and streamed, not loaded whole) and drops every F-Droid app whose advertised version signer is not one of that package's `allowedAPKSigningKeys` before any row is written — index-v2 alone cannot tell a developer key from an F-Droid-generated per-app key. That gate is F-Droid-only; the other F-Droid-format repos keep their own trust rules. **Repo addresses:** our own F-Droid-format repos are consumed from the static R2 bucket — `DefaultRepos.MODERN_APPS` = `https://static.maproj.org/fdroid/repo`, `DefaultRepos.PROPRIETARY` = `https://static.maproj.org/proprietary/repo` (same signed indexes/APKs the server publishes on every build; signing fingerprint pinned as before). The legacy origin addresses (`maproj.org/fdroid/repo`, `maproj.org/proprietary/repo`) keep serving external F-Droid clients and are named only as `LEGACY_*_ORIGIN_URL` constants: stored repo records and cached rows are keyed by URL, so `CatalogRepository.ensureDefaultRepos` prunes rows written under the old addresses and the next sync re-imports under the static ones (no double-added repos). **Entry points + reading order:** `MainActivity.kt` → `Route.kt` → `ui/AppRoot.kt` → `ui/HomePage.kt` → `platform/AppStoreViewModel.kt` → `data/CatalogRepository.kt` → `data/installer/InstallCoordinator.kt` → `data/security/InstallVerifier.kt`. **Gotchas:**
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.ktindex 361d1bd5a0..368aaf15eb 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt@@ -8,14 +8,19 @@ import kotlinx.coroutines.withContext /**  * Imports one hard-pinned F-Droid-format repository into the shared offline catalogue.  *- * The whole catalogue is imported (newest version of every app). For repositories that- * support it, F-Droid's reproducibility feed ([ReproducibleBuilds]) is consulted only to- * badge versions independently reproduced bit-for-bit. IzzyOnDroid is the exception:- * it ships developers' own binaries, so its rbtlog feed ([IzzyReproducibleBuilds]) is- * an admission gate — versions no independent builder reproduced are dropped, and a- * failed feed fetch imports nothing. Either feed is best-effort; signed-index- * verification always fails closed, so unauthenticated hashes and signer keys never replace- * cached rows.+ * The whole catalogue is imported (newest version of every app), with two+ * admission gates. IzzyOnDroid ships developers' own binaries, so its rbtlog+ * feed ([IzzyReproducibleBuilds]) is a gate — versions no independent builder+ * reproduced are dropped, and a failed feed fetch imports nothing. The+ * f-droid.org source is gated the same way on developer signing instead:+ * only apps whose advertised version is signed with one of the developer+ * keys f-droid.org allows for that package ([FDroidAllowedSigners], from the+ * signed index-v1) are imported at all — apps f-droid.org signed with its+ * own per-app key never reach the catalogue. That fetch fails closed too.+ * For repositories that support it, F-Droid's reproducibility feed+ * ([ReproducibleBuilds]) is consulted only to badge versions independently+ * reproduced bit-for-bit. Signed-index verification always fails closed, so+ * unauthenticated hashes and signer keys never replace cached rows.  */ class FDroidAppProvider(     private val db: AppDatabase,@@ -28,6 +33,10 @@ class FDroidAppProvider(     var lastReproducibleCount: Int = 0         private set +    /** Allowed developer keys fetched for the F-Droid gate on the last sync. */+    @Volatile+    private var fdroidAllowedSigners: FDroidAllowedSigners.Allowed? = null+     /** Refresh [descriptor] and replace only that repository's cached rows. */     suspend fun syncIntoDb(): Int = withContext(Dispatchers.IO) {         var result = try {@@ -49,6 +58,27 @@ class FDroidAppProvider(             )             result = result.copy(apps = kept)         }+        // f-droid.org is listed on a developer-signed claim ("reproducible+        // builds only"): an app it signed with its own per-app key must not+        // appear in any listing, not merely fail later. The allowed-keys+        // fetch inside fetchVerifiedIndex already failed closed, so here the+        // gate is a pure filter over the verified index's own signer data.+        // Replacing this repo's rows below then also evicts rows an earlier+        // unfiltered sync cached for apps the gate now drops.+        if (descriptor.source == AppSource.FDROID) {+            val allowed = fdroidAllowedSigners+            val kept = if (allowed == null) {+                emptyList()+            } else {+                result.apps.filter { allowed.admits(it) }+            }+            Log.status(+                TAG,+                "sync of ${descriptor.displayName}: kept ${kept.size} of " ++                    "${result.apps.size} apps signed by their developer"+            )+            result = result.copy(apps = kept)+        }         Log.status(             TAG,             "sync of ${descriptor.displayName}: fetched ${result.apps.size} " +@@ -104,6 +134,15 @@ class FDroidAppProvider(             }         }         lastReproducibleCount = reproduced+        // The developer-signing gate's data comes from the same repo's signed+        // index-v1. Fetching it here (not best-effort) means any failure throws+        // out of the sync and the previous catalogue stays in place, rather+        // than a fresh catalogue being imported with the gate silently off.+        fdroidAllowedSigners = if (descriptor.source == AppSource.FDROID) {+            FDroidAllowedSigners.fetch(appContext, descriptor.url, descriptor.pinnedFingerprint)+        } else {+            null+        }         return result     } 
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.ktindex 10c7017bf4..693a6d9ed7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.kt@@ -3,9 +3,11 @@ package com.vayunmathur.appstore.data import android.content.Context import android.util.JsonReader import android.util.JsonToken+import com.vayunmathur.appstore.data.security.SignedJarIndex import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File+import java.io.InputStream  /**  * The set of F-Droid builds that have been **reproduced**.@@ -133,3 +135,115 @@ object ReproducibleBuilds {         else -> { r.skipValue(); false }     } }++/**+ * The signing keys f-droid.org allows each app to be signed with — its+ * `AllowedAPKSigningKeys` build metadata, republished in the signed+ * `index-v1.jar` as `apps[].allowedAPKSigningKeys`.+ *+ * This is the only authenticated statement of who signed an F-Droid APK.+ * index-v2 carries each version's signer fingerprint, but f-droid.org signs+ * most apps itself with a per-app key it generates, so a v2 signer alone+ * looks exactly like a developer key. When an app's build metadata lists+ * allowed keys, f-droid.org instead reproduces the developer's own APK+ * bit-for-bit and publishes that developer-signed file; its version signer+ * is then one of the allowed keys. Apps with no allowed keys are signed by+ * an F-Droid-held per-app key, whatever their v2 signer fingerprint is.+ *+ * The v1 index is therefore an admission gate for the F-Droid source in+ * [FDroidAppProvider], not a badge: a listed app's advertised version must+ * be signed with one of its allowed (developer) keys. The jar is verified+ * against the same pinned fingerprint as index-v2 before anything in it is+ * trusted, and a failed fetch or verification imports nothing this sync —+ * listing everything unfiltered is exactly the failure this gate exists to+ * prevent. Other F-Droid-format repos are not gated on it: their trust+ * claims are their own (see [com.vayunmathur.appstore.data.security.TrustProfile]).+ */+object FDroidAllowedSigners {++    /** Package name → lowercase-hex SHA-256 signing-certificate fingerprints it may carry. */+    @JvmInline+    value class Allowed(private val keysByPackage: Map<String, Set<String>>) {+        val size: Int get() = keysByPackage.size++        /** The allowed developer keys for [packageName], empty when it has none. */+        fun keysFor(packageName: String): Set<String> = keysByPackage[packageName].orEmpty()++        /**+         * Whether [app]'s advertised version is developer-signed: f-droid.org+         * allows the package a developer key, and the version the catalogue+         * would offer is actually signed with one of them.+         */+        fun admits(app: UnifiedApp): Boolean {+            val allowed = keysFor(app.packageName)+            if (allowed.isEmpty() || app.expectedSigners.isEmpty()) return false+            return app.expectedSigners.any { it.lowercase() in allowed }+        }+    }++    suspend fun fetch(+        context: Context,+        repoUrl: String,+        pinnedFingerprint: String,+    ): Allowed = withContext(Dispatchers.IO) {+        val jar = File(context.cacheDir, "fdroid-index-v1-${repoUrl.hashCode()}.jar")+        try {+            FDroidRepository.downloadToFile(repoUrl.trimEnd('/') + "/index-v1.jar", jar)+            SignedJarIndex.readVerifiedStreaming(jar, "index-v1.json", pinnedFingerprint) { input ->+                parse(input)+            }.value+        } finally {+            jar.delete()+        }+    }++    internal fun parse(input: InputStream): Allowed {+        val keysByPackage = HashMap<String, Set<String>>(6_000)+        JsonReader(input.reader()).use { r ->+            r.isLenient = true+            r.beginObject()+            while (r.hasNext()) {+                if (r.nextName() == "apps") {+                    readApps(r, keysByPackage)+                } else {+                    r.skipValue()+                }+            }+            r.endObject()+        }+        return Allowed(keysByPackage)+    }++    private fun readApps(r: JsonReader, into: MutableMap<String, Set<String>>) {+        if (r.peek() != JsonToken.BEGIN_ARRAY) {+            r.skipValue()+            return+        }+        r.beginArray()+        while (r.hasNext()) {+            if (r.peek() != JsonToken.BEGIN_OBJECT) {+                r.skipValue()+                continue+            }+            readApp(r, into)+        }+        r.endArray()+    }++    private fun readApp(r: JsonReader, into: MutableMap<String, Set<String>>) {+        var packageName: String? = null+        var allowed: Set<String> = emptySet()+        r.beginObject()+        while (r.hasNext()) {+            when (r.nextName()) {+                "packageName" -> packageName = nextStringOrNull(r)+                "allowedAPKSigningKeys" -> allowed =+                    readStringArray(r).mapTo(mutableSetOf()) { it.lowercase() }+                else -> r.skipValue()+            }+        }+        r.endObject()+        val pkg = packageName+        if (pkg != null && allowed.isNotEmpty()) into[pkg] = allowed+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.ktindex 0bb8caa727..e770e3119e 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.kt@@ -42,6 +42,29 @@ object SignedJarIndex {         return Verified(content, fingerprint)     } +    /** Result of a streaming verified read: the parsed value plus the signer hash. */+    data class Streamed<T>(val value: T, val signerSha256: String)++    /**+     * Streaming form of [readVerified] for entries too large to hold in memory+     * (index-v1.json is ~79 MB uncompressed). [consume] must read the stream to+     * the end: the certificate check afterwards is what makes the read verified,+     * and it only attaches once the entry has been consumed to completion.+     */+    fun <T> readVerifiedStreaming(+        jar: File,+        entryName: String,+        pinnedFingerprint: String,+        consume: (java.io.InputStream) -> T,+    ): Streamed<T> {+        var value: T? = null+        val fingerprint = consumeVerified(jar, entryName, pinnedFingerprint) { input ->+            value = consume(input)+        }+        @Suppress("UNCHECKED_CAST")+        return Streamed(value as T, fingerprint)+    }+     private fun consumeVerified(         jar: File,         entryName: String,
appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.ktindex 168c415e2a..653ad8bf38 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt@@ -57,8 +57,8 @@ object StoreGuarantees {  * developer identity, scans every upload and every device, and can pull a malicious app  * from the whole fleet within hours — a set of practices no F-Droid build server comes  * close to. F-Droid's reproducible builds prove a *different* thing (that the binary- * matches published source), and prove it well, but F-Droid also holds the signing key- * itself and can take weeks to publish a security fix.+ * matches published source), and prove it well, but its rebuild-and-publish+ * pipeline can take weeks to ship a security fix.  *  * Neither of those is strictly better than the other, so the store no longer pretends  * one is. Each profile below states what its source actually does, what this app checks@@ -74,9 +74,11 @@ enum class TrustProfile {     MODERN_APPS,      /**-     * F-Droid, from the one hard-pinned repository. Versions independently reproduced-     * bit-for-bit by F-Droid's verification server are badged; reproducibility is a badge,-     * not an admission gate.+     * F-Droid, from the one hard-pinned repository. Only apps whose advertised+     * version is signed with a developer key f-droid.org allows for that+     * package are listed at all — apps signed with an F-Droid-held per-app key+     * are never imported. Versions independently reproduced bit-for-bit by+     * F-Droid's verification server are additionally badged.      */     FDROID, @@ -216,8 +218,9 @@ enum class TrustProfile {     companion object {         fun of(source: AppSource): TrustProfile = when (source) {             AppSource.MODERN_APPS -> MODERN_APPS-            // The whole F-Droid catalogue is listed; whether a given version was reproduced-            // is shown per-app as a badge (see UnifiedApp.reproducible).+            // Only developer-signed F-Droid versions are ever listed (see+            // FDroidAllowedSigners); whether a given version was also reproduced+            // by the verification server is shown per-app as a badge.             AppSource.FDROID -> FDROID             // Only reproduced Izzy versions are ever listed, so every Izzy row carries             // the badge — the gate is the profile's distinctive fact, not the badge.
appstore/src/main/res/values/strings.xml
diff --git a/appstore/src/main/res/values/strings.xml b/appstore/src/main/res/values/strings.xmlindex df57f0e319..641798bdf6 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -243,15 +243,15 @@     <string name="trust_modern_apps_check_hash">The file matches the hash in the repository\'s signed index</string>     <string name="trust_modern_apps_limits">One developer, one key, no independent review and nobody rebuilding the source to confirm the app matches it. There is no scanning.</string> -    <string name="trust_fdroid_summary">Built from public source code. Versions a second machine independently rebuilt to an identical file are badged as reproducible.</string>-    <string name="trust_fdroid_practice_source">Every app is built from source F-Droid publishes, not from a binary a developer sent in</string>+    <string name="trust_fdroid_summary">Only apps signed by their own developer are listed: F-Droid rebuilt the app from public source to an identical file before publishing the developer\'s copy. Versions a second machine independently rebuilt are badged as reproducible.</string>+    <string name="trust_fdroid_practice_source">Only developer-signed apps are listed — apps F-Droid signed itself are not offered here</string>     <string name="trust_fdroid_practice_rebuild">A second build server rebuilds many apps and compares the result byte for byte</string>     <string name="trust_fdroid_practice_antifeatures">Tracking, ads and non-free dependencies are labelled on the listing</string>     <string name="trust_fdroid_check_index_signed">F-Droid\'s app list is signed, and checked against a key built into this store</string>     <string name="trust_fdroid_check_chained">Every entry in that list is chained back to the signature</string>-    <string name="trust_fdroid_check_rebuilt">Versions F-Droid\'s second build server reproduced bit-for-bit are badged as reproducible</string>+    <string name="trust_fdroid_check_rebuilt">An app is listed only when its signing key is one of the developer keys in the signed list, and its file signer matches it</string>     <string name="trust_fdroid_check_hash_and_key">The hash and the signing key both come from the signed list</string>-    <string name="trust_fdroid_limits">F-Droid holds the signing key, not the developer, so its build servers can sign anything. Nobody checks what an app does, only that it matches its source. Updates wait to be rebuilt, which can take days or weeks, security fixes included.</string>+    <string name="trust_fdroid_limits">Only developer-signed apps are listed, so many F-Droid apps are not offered here at all. Nobody checks what an app does, only that it matches its source. Updates wait to be rebuilt and reproduced, which can take days or weeks, security fixes included.</string>     <string name="trust_izzy_summary">Developer-built apps, listed only when an independent builder reproduced the exact version bit-for-bit from published source.</string>     <string name="trust_izzy_practice_binaries">Apps are the developers\' own signed builds, taken from their release pages</string>     <string name="trust_izzy_practice_reproduced">Independent verification builders rebuild each covered version from its published source tag and compare the result byte for byte</string>
appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAllowedSignersTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAllowedSignersTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAllowedSignersTest.ktnew file mode 100644index 0000000000..0f87e84f2c--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAllowedSignersTest.kt@@ -0,0 +1,89 @@+package com.vayunmathur.appstore.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * The developer-signing gate data: index-v1's `allowedAPKSigningKeys` joined+ * against the version signer index-v2 published for the advertised build.+ */+@RunWith(RobolectricTestRunner::class)+class FDroidAllowedSignersTest {++    private val devKey = "ab".repeat(32)+    private val fdroidKey = "cd".repeat(32)++    private fun parse(json: String): FDroidAllowedSigners.Allowed =+        FDroidAllowedSigners.parse(json.byteInputStream())++    @Test+    fun `parses allowed keys and ignores apps without them`() {+        val allowed = parse(+            """+            {+              "repo": {"name": "F-Droid"},+              "apps": [+                {+                  "packageName": "com.example.devsigned",+                  "name": "Dev Signed",+                  "allowedAPKSigningKeys": ["${devKey.uppercase()}"],+                  "localized": {"en-US": {"description": "ignored"}}+                },+                {+                  "packageName": "com.example.fdroidsigned",+                  "name": "F-Droid Signed"+                }+              ],+              "packages": {"com.example.devsigned": [{"versionCode": 1}]}+            }+            """.trimIndent(),+        )++        assertEquals(1, allowed.size)+        assertEquals(setOf(devKey), allowed.keysFor("com.example.devsigned"))+        assertTrue(allowed.keysFor("com.example.fdroidsigned").isEmpty())+    }++    @Test+    fun `admits only when the advertised signer is an allowed developer key`() {+        val allowed = parse(+            """{"apps": [{"packageName": "com.example.devsigned", """ ++                """"allowedAPKSigningKeys": ["$devKey"]}]}""",+        )+        val devSigned = UnifiedApp(+            packageName = "com.example.devsigned",+            source = AppSource.FDROID,+            name = "Dev Signed",+            expectedSigners = listOf(devKey),+        )+        val wrongKey = devSigned.copy(expectedSigners = listOf(fdroidKey))+        val noSigner = devSigned.copy(expectedSigners = emptyList())+        val unlisted = UnifiedApp(+            packageName = "com.example.fdroidsigned",+            source = AppSource.FDROID,+            name = "F-Droid Signed",+            expectedSigners = listOf(fdroidKey),+        )++        assertTrue(allowed.admits(devSigned))+        // A version signer is not enough on its own: f-droid.org's per-app+        // keys look like developer keys until compared to the allowed list.+        assertFalse(allowed.admits(wrongKey))+        assertFalse(allowed.admits(noSigner))+        assertFalse(allowed.admits(unlisted))+    }++    @Test+    fun `malformed entries do not derail the rest of the apps array`() {+        val allowed = parse(+            """{"apps": ["junk", {"packageName": "com.example.devsigned", """ ++                """"allowedAPKSigningKeys": ["$devKey"]}, 42]}""",+        )++        assertEquals(setOf(devKey), allowed.keysFor("com.example.devsigned"))+    }+}
appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAppProviderSyncTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAppProviderSyncTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAppProviderSyncTest.ktindex 35f9c8bf1d..481d1c13ac 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAppProviderSyncTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidAppProviderSyncTest.kt@@ -37,11 +37,16 @@ class FDroidAppProviderSyncTest {     private lateinit var db: AppDatabase     private lateinit var provider: FDroidAppProvider     private val servedIndex = AtomicReference<ByteArray>()+    private val servedV1Jar = AtomicReference<ByteArray>()     private lateinit var repoUrl: String      private fun indexWith(vararg packages: String): String =         """{"packages": {${packages.joinToString(",")}}}""" +    /** Deterministic per-package signer fingerprint for the fixture index. */+    private fun signerFor(name: String): String =+        name.hashCode().toUInt().toString(16).padStart(8, '0').repeat(8)+     private fun pkg(name: String, file: String): String = """         "com.example.$name": {           "metadata": {"name": {"en-US": "$name"}},@@ -49,11 +54,47 @@ class FDroidAppProviderSyncTest {             "added": 1000,             "file": {"name": "/$file", "sha256": "${"aa".repeat(32)}", "size": 10},             "manifest": {"versionName": "1.0", "versionCode": 1,-                         "usesSdk": {"targetSdkVersion": 35}}+                         "usesSdk": {"targetSdkVersion": 35},+                         "signer": {"sha256": ["${signerFor(name)}"]}}           }}         }     """.trimIndent() +    /** Serve a signed index-v1.jar allowing only [allowedNames]' fixture signers. */+    private fun serveV1(allowedNames: Set<String>) {+        val apps = allowedNames.joinToString(",") { name ->+            """{"packageName": "com.example.$name", """ ++                """"allowedAPKSigningKeys": ["${signerFor(name)}"]}"""+        }+        val v1 = """{"apps": [$apps], "packages": {}}"""+        servedV1Jar.set(signJar("index-v1.json", v1.toByteArray(), "index-v1"))+    }++    /** Sign [content] as [entryName] with the test keystore; returns the jar bytes. */+    private fun signJar(entryName: String, content: ByteArray, stem: String): ByteArray {+        val unsigned = File(work, "$stem-unsigned.jar")+        JarOutputStream(unsigned.outputStream()).use { out ->+            out.putNextEntry(JarEntry(entryName))+            out.write(content)+            out.closeEntry()+        }+        val keystore = File(work, "ks.jks")+        if (!keystore.exists()) {+            runTool(+                "keytool", "-genkeypair", "-alias", "test", "-keyalg", "RSA", "-keysize", "2048",+                "-validity", "3650", "-keystore", keystore.absolutePath,+                "-storepass", "changeit", "-keypass", "changeit", "-dname", "CN=FDroid Test",+            )+        }+        val signed = File(work, "$stem.jar")+        signed.delete()+        runTool(+            "jarsigner", "-keystore", keystore.absolutePath, "-storepass", "changeit",+            "-signedjar", signed.absolutePath, unsigned.absolutePath, "test",+        )+        return signed.readBytes()+    }+     private fun runTool(tool: String, vararg args: String) {         val exe = File(System.getProperty("java.home"), "bin/$tool")         val process = ProcessBuilder(listOf(exe.absolutePath) + args)@@ -79,38 +120,25 @@ class FDroidAppProviderSyncTest {     }      private fun rebuildEntry(entryJson: String) {-        val entryJar = File(work, "entry-unsigned.jar")-        JarOutputStream(entryJar.outputStream()).use { out ->-            out.putNextEntry(JarEntry("entry.json"))-            out.write(entryJson.toByteArray())-            out.closeEntry()-        }+        File(work, "entry.jar").writeBytes(signJar("entry.json", entryJson.toByteArray(), "entry"))         val keystore = File(work, "ks.jks")-        if (!keystore.exists()) {-            runTool(-                "keytool", "-genkeypair", "-alias", "test", "-keyalg", "RSA", "-keysize", "2048",-                "-validity", "3650", "-keystore", keystore.absolutePath,-                "-storepass", "changeit", "-keypass", "changeit", "-dname", "CN=FDroid Test",-            )-        }-        val signedJar = File(work, "entry.jar")-        signedJar.delete()-        runTool(-            "jarsigner", "-keystore", keystore.absolutePath, "-storepass", "changeit",-            "-signedjar", signedJar.absolutePath, entryJar.absolutePath, "test",-        )         val ks = KeyStore.getInstance(KeyStore.getDefaultType())         keystore.inputStream().use { ks.load(it, "changeit".toCharArray()) }         val fingerprint = ApkCertificates.sha256(ks.getCertificate("test").encoded)+        if (servedV1Jar.get() == null) serveV1(setOf("alpha"))          if (!::server.isInitialized) {-            val signedBytes = AtomicReference(signedJar.readBytes())             server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)             server.createContext("/repo/entry.jar") { exchange ->                 val bytes = File(work, "entry.jar").readBytes()                 exchange.sendResponseHeaders(200, bytes.size.toLong())                 exchange.responseBody.use { it.write(bytes) }             }+            server.createContext("/repo/index-v1.jar") { exchange ->+                val bytes = servedV1Jar.get()+                exchange.sendResponseHeaders(200, bytes.size.toLong())+                exchange.responseBody.use { it.write(bytes) }+            }             server.createContext("/repo/index-v2.json") { exchange ->                 val bytes = servedIndex.get()                 exchange.sendResponseHeaders(200, bytes.size.toLong())@@ -134,10 +162,11 @@ class FDroidAppProviderSyncTest {     }      /** Point the signed entry at a new index, as a repo publish would. */-    private fun serveIndex(json: String) {+    private fun serveIndex(json: String, allowedNames: Set<String> = setOf("alpha")) {         servedIndex.set(json.toByteArray())         val entryJson = """{"index": {"name": "index-v2.json", "sha256": "${ApkCertificates.sha256(servedIndex.get())}"}}"""         rebuildEntry(entryJson)+        serveV1(allowedNames)     }      @AfterTest@@ -165,13 +194,48 @@ class FDroidAppProviderSyncTest {         db.cachedAppDao().upsert(             UnifiedApp("com.example.other", AppSource.MODERN_APPS, "Other").toEntity(),         )-        serveIndex(indexWith(pkg("beta", "beta_1.apk")))+        serveIndex(indexWith(pkg("beta", "beta_1.apk")), allowedNames = setOf("beta"))         assertEquals(1, provider.syncIntoDb())         assertEquals(null, db.cachedAppDao().byPackage("com.example.alpha"))         assertNotNull(db.cachedAppDao().byPackage("com.example.beta"))         assertNotNull(db.cachedAppDao().byPackage("com.example.other"))     } +    @Test+    fun `only developer-signed apps are imported from fdroid`() = runTest {+        // Index-fixture entries at import level: "devsigned" carries an+        // allowed developer key matching its version signer in the signed+        // index-v1; "fdroidsigned" has no allowed key, so f-droid.org signed+        // it with its own per-app key and it must never reach the catalogue.+        serveIndex(+            indexWith(+                pkg("devsigned", "devsigned_1.apk"),+                pkg("fdroidsigned", "fdroidsigned_1.apk"),+            ),+            allowedNames = setOf("devsigned"),+        )+        assertEquals(1, provider.syncIntoDb())+        assertNotNull(db.cachedAppDao().byPackage("com.example.devsigned"))+        assertEquals(null, db.cachedAppDao().byPackage("com.example.fdroidsigned"))+    }++    @Test+    fun `a later fdroid sync evicts rows the developer-signing gate now drops`() = runTest {+        serveIndex(indexWith(pkg("alpha", "alpha_1.apk")), allowedNames = setOf("alpha"))+        provider.syncIntoDb()+        assertNotNull(db.cachedAppDao().byPackage("com.example.alpha"))+        // Same package still in index-v2, but the signed index-v1 no longer+        // allows its key; with another admitted app present, the row+        // replacement evicts it.+        serveIndex(+            indexWith(pkg("alpha", "alpha_1.apk"), pkg("beta", "beta_1.apk")),+            allowedNames = setOf("beta"),+        )+        assertEquals(1, provider.syncIntoDb())+        assertEquals(null, db.cachedAppDao().byPackage("com.example.alpha"))+        assertNotNull(db.cachedAppDao().byPackage("com.example.beta"))+    }+     @Test     fun `a verified but empty index keeps the cached rows`() = runTest {         provider.syncIntoDb()