a427cecb9d26

wip: make issuer history transactions atomic (v2.17.46)

time
2026-11-22 02:14 UTC · 5 days ago
machine
Junes-MacBook-Pro.local
agent
gpt-6
session
remediate interim audit findings
parent
503ffc08ccfd
8 files VERSION+1 −1app/src/main/java/com/peachpasswords/sync/DeviceManifestSupport.kt+29 −2app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+190 −67app/src/main/java/com/peachpasswords/sync/SyncGenerationStore.kt+38 −18app/src/main/java/com/peachpasswords/sync/VaultSyncAdapter.kt+21 −7app/src/test/java/com/peachpasswords/sync/PairedDeviceStoreConcurrencyTest.kt+61 −0app/src/test/java/com/peachpasswords/sync/RegistryTransactionTest.kt+412 −0app/src/test/java/com/peachpasswords/sync/VaultSyncAdapterTest.kt+151 −1
VERSION+1 −1
@@ -1 +1 @@1-2.17.431+2.17.46

view file

app/src/main/java/com/peachpasswords/sync/DeviceManifestSupport.kt+29 −2
@@ -17,8 +17,8 @@1717  * bounded revocation list, and string fields long enough for any honest use.1818  */1919 private const val MAX_MANIFEST_DEVICES = 25620-private const val MAX_MANIFEST_REVOCATIONS = 50021-private const val MAX_MANIFEST_STRING = 25620+internal const val MAX_MANIFEST_REVOCATIONS = 50021+internal const val MAX_MANIFEST_STRING = 2562222 /**2323  * Display/storage bound for device names, matching the browser's2424  * MAX_DEVICE_NAME_CHARS (shared/sync-limits.ts) and both platforms' local@@ -33,6 +33,12 @@3333     if (name.length > MAX_DEVICE_NAME_CHARS) name.take(MAX_DEVICE_NAME_CHARS) else name3434 internal const val NO_KEY_SENTINEL = "0000000000000000000000000000000000000000000000000000000000000000"3535 36+data class DeviceManifestIssuerBinding(37+    val deviceId: String,38+    val longTermPublicKeyHex: String,39+    val signingPublicKeyHex: String,40+)41+3642 /**3743  * Fully staged membership change. Implementations must linearize the whole3844  * batch; callers hold the vault session epoch fence while invoking it, so a@@ -42,8 +48,17 @@4248     val incomingRevocations: List<DeviceRevocation>,4349     val removals: Set<String>,4450     val upserts: List<PairedDevice>,51+    val issuerSigningKeys: Map<String, Set<String>> = emptyMap(),52+    val authenticatedIssuer: DeviceManifestIssuerBinding,53+    val expectedSnapshot: DeviceManifestRegistrySnapshot,4554 )4655 56+data class DeviceManifestRegistrySnapshot(57+    val devices: List<PairedDevice>,58+    val revocations: List<DeviceRevocation>,59+    val issuerSigningKeys: Map<String, Set<String>>,60+)61+4762 interface PairedDeviceRegistry {4863     fun getAll(): List<PairedDevice>4964     fun get(id: String): PairedDevice?@@ -61,6 +76,18 @@6176      */6277     fun issuerSigningKeys(issuerDeviceId: String): Set<String> = emptySet()6378     fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean = true79+80+    /** Production stores capture all fields atomically; the fallback uses existing reads. */81+    fun manifestSnapshot(requestedIssuerIds: Set<String>): DeviceManifestRegistrySnapshot {82+        val devices = getAll()83+        val revocations = listRevocations()84+        val issuers = requestedIssuerIds + devices.map { it.deviceId } + revocations.map { it.revokedByDeviceId }85+        return DeviceManifestRegistrySnapshot(86+            devices,87+            revocations,88+            issuers.associateWith { issuerSigningKeys(it).toSet() },89+        )90+    }6491 6592     /** Commit a complete staged manifest as one logical registry mutation. */6693     fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean

view file

app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+190 −67
@@ -1,6 +1,7 @@11 package com.peachpasswords.sync22 33 import android.content.Context4+import android.content.SharedPreferences45 import androidx.security.crypto.EncryptedSharedPreferences56 import androidx.security.crypto.MasterKey67 import dagger.hilt.android.qualifiers.ApplicationContext@@ -39,19 +40,17 @@3940  *    no-op-friendly hook so callers from the brief compile; see integration note.4041  */4142 @Singleton42-class PairedDeviceStore @Inject constructor(43-    @ApplicationContext context: Context,43+class PairedDeviceStore internal constructor(44+    private val prefs: SharedPreferences,4445 ) : PairedDeviceRegistry {45-    private val masterKey = MasterKey.Builder(context)46-        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)47-        .build()48-49-    private val prefs = EncryptedSharedPreferences.create(50-        context,51-        PREFS_FILE,52-        masterKey,53-        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,54-        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,46+    @Inject constructor(@ApplicationContext context: Context) : this(47+        EncryptedSharedPreferences.create(48+            context,49+            PREFS_FILE,50+            MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),51+            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,52+            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,53+        ),5554     )5655 5756     private val listSerializer = ListSerializer(PairedDevice.serializer())@@ -61,8 +60,12 @@6160     /** Set by [revoke]; see [protectedRevocationIssuers]. */6261     @Volatile private var knownLocalDeviceId: String? = null6362 64-    override fun getAll(): List<PairedDevice> {65-        val raw = prefs.getString(KEY_DEVICES, null) ?: return emptyList()63+    override fun getAll(): List<PairedDevice> = mutationGate.withLock {64+        decodeDevices(readStringPreference(KEY_DEVICES))65+    }66+67+    private fun decodeDevices(raw: String?): List<PairedDevice> {68+        if (raw == null) return emptyList()6669         return try {6770             json.decodeFromString(listSerializer, raw)6871         } catch (e: Exception) {@@ -70,6 +73,23 @@7073         }7174     }7275 76+    override fun manifestSnapshot(requestedIssuerIds: Set<String>): DeviceManifestRegistrySnapshot = mutationGate.withLock {77+        manifestSnapshot(readPrefsState())78+    }79+80+    private fun manifestSnapshot(state: RegistryPrefsState): DeviceManifestRegistrySnapshot =81+        DeviceManifestRegistrySnapshot(82+            devices = decodeDevices(state.devices),83+            revocations = decodeRevocations(state.revocations),84+            issuerSigningKeys = state.issuerKeys.mapValues { (_, keys) -> keys.map(String::lowercase).toSet() },85+        )86+87+    private fun readStringPreference(key: String): String? = try {88+        prefs.getString(key, null)89+    } catch (e: ClassCastException) {90+        throw TrustDataCorruptedException(key, "invalid_string")91+    }92+7393     override fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }7494 7595     override fun getByPubkey(pubkeyHex: String): PairedDevice? =@@ -77,8 +97,9 @@7797             it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true7898         }7999 80-    fun hasIdentityCollision(device: PairedDevice): Boolean =100+    fun hasIdentityCollision(device: PairedDevice): Boolean = mutationGate.withLock {81101         hasAdoptionIdentityConflict(device, getAll(), listRevocations())102+    }82103 83104     /** Insert or replace a directly re-paired device and clear its terminal revocation atomically. */84105     fun upsertAndClearRevocation(device: PairedDevice) {@@ -93,11 +114,12 @@93114             val nextDevices = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice94115             val currentRevocations = listRevocations()95116             val nextRevocations = currentRevocations.filterNot { it.deviceId == device.deviceId }96-            val nextPrefs = RegistryPrefsState(117+            val priorPrefs = readPrefsState()118+            val nextPrefs = priorPrefs.copy(97119                 devices = json.encodeToString(listSerializer, nextDevices),98120                 revocations = json.encodeToString(revocationSerializer, nextRevocations),99121             )100-            check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {122+            check(commitPrefsState(priorPrefs, nextPrefs)) {101123                 "paired_device_persist_failed"102124             }103125         }@@ -122,21 +144,51 @@122144 123145     /**124146      * Commit a staged manifest in one synchronous SharedPreferences transaction.125-     * `apply()` is appropriate for ordinary UI writes, but it would expose each126-     * per-device edit independently to observers and could leave an old-session127-     * manifest half-applied across a lock. `commit()` updates both keys together128-     * in memory and does not return until the durable write has completed.147+     * Per-device edits could leave an old-session manifest half-applied across148+     * a lock. `commit()` updates registry, ledger and history together in memory149+     * and does not return until the durable write has completed.129150      */130151     override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {131152         return mutationGate.withLock {132153             val priorPrefs = readPrefsState()133-            val currentDevices = getAll()154+            val currentSnapshot = manifestSnapshot(priorPrefs)155+            if (!sameTrustSnapshot(currentSnapshot, batch.expectedSnapshot)) return@withLock false156+            val currentDevices = currentSnapshot.devices134157             val currentById = currentDevices.associateBy { it.deviceId }135-            val currentRevocations = listRevocations()158+            val currentRevocations = currentSnapshot.revocations159+            val admissionRevocations = currentRevocations + batch.incomingRevocations160+            val revokedIds = admissionRevocations.map { it.deviceId }.toSet()161+            val revokedKeys = admissionRevocations.map { it.longTermPublicKeyHex.lowercase() }162+                .filterNot { it == NO_KEY_SENTINEL }.toSet()163+            fun isTerminal(deviceId: String, longTermKey: String?): Boolean =164+                deviceId in revokedIds || longTermKey?.lowercase() in revokedKeys165+166+            val expectedIssuer = batch.authenticatedIssuer167+            val issuer = currentById[expectedIssuer.deviceId] ?: return@withLock false168+            // Incoming records may revoke their still-authorized forwarder.169+            val issuerAlreadyRevoked = currentRevocations.any {170+                it.deviceId == issuer.deviceId ||171+                    (it.longTermPublicKeyHex.lowercase() != NO_KEY_SENTINEL &&172+                        it.longTermPublicKeyHex.equals(issuer.longTermPublicKeyHex, ignoreCase = true))173+            }174+            if (issuer.longTermPublicKeyHex?.let { CryptoCompare.hex(it, expectedIssuer.longTermPublicKeyHex) } != true ||175+                issuer.signingPublicKeyHex?.let { CryptoCompare.hex(it, expectedIssuer.signingPublicKeyHex) } != true ||176+                (issuer.trustSource != "direct" && issuer.trustSource != "vouched") ||177+                issuer.vouchDepth >= MAX_VOUCH_DEPTH || issuerAlreadyRevoked178+            ) return@withLock false179+            val allowedIssuerKeys = priorPrefs.issuerKeys[issuer.deviceId].orEmpty().map(String::lowercase).toSet() +180+                expectedIssuer.signingPublicKeyHex.lowercase()181+            if (batch.issuerSigningKeys.any { (id, keys) ->182+                id != issuer.deviceId || keys.any { !isSigningKey(it) || it.lowercase() !in allowedIssuerKeys }183+            }) return@withLock false184+            if (batch.upserts.any {185+                isTerminal(it.deviceId, it.longTermPublicKeyHex ?: currentById[it.deviceId]?.longTermPublicKeyHex)186+            }) return@withLock false187+136188             val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records137189             val removed = batch.removals138190             val nextDevices = currentDevices139-                .filterNot { removed.contains(it.deviceId) }191+                .filterNot { removed.contains(it.deviceId) || isTerminal(it.deviceId, it.longTermPublicKeyHex) }140192                 .toMutableList()141193             batch.upserts.forEach { incoming ->142194                 val existing = currentById[incoming.deviceId]@@ -147,23 +199,26 @@147199                             (candidate.signingPublicKeyHex != null && incoming.signingPublicKeyHex != null && CryptoCompare.hex(candidate.signingPublicKeyHex, incoming.signingPublicKeyHex)))148200                 }) { "device_identity_collision" }149201                 val bound = bindImmutableIdentity(existing, incoming)150-                val alias = nextDevices.firstOrNull { it.deviceId == incoming.deviceId }?.localAlias202+                val alias = existing?.localAlias151203                 val device = bound.copy(152204                     deviceName = bound.deviceName?.let(::capDeviceName),153205                     localAlias = alias,206+                    lastSyncedAt = if (existing != null) existing.lastSyncedAt else bound.lastSyncedAt,207+                    lastKnownIp = if (existing != null) existing.lastKnownIp else bound.lastKnownIp,154208                 )155209                 nextDevices.removeAll { it.deviceId == device.deviceId }156210                 nextDevices += device157211             }158212 159-            val nextPrefs = RegistryPrefsState(213+            val nextPrefs = priorPrefs.copy(160214                 devices = json.encodeToString(listSerializer, nextDevices),161215                 revocations = json.encodeToString(revocationSerializer, nextRevocations),216+                issuerKeys = withIssuerSigningKeys(priorPrefs.issuerKeys, batch.issuerSigningKeys),162217             )163218             // Explicitly restore the old encrypted-preference values when commit()164219             // reports false. The platform usually keeps them in memory, but a real165220             // store failure must not rely on that undocumented outcome.166-            commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)221+            commitPrefsState(priorPrefs, nextPrefs)167222         }168223     }169224 @@ -183,8 +238,12 @@183238 184239     // ── Device revocation (Part 5 §C) ────────────────────────────────────────185240 186-    override fun listRevocations(): List<DeviceRevocation> {187-        val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()241+    override fun listRevocations(): List<DeviceRevocation> = mutationGate.withLock {242+        decodeRevocations(readStringPreference(KEY_REVOCATIONS))243+    }244+245+    private fun decodeRevocations(raw: String?): List<DeviceRevocation> {246+        if (raw == null) return emptyList()188247         return try {189248             json.decodeFromString(revocationSerializer, raw)190249         } catch (e: Exception) {@@ -218,11 +277,12 @@218277         // can land separately, and a device removed without its revocation219278         // record stops being blocked from re-admission — a silent failure of the220279         // ejection path rather than a visible error.221-        val nextPrefs = RegistryPrefsState(280+        val priorPrefs = readPrefsState()281+        val nextPrefs = priorPrefs.copy(222282             devices = json.encodeToString(listSerializer, mutation.devices),223283             revocations = json.encodeToString(revocationSerializer, mutation.revocations),224284         )225-        check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {285+        check(commitPrefsState(priorPrefs, nextPrefs)) {226286             "paired_device_persist_failed"227287         }228288         mutation.added@@ -272,21 +332,22 @@272332 273333     fun clear() {274334         mutationGate.withLock {275-            val edit = prefs.edit()276-                .remove(KEY_DEVICES)277-                .remove(KEY_REVOCATIONS)278-            // Known-key history is trust state: leaving it behind would keep a279-            // cleared installation admitting keys it no longer holds devices280-            // for, so it goes with the rest of the registry.281-            for (key in prefs.all.keys.filter { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }) {282-                edit.remove(key)283-            }284-            edit.commit()335+            val prior = copyRawTrustPreferences(prefs.all)336+            val removed = prior.keys.filter { it == KEY_DEVICES || it == KEY_REVOCATIONS || it.startsWith(KEY_ISSUER_KEYS_PREFIX) }.toSet()337+            val next = prior.filterKeys { it !in removed }338+            check(commitWithRollback(prior, next) { state ->339+                val edit = prefs.edit()340+                removed.forEach(edit::remove)341+                putRawTrustPreferences(edit, state.filterKeys { it in removed })342+                edit.commit()343+            }) { "paired_device_persist_failed" }285344         }286345     }287346 288347     /** Verbatim logical copy of the whole registry, for the secure-reset archive. */289-    internal fun snapshot(): Map<String, Any?> = prefs.all348+    internal fun snapshot(): Map<String, Any?> = mutationGate.withLock {349+        copyRawTrustPreferences(prefs.all)350+    }290351 291352     /**292353      * Refresh the device's `lastKnownIp` (the closest real analogue to the@@ -335,22 +396,25 @@335396         awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }336397     }337398 338-    override fun issuerSigningKeys(issuerDeviceId: String): Set<String> =339-        prefs.getStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", emptySet())340-            .orEmpty().map(String::lowercase).toSet()399+    override fun issuerSigningKeys(issuerDeviceId: String): Set<String> = mutationGate.withLock {400+        readPrefsState().issuerKeys[issuerDeviceId].orEmpty().map(String::lowercase).toSet()401+    }341402 342403     /** Any known-key history at all: legacy trust state for the reset probe. */343-    fun hasIssuerSigningKeys(): Boolean = prefs.all.keys.any { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }404+    fun hasIssuerSigningKeys(): Boolean = mutationGate.withLock {405+        readPrefsState().issuerKeys.isNotEmpty()406+    }344407 345408     override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {346-        val key = signingKeyHex.lowercase()347-        if (issuerDeviceId.isBlank() || key.length != 64) return false348-        synchronized(mutationGate) {349-            val existing = issuerSigningKeys(issuerDeviceId)350-            if (key in existing) return true351-            return prefs.edit()352-                .putStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", existing + key)353-                .commit()409+        if (issuerDeviceId.isBlank() || !isSigningKey(signingKeyHex)) return false410+        return mutationGate.withLock {411+            val prior = readPrefsState()412+            val key = signingKeyHex.lowercase()413+            if (prior.issuerKeys[issuerDeviceId].orEmpty().any { it.equals(key, ignoreCase = true) }) {414+                return@withLock true415+            }416+            val next = prior.copy(issuerKeys = withIssuerSigningKeys(prior.issuerKeys, mapOf(issuerDeviceId to setOf(key))))417+            commitPrefsState(prior, next)354418         }355419     }356420 @@ -364,32 +428,91 @@364428         val next = prior.copy(365429             revocations = json.encodeToString(revocationSerializer, records),366430         )367-        check(commitWithRollback(prior, next, ::writePrefsState)) {431+        check(commitPrefsState(prior, next)) {368432             "paired_device_persist_failed"369433         }370434     }371435 372436     private fun persist(devices: List<PairedDevice>) {373-        prefs.edit()374-            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))375-            .apply()437+        prefs.edit().putString(KEY_DEVICES, json.encodeToString(listSerializer, devices)).apply()376438     }377439 440+    private fun sameTrustSnapshot(441+        current: DeviceManifestRegistrySnapshot,442+        expected: DeviceManifestRegistrySnapshot,443+    ): Boolean {444+        fun deviceCounts(devices: List<PairedDevice>) = devices.map {445+            it.copy(lastSyncedAt = null, lastKnownIp = null, localAlias = null)446+        }.groupingBy { it }.eachCount()447+        return deviceCounts(current.devices) == deviceCounts(expected.devices) &&448+            current.revocations == expected.revocations && current.issuerSigningKeys == expected.issuerSigningKeys449+    }450+378451     private data class RegistryPrefsState(379452         val devices: String?,380453         val revocations: String?,454+        val issuerKeys: Map<String, Set<String>>,381455     )382456 383-    private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(384-        devices = prefs.getString(KEY_DEVICES, null),385-        revocations = prefs.getString(KEY_REVOCATIONS, null),386-    )457+    private fun readPrefsState(): RegistryPrefsState {458+        val all = prefs.all459+        val issuerKeys = all.filterKeys { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }.map { (key, value) ->460+            val issuer = key.removePrefix(KEY_ISSUER_KEYS_PREFIX)461+            if (issuer.isBlank() || value !is Set<*> || value.any { it !is String || !isSigningKey(it) }) {462+                throw TrustDataCorruptedException(key, "invalid_issuer_signing_keys")463+            }464+            issuer to value.map { it as String }.toSet()465+        }.toMap()466+        return RegistryPrefsState(467+            devices = snapshotString(all, KEY_DEVICES),468+            revocations = snapshotString(all, KEY_REVOCATIONS),469+            issuerKeys = issuerKeys,470+        )471+    }387472 388-    private fun writePrefsState(state: RegistryPrefsState): Boolean {389-        val edit = prefs.edit()390-        if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)391-        if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)392-        return edit.commit()473+    private fun snapshotString(all: Map<String, *>, key: String): String? {474+        val value = all[key]475+        if (value == null && !all.containsKey(key)) return null476+        if (value !is String) throw TrustDataCorruptedException(key, "invalid_string")477+        return value478+    }479+480+    private fun withIssuerSigningKeys(481+        existing: Map<String, Set<String>>,482+        incoming: Map<String, Set<String>>,483+    ): Map<String, Set<String>> {484+        val next = existing.toMutableMap()485+        incoming.forEach { (issuer, keys) ->486+            require(issuer.isNotBlank() && keys.all(::isSigningKey)) { "invalid_issuer_signing_keys" }487+            val prior = next[issuer].orEmpty()488+            val known = prior.map(String::lowercase).toSet()489+            next[issuer] = prior + keys.map(String::lowercase).filterNot { it in known }490+        }491+        return next.toMap()492+    }493+494+    private fun isSigningKey(key: String): Boolean =495+        key.length == 64 && key.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }496+497+    private fun commitPrefsState(prior: RegistryPrefsState, next: RegistryPrefsState): Boolean {498+        val changedIssuers = (prior.issuerKeys.keys + next.issuerKeys.keys).filter {499+            prior.issuerKeys[it] != next.issuerKeys[it]500+        }501+        return commitWithRollback(prior, next) { state ->502+            val edit = prefs.edit()503+            if (prior.devices != next.devices) {504+                if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)505+            }506+            if (prior.revocations != next.revocations) {507+                if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)508+            }509+            changedIssuers.forEach { issuer ->510+                val key = "$KEY_ISSUER_KEYS_PREFIX$issuer"511+                val keys = state.issuerKeys[issuer]512+                if (keys == null) edit.remove(key) else edit.putStringSet(key, keys.toSet())513+            }514+            edit.commit()515+        }393516     }394517 395518     private companion object {

view file

app/src/main/java/com/peachpasswords/sync/SyncGenerationStore.kt+38 −18
@@ -64,27 +64,10 @@6464             for ((key, value) in devices.snapshot()) put("$prefix$ARCHIVE_DEVICES_PREFIX$key", value)6565             for ((key, value) in pendingDevices.snapshot()) put("$prefix$ARCHIVE_PENDING_PREFIX$key", value)6666         }67-        val edit = archive.edit()68-        for ((key, value) in expected) {69-            when (value) {70-                is String -> edit.putString(key, value)71-                is Set<*> -> edit.putStringSet(key, value.filterIsInstance<String>().toSet())72-            }73-        }74-        check(edit.commit()) { "generation_archive_persist_failed" }75-        check(expected.all { (key, value) -> archiveMatches(archive, key, value) }) {76-            "generation_archive_verify_failed"77-        }67+        check(archiveTrustPreferenceValues(archive, expected)) { "generation_archive_persist_failed" }7868         ARCHIVE_PREFS_FILE7969     }.getOrNull()8070 81-    private fun archiveMatches(archive: SharedPreferences, key: String, expected: Any?): Boolean =82-        when (expected) {83-            is String -> archive.getString(key, null) == expected84-            is Set<*> -> archive.getStringSet(key, null) == expected.filterIsInstance<String>().toSet()85-            else -> false86-        }87-8871     override fun clearLegacyTrustState(): Boolean = runCatching {8972         PeachSyncService.stop(context)9073         lockedSyncSpool.clear()@@ -151,3 +134,40 @@151134         EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,152135         EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,153136     )137+138+internal fun copyRawTrustPreferences(values: Map<String, *>): Map<String, Any> = values.mapValues { (key, value) ->139+    when (value) {140+        is String, is Int, is Long, is Float, is Boolean -> value141+        is Set<*> -> value.map { item ->142+            require(item is String) { "unsupported_trust_preference:$key" }143+            item144+        }.toSet()145+        else -> throw IllegalArgumentException("unsupported_trust_preference:$key")146+    }147+}148+149+internal fun putRawTrustPreferences(edit: SharedPreferences.Editor, values: Map<String, Any>) {150+    values.forEach { (key, value) ->151+        when (value) {152+            is String -> edit.putString(key, value)153+            is Int -> edit.putInt(key, value)154+            is Long -> edit.putLong(key, value)155+            is Float -> edit.putFloat(key, value)156+            is Boolean -> edit.putBoolean(key, value)157+            is Set<*> -> edit.putStringSet(key, value.map { item ->158+                require(item is String) { "unsupported_trust_preference:$key" }159+                item160+            }.toSet())161+            else -> throw IllegalArgumentException("unsupported_trust_preference:$key")162+        }163+    }164+}165+166+internal fun archiveTrustPreferenceValues(archive: SharedPreferences, expected: Map<String, Any?>): Boolean {167+    val raw = copyRawTrustPreferences(expected)168+    val edit = archive.edit()169+    putRawTrustPreferences(edit, raw)170+    if (!edit.commit()) return false171+    val actual = archive.all172+    return raw.all { (key, value) -> actual[key] == value }173+}

view file

app/src/main/java/com/peachpasswords/sync/VaultSyncAdapter.kt+21 −7
@@ -155,12 +155,20 @@155155         val registry = pairedDevices ?: return156156         val pending = pendingVouched ?: return157157         if (authenticatedRemoteStaticPublicKey.size != 32) return158-        val issuer = registry.getByPubkey(pubkeyToHex(authenticatedRemoteStaticPublicKey)) ?: return158+        if (manifest.body.revoked.size > MAX_MANIFEST_REVOCATIONS ||159+            manifest.body.revoked.any { it.revokedByDeviceId.length > MAX_MANIFEST_STRING }160+        ) return161+        val registrySnapshot = registry.manifestSnapshot(manifest.body.revoked.map { it.revokedByDeviceId }.toSet())162+        val currentById = registrySnapshot.devices.associateBy { it.deviceId }163+        val remoteStatic = pubkeyToHex(authenticatedRemoteStaticPublicKey)164+        val issuer = registrySnapshot.devices.firstOrNull {165+            it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, remoteStatic) } == true166+        } ?: return159167         // Direct and bounded-vouch issuers may propagate the signed device pool.160168         if (issuer.trustSource != "direct" && issuer.trustSource != "vouched") return161169         if (issuer.vouchDepth >= MAX_VOUCH_DEPTH) return162170         val currentSigningKey = issuer.signingPublicKeyHex?.lowercase()?.takeIf { it.length == 64 } ?: return163-        val knownIssuerKeys = registry.issuerSigningKeys(issuer.deviceId) + currentSigningKey171+        val knownIssuerKeys = registrySnapshot.issuerSigningKeys[issuer.deviceId].orEmpty() + currentSigningKey164172         // Historical keys and the persisted current key remain valid; mutable165173         // device metadata never rewrites the issuer's key history.166174         //@@ -168,8 +176,8 @@168176         // active row is gone — so resolve that issuer's key from the registry169177         // and its immutable history rather than from the record itself.170178         val resolveIssuerSigningKeys: (String) -> Set<String> = { deviceId ->171-            val history = registry.issuerSigningKeys(deviceId)172-            val current = registry.get(deviceId)?.signingPublicKeyHex?.lowercase()179+            val history = registrySnapshot.issuerSigningKeys[deviceId].orEmpty()180+            val current = currentById[deviceId]?.signingPublicKeyHex?.lowercase()173181             if (current != null && current.length == 64) history + current else history174182         }175183         val verified = knownIssuerKeys.firstNotNullOfOrNull { candidate ->@@ -191,7 +199,7 @@191199             // a per-item epoch check would still leave a prefix behind if lock()192200             // wins between two items.193201             val incomingRevocations = body.revoked.filterNot { it.deviceId == ourDeviceId }194-            val currentRevocations = registry.listRevocations()202+            val currentRevocations = registrySnapshot.revocations195203             val knownRevokedIds = currentRevocations.map { it.deviceId }.toSet()196204             val newlyRevoked = incomingRevocations.filterNot { knownRevokedIds.contains(it.deviceId) }197205             val revokedIds = (knownRevokedIds + incomingRevocations.map { it.deviceId }).toSet()@@ -221,7 +229,7 @@221229                     continue222230                 }223231                 if (entry.vouchDepth > issuer.vouchDepth + 1) continue224-                val existing = stagedUpserts[entry.deviceId] ?: registry.get(entry.deviceId)232+                val existing = stagedUpserts[entry.deviceId] ?: currentById[entry.deviceId]225233                 val meshRoute = deriveManifestMeshRoute(localKeys.secretKey, localKeys.publicKey, entry)226234                 if (existing == null) {227235                     if (meshRoute == null) continue@@ -290,6 +298,13 @@290298                 incomingRevocations = incomingRevocations,291299                 removals = newlyRevoked.map { it.deviceId }.toSet(),292300                 upserts = stagedUpserts.values.toList(),301+                issuerSigningKeys = mapOf(issuer.deviceId to setOf(signingKey)),302+                expectedSnapshot = registrySnapshot,303+                authenticatedIssuer = DeviceManifestIssuerBinding(304+                    issuer.deviceId,305+                    issuer.longTermPublicKeyHex ?: return,306+                    currentSigningKey,307+                ),293308             )294309             // Remove any matching pending introductions synchronously BEFORE295310             // installing trust. If the registry commit fails, restoring this@@ -298,7 +313,6 @@298313             val pendingIds = batch.removals + stagedUpserts.keys299314             val priorPending = pending.getAll().filter { it.deviceId in pendingIds }300315             val committed = repo.withSessionEpochCommit(snapshot.epoch) {301-                if (!registry.appendIssuerSigningKey(issuer.deviceId, signingKey)) return@withSessionEpochCommit false302316                 val pendingRemoved = runCatching { pending.removeBatch(pendingIds) }.getOrDefault(false)303317                 if (!pendingRemoved) {304318                     pending.restoreBatch(priorPending)

view file

app/src/test/java/com/peachpasswords/sync/PairedDeviceStoreConcurrencyTest.kt+61 −0
@@ -44,4 +44,65 @@4444 4545         assertEquals(setOf("firefox-synced", "chrome"), devices.toSet())4646     }47+48+    @Test49+    fun `history append serializes registry clear and snapshot`() {50+        val prefs = RegistryTestPreferences()51+        val store = PairedDeviceStore(prefs)52+        val appendWriting = CountDownLatch(1)53+        val releaseAppend = CountDownLatch(1)54+        val clearStarted = CountDownLatch(1)55+        val clearWriting = CountDownLatch(1)56+        val snapshotStarted = CountDownLatch(1)57+        val snapshotReturned = CountDownLatch(1)58+        val failure = java.util.concurrent.atomic.AtomicReference<Throwable?>()59+        prefs.beforeCommit = {60+            if (Thread.currentThread().name == "history-append") {61+                appendWriting.countDown()62+                check(releaseAppend.await(5, TimeUnit.SECONDS))63+            } else {64+                clearWriting.countDown()65+            }66+        }67+        val append = thread(name = "history-append") {68+            runCatching { check(store.appendIssuerSigningKey("issuer", "ab".repeat(32))) }69+                .onFailure { failure.set(it) }70+        }71+        assertTrue(appendWriting.await(5, TimeUnit.SECONDS))72+        val clear = thread {73+            clearStarted.countDown()74+            runCatching { store.clear() }.onFailure { failure.set(it) }75+        }76+        val snapshot = thread {77+            snapshotStarted.countDown()78+            runCatching { store.snapshot() }.onFailure { failure.set(it) }79+            snapshotReturned.countDown()80+        }81+        try {82+            assertTrue(clearStarted.await(5, TimeUnit.SECONDS))83+            assertTrue(snapshotStarted.await(5, TimeUnit.SECONDS))84+            fun awaitRegistryGate(worker: Thread) {85+                val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)86+                while (worker.isAlive && System.nanoTime() < deadline &&87+                    (worker.state != Thread.State.WAITING || worker.stackTrace.none {88+                        it.className == RegistryMutationGate::class.java.name89+                    })90+                ) Thread.yield()91+                assertEquals(Thread.State.WAITING, worker.state)92+                assertTrue(worker.stackTrace.any { it.className == RegistryMutationGate::class.java.name })93+            }94+            awaitRegistryGate(clear)95+            awaitRegistryGate(snapshot)96+            assertEquals(1L, clearWriting.count)97+            assertEquals(1L, snapshotReturned.count)98+        } finally {99+            releaseAppend.countDown()100+            append.join(5_000)101+            clear.join(5_000)102+            snapshot.join(5_000)103+        }104+        failure.get()?.let { throw AssertionError(it) }105+        assertTrue(prefs.values.isEmpty())106+    }107+47108 }

view file

app/src/test/java/com/peachpasswords/sync/RegistryTransactionTest.kt+412 −0
@@ -4,6 +4,8 @@44 import org.junit.Assert.assertFalse55 import org.junit.Assert.assertTrue66 import org.junit.Test7+import kotlinx.serialization.builtins.ListSerializer8+import kotlinx.serialization.json.Json79 810 /** Pure failure-injection coverage for the real SharedPreferences transaction helper. */911 class RegistryTransactionTest {@@ -38,4 +40,414 @@3840         assertEquals("next", state)3941         assertEquals(listOf("next"), writes)4042     }43+}44+45+internal class RegistryTestPreferences : android.content.SharedPreferences {46+    val values = linkedMapOf<String, Any?>()47+    var failNextCommit = false48+    var allReads = 049+    var stringReads = 050+    val historyPuts = mutableListOf<String>()51+    val historyRemovals = mutableListOf<String>()52+    var beforeCommit: (() -> Unit)? = null53+    override fun getAll(): Map<String, *> { allReads++; return values.toMap() }54+    override fun getString(key: String, defValue: String?): String? { stringReads++; return values[key]?.let { it as String } ?: defValue }55+    override fun getStringSet(key: String, defValues: MutableSet<String>?): MutableSet<String>? {56+        val value = values[key] ?: return defValues57+        require(value is Set<*>)58+        return value.map { requireNotNull(it as? String) }.toMutableSet()59+    }60+    override fun getInt(key: String, defValue: Int) = values[key] as? Int ?: defValue61+    override fun getLong(key: String, defValue: Long) = values[key] as? Long ?: defValue62+    override fun getFloat(key: String, defValue: Float) = values[key] as? Float ?: defValue63+    override fun getBoolean(key: String, defValue: Boolean) = values[key] as? Boolean ?: defValue64+    override fun contains(key: String) = values.containsKey(key)65+    override fun registerOnSharedPreferenceChangeListener(listener: android.content.SharedPreferences.OnSharedPreferenceChangeListener) = Unit66+    override fun unregisterOnSharedPreferenceChangeListener(listener: android.content.SharedPreferences.OnSharedPreferenceChangeListener) = Unit67+    override fun edit(): android.content.SharedPreferences.Editor = object : android.content.SharedPreferences.Editor {68+        private val writes = linkedMapOf<String, Any?>()69+        private var clearAll = false70+        override fun putString(key: String, value: String?) = apply { writes[key] = value }71+        override fun putStringSet(key: String, value: MutableSet<String>?) = apply {72+            if (key.startsWith("issuer_signing_keys:")) historyPuts += key73+            writes[key] = value?.toMutableSet()74+        }75+        override fun putInt(key: String, value: Int) = apply { writes[key] = value }76+        override fun putLong(key: String, value: Long) = apply { writes[key] = value }77+        override fun putFloat(key: String, value: Float) = apply { writes[key] = value }78+        override fun putBoolean(key: String, value: Boolean) = apply { writes[key] = value }79+        override fun remove(key: String) = apply {80+            if (key.startsWith("issuer_signing_keys:")) historyRemovals += key81+            writes[key] = null82+        }83+        override fun clear() = apply { clearAll = true }84+        override fun commit(): Boolean {85+            beforeCommit?.invoke()86+            if (clearAll) values.clear()87+            writes.forEach { (key, value) -> if (value == null) values.remove(key) else values[key] = value }88+            if (failNextCommit) {89+                failNextCommit = false90+                return false91+            }92+            return true93+        }94+        override fun apply() { commit() }95+    }96+}97+98+class RegistryIssuerTransactionTest {99+    private val keyA = "ab".repeat(32)100+    private val keyB = "cd".repeat(32)101+    private val keyC = "ef".repeat(32)102+    private val issuer = PairedDevice(103+        "source", longTermPublicKeyHex = "11".repeat(32), signingPublicKeyHex = "22".repeat(32),104+        trustSource = "direct", pairedAt = 1L,105+    )106+    private fun seededPreferences() = RegistryTestPreferences().also {107+        it.values["paired_devices"] = Json.encodeToString(ListSerializer(PairedDevice.serializer()), listOf(issuer))108+    }109+    private fun batch(store: PairedDeviceStore) = DeviceManifestRegistryBatch(110+        emptyList(), emptySet(), emptyList(), mapOf(issuer.deviceId to setOf(requireNotNull(issuer.signingPublicKeyHex))),111+        DeviceManifestIssuerBinding(issuer.deviceId, requireNotNull(issuer.longTermPublicKeyHex), requireNotNull(issuer.signingPublicKeyHex)),112+        store.manifestSnapshot(emptySet()),113+    )114+115+    @Test fun manifest_commit_retains_complete_history_in_one_transaction() {116+        val prefs = seededPreferences()117+        prefs.values["issuer_signing_keys:old"] = mutableSetOf(keyA.uppercase(), keyB)118+        val store = PairedDeviceStore(prefs)119+        assertTrue(store.applyManifestBatch(batch(store)))120+        assertEquals(setOf(keyA, keyB), store.issuerSigningKeys("old"))121+        assertEquals(setOf(issuer.signingPublicKeyHex), store.issuerSigningKeys(issuer.deviceId))122+        assertEquals(listOf(issuer), store.getAll())123+        assertEquals(null, store.getByPubkey(keyA))124+    }125+126+    @Test fun failed_manifest_restores_all_history_and_removes_new_sets() {127+        val prefs = seededPreferences()128+        prefs.values["device_revocations"] = "[]"129+        prefs.values["issuer_signing_keys:old"] = mutableSetOf(keyA.uppercase(), keyB)130+        val before = prefs.values.toMap()131+        val store = PairedDeviceStore(prefs)132+        prefs.failNextCommit = true133+        assertFalse(store.applyManifestBatch(batch(store)))134+        assertEquals(before, prefs.values)135+    }136+137+    @Test fun append_refuses_invalid_input_without_touching_preferences() {138+        val prefs = RegistryTestPreferences()139+        val store = PairedDeviceStore(prefs)140+        for (key in listOf("z".repeat(64), "a".repeat(63), "a".repeat(65))) {141+            assertFalse(store.appendIssuerSigningKey("issuer", key))142+        }143+        assertFalse(store.appendIssuerSigningKey(" ", keyA))144+        assertTrue(prefs.values.isEmpty())145+    }146+147+    @Test fun corrupt_history_blocks_trust_operations_without_repairing_bytes() {148+        for (bad in listOf("wrong-type", setOf(42), setOf("z".repeat(64)), setOf("a".repeat(63)))) {149+            val prefs = RegistryTestPreferences()150+            prefs.values["issuer_signing_keys:corrupt"] = bad151+            val store = PairedDeviceStore(prefs)152+            val before = prefs.values.toMap()153+            for (operation in listOf<() -> Any?>(154+                { store.issuerSigningKeys("other") },155+                { store.appendIssuerSigningKey("other", keyA) },156+                { store.applyManifestBatch(batch(store)) },157+                { store.manifestSnapshot(setOf("other")) },158+            )) {159+                org.junit.Assert.assertThrows(TrustDataCorruptedException::class.java) { operation() }160+                assertEquals(before, prefs.values)161+            }162+        }163+    }164+165+    @Test fun history_and_snapshot_sets_are_detached_and_duplicate_append_is_idempotent() {166+        val prefs = RegistryTestPreferences()167+        val backing = mutableSetOf(keyA.uppercase())168+        prefs.values["issuer_signing_keys:old"] = backing169+        val store = PairedDeviceStore(prefs)170+        val snapshot = store.snapshot()171+        val keys = store.issuerSigningKeys("old")172+        assertTrue(store.appendIssuerSigningKey("old", keyA))173+        assertEquals(setOf(keyA.uppercase()), prefs.values["issuer_signing_keys:old"])174+        backing.add(keyB)175+        assertEquals(setOf(keyA.uppercase()), snapshot["issuer_signing_keys:old"])176+        assertEquals(setOf(keyA), keys)177+    }178+179+    @Test fun failed_append_and_clear_restore_the_complete_prior_state() {180+        val prefs = RegistryTestPreferences()181+        prefs.values["issuer_signing_keys:old"] = mutableSetOf(keyA)182+        val store = PairedDeviceStore(prefs)183+        val before = prefs.values.toMap()184+        prefs.failNextCommit = true185+        assertFalse(store.appendIssuerSigningKey("new", keyB))186+        assertEquals(before, prefs.values)187+        prefs.failNextCommit = true188+        org.junit.Assert.assertThrows(IllegalStateException::class.java) { store.clear() }189+        assertEquals(before, prefs.values)190+        store.clear()191+        assertTrue(prefs.values.isEmpty())192+    }193+194+    @Test fun metadata_updates_never_rewrite_unchanged_historical_sets() {195+        val prefs = RegistryTestPreferences()196+        prefs.values["issuer_signing_keys:old"] = mutableSetOf(keyA.uppercase())197+        prefs.values["issuer_signing_keys:archived"] = mutableSetOf(keyB)198+        val store = PairedDeviceStore(prefs)199+        store.upsert(PairedDevice("peer", pairedAt = 1L))200+        store.updateLastSync("peer", 5L)201+        assertTrue(prefs.historyPuts.isEmpty())202+        assertTrue(prefs.historyRemovals.isEmpty())203+        assertEquals(setOf(keyA.uppercase()), prefs.values["issuer_signing_keys:old"])204+    }205+206+    @Test fun failed_append_writes_and_restores_only_changed_history() {207+        val prefs = RegistryTestPreferences()208+        prefs.values["issuer_signing_keys:old"] = mutableSetOf(keyA.uppercase())209+        val store = PairedDeviceStore(prefs)210+        prefs.failNextCommit = true211+        assertFalse(store.appendIssuerSigningKey("new", keyB))212+        assertEquals(listOf("issuer_signing_keys:new"), prefs.historyPuts)213+        assertEquals(listOf("issuer_signing_keys:new"), prefs.historyRemovals)214+        prefs.historyPuts.clear()215+        prefs.historyRemovals.clear()216+        prefs.failNextCommit = true217+        assertFalse(store.appendIssuerSigningKey("old", keyC))218+        assertEquals(listOf("issuer_signing_keys:old", "issuer_signing_keys:old"), prefs.historyPuts)219+        assertTrue(prefs.historyRemovals.isEmpty())220+        assertEquals(setOf(keyA.uppercase()), prefs.values["issuer_signing_keys:old"])221+    }222+223+    @Test fun manifest_snapshot_reads_the_complete_validated_archive_once() {224+        val prefs = RegistryTestPreferences()225+        val backing = mutableSetOf(keyA.uppercase())226+        prefs.values["issuer_signing_keys:archived"] = backing227+        prefs.values["issuer_signing_keys:unrequested"] = mutableSetOf(keyB)228+        val store = PairedDeviceStore(prefs)229+        val snapshot = store.manifestSnapshot(setOf("archived"))230+        assertEquals(1, prefs.allReads)231+        assertEquals(0, prefs.stringReads)232+        backing.add(keyC)233+        assertEquals(setOf(keyA), snapshot.issuerSigningKeys["archived"])234+        assertEquals(setOf(keyB), snapshot.issuerSigningKeys["unrequested"])235+    }236+237+238+    @Test fun staged_upserts_cannot_restore_terminal_ids_or_keys_from_either_ledger() {239+        val target = PairedDevice("target", longTermPublicKeyHex = keyA, signingPublicKeyHex = keyB, pairedAt = 2L)240+        for (incoming in listOf(false, true)) {241+            for (revokedId in listOf(target.deviceId, "old-alias")) {242+                val prefs = seededPreferences()243+                val store = PairedDeviceStore(prefs)244+                val staged = batch(store).copy(upserts = listOf(target))245+                val record = DeviceRevocation(revokedId, keyA, 3L, "source")246+                if (!incoming) store.mergeRevocations(listOf(record))247+                val before = prefs.values.toMap()248+                prefs.historyPuts.clear()249+                assertFalse(store.applyManifestBatch(if (incoming) staged.copy(incomingRevocations = listOf(record)) else staged))250+                assertEquals(before, prefs.values)251+                assertTrue(prefs.historyPuts.isEmpty())252+            }253+        }254+    }255+256+    @Test fun changed_missing_or_terminal_authenticated_issuer_rejects_the_entire_batch() {257+        val altered = listOf(258+            emptyList(),259+            listOf(issuer.copy(longTermPublicKeyHex = keyA)),260+            listOf(issuer.copy(signingPublicKeyHex = keyA)),261+            listOf(issuer.copy(trustSource = "manifest")),262+            listOf(issuer.copy(vouchDepth = MAX_VOUCH_DEPTH)),263+        )264+        for (devices in altered) {265+            val prefs = seededPreferences()266+            val store = PairedDeviceStore(prefs)267+            val staged = batch(store)268+            prefs.values["paired_devices"] = Json.encodeToString(ListSerializer(PairedDevice.serializer()), devices)269+            val before = prefs.values.toMap()270+            assertFalse(store.applyManifestBatch(staged))271+            assertEquals(before, prefs.values)272+        }273+        for (revokedId in listOf(issuer.deviceId, "old-alias")) {274+            val prefs = seededPreferences()275+            val store = PairedDeviceStore(prefs)276+            val staged = batch(store)277+            store.mergeRevocations(listOf(DeviceRevocation(revokedId, requireNotNull(issuer.longTermPublicKeyHex), 3L, "other")))278+            val before = prefs.values.toMap()279+            assertFalse(store.applyManifestBatch(staged))280+            assertEquals(before, prefs.values)281+        }282+    }283+284+285+    @Test fun staged_metadata_upsert_cannot_inherit_a_terminal_long_term_key() {286+        val prefs = seededPreferences()287+        val store = PairedDeviceStore(prefs)288+        val target = PairedDevice("target", longTermPublicKeyHex = keyA, pairedAt = 2L)289+        store.upsert(target)290+        val staged = batch(store).copy(upserts = listOf(target.copy(longTermPublicKeyHex = null)))291+        store.mergeRevocations(listOf(DeviceRevocation("old-alias", keyA, 3L, "source")))292+        val before = prefs.values.toMap()293+        assertFalse(store.applyManifestBatch(staged))294+        assertEquals(before, prefs.values)295+    }296+297+298+    @Test fun live_issuer_can_deliver_its_own_removal_then_cannot_deliver_another_batch() {299+        val prefs = seededPreferences()300+        val store = PairedDeviceStore(prefs)301+        val originalIssuer = deriveSyncSigningKeypair(ByteArray(32) { 7 }, "original-issuer")302+        val originalKey = pubkeyToHex(originalIssuer.publicKeyRaw)303+        assertTrue(store.appendIssuerSigningKey("original-issuer", originalKey))304+        val record = signDeviceRevocation(305+            DeviceRevocation(issuer.deviceId, requireNotNull(issuer.longTermPublicKeyHex), 3L, "original-issuer"),306+            originalIssuer.privateKey,307+        )308+        val staged = batch(store).copy(309+            incomingRevocations = listOf(record),310+            removals = setOf(issuer.deviceId),311+            upserts = listOf(PairedDevice("nonterminal-child", longTermPublicKeyHex = keyA, pairedAt = 4L)),312+            issuerSigningKeys = mapOf(issuer.deviceId to setOf(requireNotNull(issuer.signingPublicKeyHex))),313+        )314+        assertTrue(store.applyManifestBatch(staged))315+        assertEquals(null, store.get(issuer.deviceId))316+        assertTrue(store.get("nonterminal-child") != null)317+        assertEquals(listOf(record), store.listRevocations())318+        assertTrue(verifyDeviceRevocation(store.listRevocations().single(), originalIssuer.publicKeyRaw))319+        assertEquals(setOf(originalKey), store.issuerSigningKeys("original-issuer"))320+        assertEquals(setOf(issuer.signingPublicKeyHex), store.issuerSigningKeys(issuer.deviceId))321+        val committed = prefs.values.toMap()322+        assertFalse(store.applyManifestBatch(staged))323+        assertEquals(committed, prefs.values)324+    }325+326+327+    @Test fun raw_recovery_archives_and_clears_semantically_corrupt_native_values() {328+        val prefs = RegistryTestPreferences()329+        prefs.values.putAll(mapOf(330+            "paired_devices" to 7,331+            "device_revocations" to true,332+            "issuer_signing_keys:text" to "not-a-set",333+            "issuer_signing_keys:set" to mutableSetOf("not-hex"),334+            "issuer_signing_keys:int" to 42,335+            "issuer_signing_keys:long" to 42L,336+            "issuer_signing_keys:float" to 1.5f,337+            "issuer_signing_keys:bool" to false,338+            "unrelated" to "retain",339+        ))340+        val store = PairedDeviceStore(prefs)341+        val snapshot = store.snapshot()342+        assertEquals(prefs.values, snapshot)343+        val archive = RegistryTestPreferences()344+        assertTrue(archiveTrustPreferenceValues(archive, snapshot))345+        assertEquals(snapshot, archive.values)346+        prefs.failNextCommit = true347+        org.junit.Assert.assertThrows(IllegalStateException::class.java) { store.clear() }348+        assertEquals(snapshot, prefs.values)349+        store.clear()350+        assertEquals(mapOf("unrelated" to "retain"), prefs.values)351+    }352+353+    @Test fun unsupported_raw_values_block_recovery_before_any_write() {354+        for (bad in listOf(setOf(42), listOf("unsupported"))) {355+            val prefs = RegistryTestPreferences()356+            prefs.values["issuer_signing_keys:bad"] = bad357+            val before = prefs.values.toMap()358+            val store = PairedDeviceStore(prefs)359+            org.junit.Assert.assertThrows(IllegalArgumentException::class.java) { store.snapshot() }360+            org.junit.Assert.assertThrows(IllegalArgumentException::class.java) { store.clear() }361+            assertEquals(before, prefs.values)362+            val archive = RegistryTestPreferences()363+            org.junit.Assert.assertThrows(IllegalArgumentException::class.java) { archiveTrustPreferenceValues(archive, before) }364+            assertTrue(archive.values.isEmpty())365+        }366+    }367+368+    @Test fun device_only_metadata_and_reads_do_not_scan_or_validate_history() {369+        val prefs = seededPreferences()370+        prefs.values["issuer_signing_keys:corrupt"] = "preserve"371+        val store = PairedDeviceStore(prefs)372+        assertEquals(issuer, store.get(issuer.deviceId))373+        assertTrue(store.listRevocations().isEmpty())374+        store.updateLastSync(issuer.deviceId, 9L)375+        store.rename(issuer.deviceId, "Local")376+        assertEquals(9L, store.get(issuer.deviceId)?.lastSyncedAt)377+        assertEquals(0, prefs.allReads)378+        assertEquals("preserve", prefs.values["issuer_signing_keys:corrupt"])379+    }380+381+    @Test fun empty_history_set_is_preserved_as_a_conservative_trust_marker() {382+        val prefs = seededPreferences()383+        prefs.values["issuer_signing_keys:empty"] = mutableSetOf<String>()384+        val store = PairedDeviceStore(prefs)385+        assertTrue(store.hasIssuerSigningKeys())386+        assertTrue(store.manifestSnapshot(emptySet()).issuerSigningKeys.containsKey("empty"))387+        assertTrue(store.applyManifestBatch(batch(store)))388+        assertEquals(emptySet<String>(), prefs.values["issuer_signing_keys:empty"])389+    }390+391+    @Test fun batch_history_can_only_retain_authenticated_issuer_current_or_known_keys() {392+        val prefs = seededPreferences()393+        val store = PairedDeviceStore(prefs)394+        val staged = batch(store)395+        for (additions in listOf(mapOf("foreign" to setOf(keyA)), mapOf(issuer.deviceId to setOf(keyA)))) {396+            val before = prefs.values.toMap()397+            assertFalse(store.applyManifestBatch(staged.copy(issuerSigningKeys = additions)))398+            assertEquals(before, prefs.values)399+        }400+        assertTrue(store.appendIssuerSigningKey(issuer.deviceId, keyA.uppercase()))401+        assertTrue(store.applyManifestBatch(batch(store).copy(issuerSigningKeys = mapOf(issuer.deviceId to setOf(keyA)))))402+    }403+404+    @Test fun snapshot_change_refuses_stale_rows_ledgers_and_history_but_preserves_local_metadata() {405+        val target = PairedDevice("target", longTermPublicKeyHex = keyA, signingPublicKeyHex = keyB, trustSource = "vouched", pairedAt = 2L)406+        for (change in listOf("depth", "repair", "remove", "ledger", "history")) {407+            val prefs = seededPreferences()408+            val store = PairedDeviceStore(prefs)409+            store.upsert(target)410+            store.appendIssuerSigningKey(issuer.deviceId, keyC)411+            val record = DeviceRevocation("gone", keyB, 3L, issuer.deviceId)412+            store.mergeRevocations(listOf(record))413+            val staged = batch(store).copy(upserts = listOf(target), incomingRevocations = listOf(record))414+            when (change) {415+                "depth" -> store.upsert(issuer.copy(vouchDepth = 1))416+                "repair" -> store.upsertAndClearRevocation(target.copy(trustSource = "direct", relayUrl = "wss://new.example"))417+                "remove" -> store.remove(target.deviceId)418+                "ledger" -> store.clearRevocation(record.deviceId)419+                "history" -> { store.clear(); store.upsert(issuer); store.upsert(target); store.mergeRevocations(listOf(record)) }420+            }421+            val changed = prefs.values.toMap()422+            assertFalse("stale $change must refuse", store.applyManifestBatch(staged))423+            assertEquals(changed, prefs.values)424+        }425+        val prefs = seededPreferences()426+        val store = PairedDeviceStore(prefs)427+        store.upsert(target)428+        val staged = batch(store).copy(upserts = listOf(target.copy(deviceName = "Remote name")))429+        store.updateLastSync(target.deviceId, 99L)430+        store.updateLastSeen(target.deviceId, "192.0.2.1")431+        store.rename(target.deviceId, "Local alias")432+        store.upsert(issuer.copy(lastSyncedAt = 100L))433+        assertTrue(store.applyManifestBatch(staged))434+        assertEquals(100L, store.get(issuer.deviceId)?.lastSyncedAt)435+        assertEquals(target.copy(deviceName = "Remote name", lastSyncedAt = 99L, lastKnownIp = "192.0.2.1", localAlias = "Local alias"), store.get(target.deviceId))436+    }437+438+    @Test fun incoming_terminal_key_removes_alias_row_without_cascading_other_upserts() {439+        val prefs = seededPreferences()440+        val store = PairedDeviceStore(prefs)441+        val alias = PairedDevice("alias", longTermPublicKeyHex = keyA, pairedAt = 2L)442+        val child = PairedDevice("child", longTermPublicKeyHex = keyB, pairedAt = 2L)443+        store.upsert(alias)444+        val staged = batch(store).copy(445+            incomingRevocations = listOf(DeviceRevocation("old-id", keyA, 3L, issuer.deviceId)),446+            removals = setOf("old-id"), upserts = listOf(child),447+        )448+        assertTrue(store.applyManifestBatch(staged))449+        assertEquals(null, store.get(alias.deviceId))450+        assertEquals(child, store.get(child.deviceId))451+    }452+41453 }

view file

app/src/test/java/com/peachpasswords/sync/VaultSyncAdapterTest.kt+151 −1
@@ -39,6 +39,12 @@3939         devices: List<PairedDevice> = emptyList(),4040     ) : PairedDeviceRegistry {4141         var failManifestCommit = false42+        val history = mutableMapOf<String, Set<String>>()43+        override fun issuerSigningKeys(issuerDeviceId: String) = history[issuerDeviceId].orEmpty()44+        override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {45+            history[issuerDeviceId] = issuerSigningKeys(issuerDeviceId) + signingKeyHex46+            return true47+        }4248         private val byId = devices.associateBy { it.deviceId }.toMutableMap()4349         private val revocations = mutableListOf<DeviceRevocation>()4450         override fun getAll(): List<PairedDevice> = byId.values.toList()@@ -52,6 +58,7 @@5258             val nextDevices = byId.toMutableMap()5359             batch.removals.forEach(nextDevices::remove)5460             batch.upserts.forEach { nextDevices[it.deviceId] = it }61+            batch.issuerSigningKeys.forEach { (issuer, keys) -> history[issuer] = issuerSigningKeys(issuer) + keys }5562             revocations.clear()5663             revocations += nextRevocations5764             byId.clear()@@ -70,6 +77,13 @@7077     }7178 7279     private class FakePendingRegistry : PendingVouchedRegistry {80+        var failRemoveBatch = false81+        var beforeRemoveBatch: (() -> Unit)? = null82+        override fun removeBatch(ids: Set<String>): Boolean {83+            ids.forEach(::remove)84+            beforeRemoveBatch?.invoke()85+            return !failRemoveBatch86+        }7387         val devices = mutableListOf<PendingVouchedDevice>()7488         override fun getAll(): List<PendingVouchedDevice> = devices.toList()7589         override fun upsert(device: PendingVouchedDevice) {@@ -338,10 +352,19 @@338352         assertEquals(meshRelay, admitted?.relayUrl)339353         assertTrue(admitted?.rendezvousSecretHex?.matches(Regex("[0-9a-f]{64}")) == true)340354         assertTrue(pending.devices.isEmpty())355+        assertEquals(setOf(pubkeyToHex(issuerSigning.publicKeyRaw)), paired.issuerSigningKeys("extension-issuer"))341356         master.fill(0)342357     }343358 344359     @Test fun failed_manifest_commit_restores_pending_before_trust_can_land() = runBlocking {360+        assertFailedManifestRetainsNoHistory(failPending = false)361+    }362+363+    @Test fun failed_pending_removal_does_not_commit_issuer_history() = runBlocking {364+        assertFailedManifestRetainsNoHistory(failPending = true)365+    }366+367+    private suspend fun assertFailedManifestRetainsNoHistory(failPending: Boolean) {345368         val repo = VaultRepository(FakeStorage())346369         repo.createVault("correct horse")347370         val master = repo.syncMasterKey()!!@@ -358,8 +381,9 @@358381                     pairedAt = 1L,359382                 ),360383             ),361-        ).also { it.failManifestCommit = true }384+        ).also { it.failManifestCommit = !failPending }362385         val pending = FakePendingRegistry().also {386+            it.failRemoveBatch = failPending363387             it.upsert(364388                 PendingVouchedDevice(365389                     deviceId = "new-phone",@@ -394,6 +418,7 @@394418 395419         assertNull("failed registry commit must not install trust", paired.get("new-phone"))396420         assertEquals("pending introduction is restored for retry", 1, pending.devices.size)421+        assertTrue("failed batch must not retain a newly learned signing key", paired.history.isEmpty())397422         master.fill(0)398423     }399424     /**@@ -773,4 +798,129 @@773798         assertTrue(runCatching { hexToPubkey("ab".repeat(33)) }.isFailure)774799         assertEquals(64, hexToBytes("ab".repeat(64)).size)775800     }801+802+    @Test fun incoming_manifest_archive_reads_do_not_scale_with_record_count() = runBlocking {803+        val readCounts = listOf(1, 20).map { recordCount ->804+            val repo = VaultRepository(FakeStorage())805+            repo.createVault("correct horse")806+            val master = repo.syncMasterKey()!!807+            try {808+                val issuer = deriveSyncSigningKeypair(master, "direct")809+                val archived = deriveSyncSigningKeypair(master, "archived")810+                val historicalIssuer = deriveSyncSigningKeypair(master, "historical-direct")811+                val prefs = RegistryTestPreferences()812+                val registry = PairedDeviceStore(prefs)813+                registry.upsert(PairedDevice(814+                    "direct", longTermPublicKeyHex = "11".repeat(32),815+                    signingPublicKeyHex = pubkeyToHex(issuer.publicKeyRaw),816+                    trustSource = "direct", pairedAt = 1L,817+                ))818+                registry.appendIssuerSigningKey("archived", pubkeyToHex(archived.publicKeyRaw))819+                registry.appendIssuerSigningKey("direct", pubkeyToHex(historicalIssuer.publicKeyRaw))820+                val records = (0 until recordCount).map { index ->821+                    signDeviceRevocation(822+                        DeviceRevocation("gone-$index", "22".repeat(32), 1L, "archived"),823+                        archived.privateKey,824+                    )825+                }826+                val entries = (0 until recordCount).map { index ->827+                    val suffix = index.toString(16).padStart(2, '0')828+                    ManifestDeviceEntry(829+                        "peer-$index", deviceName = "Peer $index", deviceType = "android",830+                        longTermPublicKeyHex = "33".repeat(31) + suffix,831+                        signingPublicKeyHex = "44".repeat(31) + suffix,832+                        relayUrl = meshRelay, pairedAt = 1L,833+                    )834+                }835+                val manifest = buildSignedDeviceManifest("direct", entries, historicalIssuer.privateKey, revoked = records)836+                val adapter = VaultSyncAdapter(837+                    repo, ourDeviceId = "self", pairedDevices = registry,838+                    pendingVouched = FakePendingRegistry(), localCredentials = localCredentials("self"),839+                )840+                prefs.allReads = 0841+                prefs.stringReads = 0842+                adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })843+                val reads = prefs.allReads + prefs.stringReads844+                assertEquals(records, registry.listRevocations())845+                assertNull(registry.get("archived"))846+                assertEquals(recordCount + 1, registry.getAll().size)847+                reads848+            } finally {849+                master.fill(0)850+            }851+        }852+        assertEquals("one snapshot and one commit revalidation for either manifest size", listOf(2, 2), readCounts)853+    }854+855+856+    @Test fun untrusted_manifest_record_count_and_issuer_size_reject_before_snapshot() = runBlocking {857+        val prefs = RegistryTestPreferences()858+        prefs.values["issuer_signing_keys:corrupt"] = "preserve"859+        val adapter = VaultSyncAdapter(860+            VaultRepository(FakeStorage()), "self", PairedDeviceStore(prefs), FakePendingRegistry(),861+        )862+        val record = DeviceRevocation("gone", "22".repeat(32), 1L, "issuer")863+        val bodies = listOf(864+            List(MAX_MANIFEST_REVOCATIONS + 1) { record },865+            listOf(record.copy(revokedByDeviceId = "x".repeat(MAX_MANIFEST_STRING + 1))),866+        )867+        for (records in bodies) {868+            adapter.applyIncomingDeviceManifest(869+                SignedDeviceManifest(DeviceManifestBody(DEVICE_MANIFEST_VERSION, "issuer", 1L, emptyList(), records), ""),870+                ByteArray(32) { 0x11 },871+            )872+        }873+        assertEquals(0, prefs.allReads)874+        assertEquals("preserve", prefs.values["issuer_signing_keys:corrupt"])875+    }876+877+878+    @Test fun real_store_commit_failures_and_stale_snapshots_restore_pending_without_replacing_concurrent_changes() = runBlocking {879+        for (change in listOf("commit", "revoke", "depth", "repair", "remove", "history")) {880+            val repo = VaultRepository(FakeStorage())881+            repo.createVault("correct horse")882+            val master = repo.syncMasterKey()!!883+            try {884+                val signing = deriveSyncSigningKeypair(master, "issuer")885+                val historical = deriveSyncSigningKeypair(master, "historical")886+                val prefs = RegistryTestPreferences()887+                val registry = PairedDeviceStore(prefs)888+                val issuer = PairedDevice("issuer", longTermPublicKeyHex = "11".repeat(32),889+                    signingPublicKeyHex = pubkeyToHex(signing.publicKeyRaw), trustSource = "direct", pairedAt = 1L)890+                val target = PairedDevice("target", longTermPublicKeyHex = "aa".repeat(32),891+                    signingPublicKeyHex = "bb".repeat(32), trustSource = "vouched", vouchDepth = 1, pairedAt = 2L)892+                registry.upsert(issuer)893+                registry.upsert(target)894+                registry.appendIssuerSigningKey(issuer.deviceId, pubkeyToHex(historical.publicKeyRaw))895+                val pending = FakePendingRegistry()896+                pending.upsert(PendingVouchedDevice("target", "Target", "android", "aa".repeat(32), "bb".repeat(32),897+                    pairedAt = 2L, receivedAt = 3L, vouchedByDeviceId = issuer.deviceId))898+                val priorPending = pending.getAll()899+                var expectedAfterHook: Map<String, Any?>? = null900+                pending.beforeRemoveBatch = {901+                    when (change) {902+                        "commit" -> prefs.failNextCommit = true903+                        "revoke" -> registry.revoke(issuer.deviceId, "self", 4L)904+                        "depth" -> registry.upsert(issuer.copy(vouchDepth = 1))905+                        "repair" -> registry.upsertAndClearRevocation(target.copy(trustSource = "direct", relayUrl = "wss://new.example"))906+                        "remove" -> registry.remove(target.deviceId)907+                        "history" -> { registry.clear(); registry.upsert(issuer); registry.upsert(target) }908+                    }909+                    expectedAfterHook = prefs.values.toMap()910+                }911+                val manifest = buildSignedDeviceManifest(issuer.deviceId, listOf(912+                    ManifestDeviceEntry("target", "Target", "android", "aa".repeat(32), "bb".repeat(32),913+                        relayUrl = meshRelay, pairedAt = 2L),914+                ), if (change == "history") historical.privateKey else signing.privateKey)915+                val adapter = VaultSyncAdapter(repo, "self", registry, pending, localCredentials = localCredentials("self"))916+                adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })917+                assertTrue("pending hook ran for $change", expectedAfterHook != null)918+                assertEquals("concurrent $change retained exactly", expectedAfterHook, prefs.values)919+                assertEquals("pending restored after $change", priorPending, pending.getAll())920+            } finally {921+                master.fill(0)922+            }923+        }924+    }925+776926 }

view file