VaultSyncAdapterTest.kt

42.7 KB · raw

1package com.peachpasswords.sync23import com.peachpasswords.vault.StoredVault4import com.peachpasswords.vault.VaultEntry5import com.peachpasswords.vault.VaultRepository6import com.peachpasswords.vault.VaultSettings7import com.peachpasswords.vault.VaultStorage8import kotlinx.coroutines.runBlocking9import org.junit.Assert.assertEquals10import org.junit.Assert.assertFalse11import org.junit.Assert.assertNull12import org.junit.Assert.assertTrue13import org.junit.Test1415private class FakeStorage : VaultStorage {16    private var slotA: StoredVault? = null17    private var slotB: String? = null18    private var ver: Long = 019    private var settings = VaultSettings()20    override fun loadSlotA() = slotA21    override fun hasVault() = slotA != null22    override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }23    override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }24    private var decoy: StoredVault? = null25    override fun loadDecoySlot() = decoy26    override fun writeDecoySlot(slot: StoredVault): Boolean { decoy = slot; return true }27    override fun hasDecoySlot() = decoy != null28    override fun clearDecoySlot() { decoy = null }29    override fun version() = ver30    override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }31    override fun loadSettings() = settings32    override fun writeSettings(s: VaultSettings): Boolean { settings = s; return true }33    override fun clearVault(): Boolean { slotA = null; slotB = null; ver = 0; settings = VaultSettings(); return true }34}3536class VaultSyncAdapterTest {37    private val meshRelay = "wss://relay.peachpasswords.com"38    private class FakeDeviceRegistry(39        devices: List<PairedDevice> = emptyList(),40    ) : PairedDeviceRegistry {41        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        }48        private val byId = devices.associateBy { it.deviceId }.toMutableMap()49        private val revocations = mutableListOf<DeviceRevocation>()50        override fun getAll(): List<PairedDevice> = byId.values.toList()51        override fun get(id: String): PairedDevice? = byId[id]52        override fun upsert(device: PairedDevice) { byId[device.deviceId] = device }53        override fun remove(deviceId: String) { byId.remove(deviceId) }54        override fun listRevocations(): List<DeviceRevocation> = revocations.toList()55        override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {56            if (failManifestCommit) return false57            val nextRevocations = mergeRevocationRecords(revocations, batch.incomingRevocations).records.toMutableList()58            val nextDevices = byId.toMutableMap()59            batch.removals.forEach(nextDevices::remove)60            batch.upserts.forEach { nextDevices[it.deviceId] = it }61            batch.issuerSigningKeys.forEach { (issuer, keys) -> history[issuer] = issuerSigningKeys(issuer) + keys }62            revocations.clear()63            revocations += nextRevocations64            byId.clear()65            byId.putAll(nextDevices)66            return true67        }68        override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {69            val merged = mergeRevocationRecords(revocations, incoming)70            revocations.clear()71            revocations += merged.records72            return merged.admitted.map { it.deviceId }73        }74        override fun clearRevocation(deviceId: String) {75            revocations.removeAll { it.deviceId == deviceId }76        }77    }7879    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        }87        val devices = mutableListOf<PendingVouchedDevice>()88        override fun getAll(): List<PendingVouchedDevice> = devices.toList()89        override fun upsert(device: PendingVouchedDevice) {90            devices.removeAll { it.deviceId == device.deviceId }91            devices += device92        }93        override fun remove(id: String) { devices.removeAll { it.deviceId == id } }94    }9596    private fun localCredentials(deviceId: String) = randomLocalIdentityCredentials(deviceId)9798    private fun newAdapter(): Pair<VaultRepository, VaultSyncAdapter> {99        val repo = VaultRepository(FakeStorage())100        runBlocking { repo.createVault("correct horse") }101        return repo to VaultSyncAdapter(102            repo,103            ourDeviceId = "android-test",104            localCredentials = localCredentials("android-test"),105        )106    }107108    @Test fun manifest_and_vault_id_reflect_the_vault() = runBlocking {109        val (repo, adapter) = newAdapter()110        val e = repo.addEntry(VaultEntry(id = "", title = "GitHub", createdAt = 0, modifiedAt = 0, password = "p"))111        val manifest = adapter.buildEntryManifest()112        assertEquals(setOf(e.id), manifest.keys)113        assertTrue(adapter.computeVaultId().length == 64) // blake3-256 hex114    }115116    @Test fun envelope_round_trips_within_the_vault() = runBlocking {117        val (repo, adapter) = newAdapter()118        val e = repo.addEntry(VaultEntry(id = "", title = "Mail", createdAt = 0, modifiedAt = 0, password = "secret"))119        val envelopes = adapter.getEncryptedEntries(listOf(e.id))120        assertTrue(envelopes.containsKey(e.id))121        // Re-applying the same envelope is a safe no-op (same mtime, no overwrite).122        adapter.applyEntries(envelopes)123        assertEquals(1, repo.getEntries().size)124    }125126    @Test fun swapped_envelope_is_rejected_by_id_binding() = runBlocking {127        val (repo, adapter) = newAdapter()128        val e = repo.addEntry(VaultEntry(id = "", title = "Bank", createdAt = 0, modifiedAt = 0, password = "x"))129        val blob = adapter.getEncryptedEntries(listOf(e.id)).getValue(e.id)130        // Present the ciphertext under a different id — the decrypted entry.id131        // won't match, so it must be dropped, not poison a new slot.132        adapter.applyEntries(mapOf("attacker-chosen-id" to blob))133        assertNull(repo.getEntry("attacker-chosen-id"))134        assertEquals(1, repo.getEntries().size)135    }136137    // HKDF separator (coordinated with peach-browser): an envelope minted under138    // the OLD, unseparated info (`entryId + suffix`) must no longer decrypt. This139    // locks in the conscious wire break and asserts byte-for-byte parity with the140    // browser's matching `legacy_info_envelope_fails_closed` test.141    @Test fun legacy_info_envelope_fails_closed() = runBlocking {142        val (repo, adapter) = newAdapter()143        val master = repo.syncMasterKey()!!144        val entryId = "11111111-2222-4333-8444-555555555555"145        val entry = VaultEntry(id = entryId, title = "LegacyOnly", createdAt = 0, modifiedAt = 0, password = "pw")146147        // Legacy info: no U+0000 separator.148        val legacyInfo = (entryId + "sync-entry-v1").toByteArray(Charsets.UTF_8)149        val gen = org.bouncycastle.crypto.generators.HKDFBytesGenerator(org.bouncycastle.crypto.digests.SHA256Digest())150        gen.init(org.bouncycastle.crypto.params.HKDFParameters(master, ByteArray(0), legacyInfo))151        val key = ByteArray(32).also { gen.generateBytes(it, 0, it.size) }152153        val json = kotlinx.serialization.json.Json { encodeDefaults = false; ignoreUnknownKeys = true }154        val plaintext = json.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)155        val nonce = ByteArray(12).also { java.security.SecureRandom().nextBytes(it) }156        val cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding")157        cipher.init(158            javax.crypto.Cipher.ENCRYPT_MODE,159            javax.crypto.spec.SecretKeySpec(key, "AES"),160            javax.crypto.spec.GCMParameterSpec(128, nonce),161        )162        cipher.updateAAD("peach-sync-entry-v1".toByteArray(Charsets.UTF_8))163        val ct = cipher.doFinal(plaintext)164        val legacyEnvelope = java.util.Base64.getEncoder().encodeToString(nonce + ct)165166        adapter.applyEntries(mapOf(entryId to legacyEnvelope))167        // Patched adapter derives with the separated info → decrypt fails → dropped.168        assertNull(repo.getEntry(entryId))169    }170171    @Test fun signed_device_manifest_round_trips_through_canonical_signature() = runBlocking {172        val master = ByteArray(32) { it.toByte() }173        val signing = deriveSyncSigningKeypair(master, "extension-issuer")174        val manifest = buildSignedDeviceManifest(175            issuerDeviceId = "extension-issuer",176            devices = listOf(177                ManifestDeviceEntry(178                    deviceId = "android-peer",179                    deviceName = "Phone",180                    deviceType = "android",181                    longTermPublicKeyHex = "aa".repeat(32),182                    signingPublicKeyHex = "bb".repeat(32),183                    pairedAt = 123L,184                ),185            ),186            signingPrivateKey = signing.privateKey,187            nowMs = 1_000L,188        )189190        val verified = verifyDeviceManifest(191            manifest,192            signing.publicKeyRaw,193            { setOf(pubkeyToHex(signing.publicKeyRaw)) },194            nowMs = 1_000L,195        )196197        assertEquals("extension-issuer", verified?.issuerDeviceId)198        assertEquals("android-peer", verified?.devices?.single()?.deviceId)199        assertTrue(verifyDeviceManifest(manifest.copy(signatureHex = "00".repeat(64)), signing.publicKeyRaw, { setOf(pubkeyToHex(signing.publicKeyRaw)) }, nowMs = 1_000L) == null)200    }201202    @Test fun `vouched peer revocation evicts the device and permanently blocks re-vouching`() = runBlocking {203        val repo = VaultRepository(FakeStorage())204        repo.createVault("correct horse")205        val master = repo.syncMasterKey()!!206        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")207        val paired = FakeDeviceRegistry(208            listOf(209                PairedDevice(210                    deviceId = "extension-issuer",211                    deviceName = "Peach Browser",212                    deviceType = "extension",213                    longTermPublicKeyHex = "11".repeat(32),214                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),215                    trustSource = "vouched",216                    pairedAt = 1L,217                ),218                PairedDevice(219                    deviceId = "stolen-laptop",220                    deviceName = "Old Laptop",221                    deviceType = "extension",222                    longTermPublicKeyHex = "dd".repeat(32),223                    signingPublicKeyHex = "ee".repeat(32),224                    trustSource = "direct",225                    pairedAt = 2L,226                ),227            ),228        )229        val pending = FakePendingRegistry()230        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))231232        val revocation = buildSignedDeviceManifest(233            issuerDeviceId = "extension-issuer",234            devices = emptyList(),235            signingPrivateKey = issuerSigning.privateKey,236            revoked = listOf(237                DeviceRevocation(238                    deviceId = "stolen-laptop",239                    longTermPublicKeyHex = "dd".repeat(32),240                    revokedAt = System.currentTimeMillis(),241                    revokedByDeviceId = "extension-issuer",242                ),243            ),244        )245        adapter.applyIncomingDeviceManifest(revocation, ByteArray(32) { 0x11 })246247        assertNull(paired.get("stolen-laptop"))248249        // A later manifest vouches it back with a fresh pairedAt — exactly the250        // resurrection a timestamp-ordered design would allow.251        val revouch = buildSignedDeviceManifest(252            issuerDeviceId = "extension-issuer",253            devices = listOf(254                ManifestDeviceEntry(255                    deviceId = "stolen-laptop",256                    deviceName = "Old Laptop",257                    deviceType = "extension",258                    longTermPublicKeyHex = "dd".repeat(32),259                    signingPublicKeyHex = "ee".repeat(32),260                    pairedAt = System.currentTimeMillis() + 60_000L,261                ),262            ),263            signingPrivateKey = issuerSigning.privateKey,264        )265        adapter.applyIncomingDeviceManifest(revouch, ByteArray(32) { 0x11 })266267        assertNull(paired.get("stolen-laptop"))268        assertEquals(0, pending.devices.size)269        master.fill(0)270    }271272    @Test fun `a peer cannot revoke this device`() = runBlocking {273        val repo = VaultRepository(FakeStorage())274        repo.createVault("correct horse")275        val master = repo.syncMasterKey()!!276        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")277        val paired = FakeDeviceRegistry(278            listOf(279                PairedDevice(280                    deviceId = "extension-issuer",281                    deviceName = "Peach Browser",282                    deviceType = "extension",283                    longTermPublicKeyHex = "11".repeat(32),284                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),285                    trustSource = "direct",286                    pairedAt = 1L,287                ),288            ),289        )290        val pending = FakePendingRegistry()291        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))292293        val selfRevoke = buildSignedDeviceManifest(294            issuerDeviceId = "extension-issuer",295            devices = emptyList(),296            signingPrivateKey = issuerSigning.privateKey,297            revoked = listOf(298                DeviceRevocation(299                    deviceId = "android-self",300                    longTermPublicKeyHex = "ff".repeat(32),301                    revokedAt = System.currentTimeMillis(),302                    revokedByDeviceId = "extension-issuer",303                ),304            ),305        )306        adapter.applyIncomingDeviceManifest(selfRevoke, ByteArray(32) { 0x11 })307308        assertTrue(paired.listRevocations().none { it.deviceId == "android-self" })309        master.fill(0)310    }311312    @Test fun incoming_extension_manifest_auto_admits_routable_same_vault_peer() = runBlocking {313        val repo = VaultRepository(FakeStorage())314        repo.createVault("correct horse")315        val master = repo.syncMasterKey()!!316        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")317        val paired = FakeDeviceRegistry(318            listOf(319                PairedDevice(320                    deviceId = "extension-issuer",321                    deviceName = "Peach Browser",322                    deviceType = "extension",323                    longTermPublicKeyHex = "11".repeat(32),324                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),325                    trustSource = "direct",326                    pairedAt = 1L,327                ),328            ),329        )330        val pending = FakePendingRegistry()331        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))332        val manifest = buildSignedDeviceManifest(333            issuerDeviceId = "extension-issuer",334            devices = listOf(335                ManifestDeviceEntry(336                    deviceId = "new-phone",337                    deviceName = "June's Phone",338                    deviceType = "android",339                    longTermPublicKeyHex = "aa".repeat(32),340                    signingPublicKeyHex = "bb".repeat(32),341                    relayUrl = meshRelay,342                    pairedAt = 44L,343                ),344            ),345            signingPrivateKey = issuerSigning.privateKey,346        )347348        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })349350        val admitted = paired.get("new-phone")351        assertEquals("vouched", admitted?.trustSource)352        assertEquals(meshRelay, admitted?.relayUrl)353        assertTrue(admitted?.rendezvousSecretHex?.matches(Regex("[0-9a-f]{64}")) == true)354        assertTrue(pending.devices.isEmpty())355        assertEquals(setOf(pubkeyToHex(issuerSigning.publicKeyRaw)), paired.issuerSigningKeys("extension-issuer"))356        master.fill(0)357    }358359    @Test fun failed_manifest_commit_restores_pending_before_trust_can_land() = runBlocking {360        assertFailedManifestRetainsNoHistory(failPending = false)361    }362363    @Test fun failed_pending_removal_does_not_commit_issuer_history() = runBlocking {364        assertFailedManifestRetainsNoHistory(failPending = true)365    }366367    private suspend fun assertFailedManifestRetainsNoHistory(failPending: Boolean) {368        val repo = VaultRepository(FakeStorage())369        repo.createVault("correct horse")370        val master = repo.syncMasterKey()!!371        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")372        val paired = FakeDeviceRegistry(373            listOf(374                PairedDevice(375                    deviceId = "extension-issuer",376                    deviceName = "Peach Browser",377                    deviceType = "extension",378                    longTermPublicKeyHex = "11".repeat(32),379                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),380                    trustSource = "direct",381                    pairedAt = 1L,382                ),383            ),384        ).also { it.failManifestCommit = !failPending }385        val pending = FakePendingRegistry().also {386            it.failRemoveBatch = failPending387            it.upsert(388                PendingVouchedDevice(389                    deviceId = "new-phone",390                    deviceName = "June's Phone",391                    deviceType = "android",392                    longTermPublicKeyHex = "aa".repeat(32),393                    signingPublicKeyHex = "bb".repeat(32),394                    pairedAt = 44L,395                    receivedAt = 45L,396                    vouchedByDeviceId = "extension-issuer",397                ),398            )399        }400        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))401        val manifest = buildSignedDeviceManifest(402            issuerDeviceId = "extension-issuer",403            devices = listOf(404                ManifestDeviceEntry(405                    deviceId = "new-phone",406                    deviceName = "June's Phone",407                    deviceType = "android",408                    longTermPublicKeyHex = "aa".repeat(32),409                    signingPublicKeyHex = "bb".repeat(32),410                    relayUrl = meshRelay,411                    pairedAt = 44L,412                ),413            ),414            signingPrivateKey = issuerSigning.privateKey,415        )416417        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })418419        assertNull("failed registry commit must not install trust", paired.get("new-phone"))420        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())422        master.fill(0)423    }424    /**425     * Browser parity (`applyVerifiedPeerManifest`): trust is keyed on the issuer426     * being DIRECTLY paired, not on it being a browser. Android used to require427     * deviceType == "extension", which silently killed mesh propagation between428     * native devices — the case the mesh exists for now that phones are the429     * listening side.430     */431    @Test fun `a manifest from a directly paired phone is accepted`() = runBlocking {432        val repo = VaultRepository(FakeStorage())433        repo.createVault("correct horse")434        val master = repo.syncMasterKey()!!435        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")436        val paired = FakeDeviceRegistry(437            listOf(438                PairedDevice(439                    deviceId = "phone-issuer",440                    deviceName = "Other Phone",441                    deviceType = "android",442                    longTermPublicKeyHex = "11".repeat(32),443                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),444                    trustSource = "direct",445                    pairedAt = 1L,446                ),447            ),448        )449        val pending = FakePendingRegistry()450        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))451        val manifest = buildSignedDeviceManifest(452            issuerDeviceId = "phone-issuer",453            devices = listOf(454                ManifestDeviceEntry(455                    deviceId = "laptop-b",456                    deviceName = "Laptop B",457                    deviceType = "extension",458                    longTermPublicKeyHex = "aa".repeat(32),459                    signingPublicKeyHex = "bb".repeat(32),460                    relayUrl = meshRelay,461                    pairedAt = 44L,462                ),463            ),464            signingPrivateKey = issuerSigning.privateKey,465        )466467        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })468469        assertEquals("vouched", paired.get("laptop-b")?.trustSource)470        assertEquals(meshRelay, paired.get("laptop-b")?.relayUrl)471        assertTrue(pending.devices.isEmpty())472        master.fill(0)473    }474475    /** A vouched peer cannot extend the trust graph beyond one hop. */476    @Test fun `a vouched issuer cannot introduce further mesh devices`() = runBlocking {477        val repo = VaultRepository(FakeStorage())478        repo.createVault("correct horse")479        val master = repo.syncMasterKey()!!480        val issuerSigning = deriveSyncSigningKeypair(master, "vouched-issuer")481        val paired = FakeDeviceRegistry(482            listOf(483                PairedDevice(484                    deviceId = "vouched-issuer",485                    deviceName = "Vouched Device",486                    deviceType = "extension",487                    longTermPublicKeyHex = "11".repeat(32),488                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),489                    trustSource = "vouched",490                    vouchDepth = MAX_VOUCH_DEPTH,491                    pairedAt = 1L,492                ),493            ),494        )495        val pending = FakePendingRegistry()496        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))497        val manifest = buildSignedDeviceManifest(498            issuerDeviceId = "vouched-issuer",499            devices = listOf(500                ManifestDeviceEntry(501                    deviceId = "onward-mesh-device",502                    deviceName = "Onward mesh device",503                    deviceType = "extension",504                    longTermPublicKeyHex = "aa".repeat(32),505                    signingPublicKeyHex = "bb".repeat(32),506                    relayUrl = meshRelay,507                    pairedAt = 44L,508                ),509            ),510            signingPrivateKey = issuerSigning.privateKey,511        )512513        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })514515        assertNull(paired.get("onward-mesh-device"))516        assertEquals(0, pending.devices.size)517        master.fill(0)518    }519520    @Test fun `a self asserted manifest issuer cannot override the authenticated peer`() = runBlocking {521        val repo = VaultRepository(FakeStorage())522        repo.createVault("correct horse")523        val master = repo.syncMasterKey()!!524        val claimedSigning = deriveSyncSigningKeypair(master, "claimed-issuer")525        val paired = FakeDeviceRegistry(526            listOf(527                PairedDevice(528                    deviceId = "claimed-issuer",529                    deviceName = "Claimed Browser",530                    deviceType = "extension",531                    longTermPublicKeyHex = "11".repeat(32),532                    signingPublicKeyHex = pubkeyToHex(claimedSigning.publicKeyRaw),533                    trustSource = "direct",534                    pairedAt = 1L,535                ),536                PairedDevice(537                    deviceId = "authenticated-peer",538                    deviceName = "Authenticated Phone",539                    deviceType = "android",540                    longTermPublicKeyHex = "22".repeat(32),541                    signingPublicKeyHex = "33".repeat(32),542                    trustSource = "direct",543                    pairedAt = 2L,544                ),545            ),546        )547        val pending = FakePendingRegistry()548        val adapter = VaultSyncAdapter(549            repo,550            ourDeviceId = "android-self",551            pairedDevices = paired,552            pendingVouched = pending,553            localCredentials = localCredentials("android-self"),554        )555        val manifest = buildSignedDeviceManifest(556            issuerDeviceId = "claimed-issuer",557            devices = listOf(558                ManifestDeviceEntry(559                    deviceId = "smuggled-device",560                    deviceName = "Smuggled",561                    deviceType = "extension",562                    longTermPublicKeyHex = "aa".repeat(32),563                    signingPublicKeyHex = "bb".repeat(32),564                    relayUrl = meshRelay,565                    pairedAt = 44L,566                ),567            ),568            signingPrivateKey = claimedSigning.privateKey,569        )570571        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x22 })572573        assertEquals(0, pending.devices.size)574575        // Control: the same manifest over the claimed issuer's OWN session does576        // admit the device. Without it the assertion above could pass for any577        // reason — a malformed body, a bad signature, a dead code path.578        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })579        assertEquals("vouched", paired.get("smuggled-device")?.trustSource)580        assertTrue(pending.devices.isEmpty())581        master.fill(0)582    }583584    @Test fun `a revoked long term key cannot walk back in under a fresh deviceId`() = runBlocking {585        val repo = VaultRepository(FakeStorage())586        repo.createVault("correct horse")587        val master = repo.syncMasterKey()!!588        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")589        val stolenKey = "dd".repeat(32)590        val paired = FakeDeviceRegistry(591            listOf(592                PairedDevice(593                    deviceId = "phone-issuer",594                    deviceName = "Pixel",595                    deviceType = "android",596                    longTermPublicKeyHex = "11".repeat(32),597                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),598                    trustSource = "direct",599                    pairedAt = 1L,600                ),601                PairedDevice(602                    deviceId = "stolen-laptop",603                    deviceName = "Old Laptop",604                    deviceType = "extension",605                    longTermPublicKeyHex = stolenKey,606                    signingPublicKeyHex = "ee".repeat(32),607                    trustSource = "direct",608                    pairedAt = 2L,609                ),610            ),611        )612        val pending = FakePendingRegistry()613        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))614615        adapter.applyIncomingDeviceManifest(616            buildSignedDeviceManifest(617                issuerDeviceId = "phone-issuer",618                devices = emptyList(),619                signingPrivateKey = issuerSigning.privateKey,620                revoked = listOf(621                    DeviceRevocation(622                        deviceId = "stolen-laptop",623                        longTermPublicKeyHex = stolenKey,624                        revokedAt = System.currentTimeMillis(),625                        revokedByDeviceId = "phone-issuer",626                    ),627                ),628            ),629            ByteArray(32) { 0x11 },630        )631        assertNull(paired.get("stolen-laptop"))632633        // deviceId is the issuer's to choose, so re-vouching the same key under634        // a new one is free. Terminality has to follow the key, not the label.635        adapter.applyIncomingDeviceManifest(636            buildSignedDeviceManifest(637                issuerDeviceId = "phone-issuer",638                devices = listOf(639                    ManifestDeviceEntry(640                        deviceId = "stolen-laptop-mk2",641                        deviceName = "New Laptop",642                        deviceType = "extension",643                        longTermPublicKeyHex = stolenKey,644                        signingPublicKeyHex = "ee".repeat(32),645                        relayUrl = meshRelay,646                        pairedAt = System.currentTimeMillis(),647                    ),648                ),649                signingPrivateKey = issuerSigning.privateKey,650            ),651            ByteArray(32) { 0x11 },652        )653        assertEquals(0, pending.devices.size)654        assertNull(paired.get("stolen-laptop-mk2"))655656        // Control: the same fresh id carrying a key that was never revoked657        // queues normally, so the rejection above is the key check, not the id.658        adapter.applyIncomingDeviceManifest(659            buildSignedDeviceManifest(660                issuerDeviceId = "phone-issuer",661                devices = listOf(662                    ManifestDeviceEntry(663                        deviceId = "stolen-laptop-mk2",664                        deviceName = "New Laptop",665                        deviceType = "extension",666                        longTermPublicKeyHex = "99".repeat(32),667                        signingPublicKeyHex = "ee".repeat(32),668                        relayUrl = meshRelay,669                        pairedAt = System.currentTimeMillis(),670                    ),671                ),672                signingPrivateKey = issuerSigning.privateKey,673            ),674            ByteArray(32) { 0x11 },675        )676        assertEquals("vouched", paired.get("stolen-laptop-mk2")?.trustSource)677        assertTrue(pending.devices.isEmpty())678        master.fill(0)679    }680681    @Test fun `direct and vouched peers reject long term and signing key rotation`() = runBlocking {682        val repo = VaultRepository(FakeStorage())683        repo.createVault("correct horse")684        val master = repo.syncMasterKey()!!685        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")686        val revokedKey = "dd".repeat(32)687        val paired = FakeDeviceRegistry(688            listOf(689                PairedDevice(690                    deviceId = "phone-issuer",691                    deviceName = "Pixel",692                    deviceType = "android",693                    longTermPublicKeyHex = "11".repeat(32),694                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),695                    trustSource = "direct",696                    pairedAt = 1L,697                ),698                PairedDevice(699                    deviceId = "trusted-tablet",700                    deviceName = "Tablet",701                    deviceType = "android",702                    longTermPublicKeyHex = "77".repeat(32),703                    signingPublicKeyHex = "ee".repeat(32),704                    trustSource = "direct",705                    pairedAt = 2L,706                ),707                PairedDevice(708                    deviceId = "vouched-laptop",709                    deviceName = "Laptop",710                    deviceType = "extension",711                    longTermPublicKeyHex = "66".repeat(32),712                    signingPublicKeyHex = "aa".repeat(32),713                    trustSource = "vouched",714                    pairedAt = 3L,715                ),716            ),717        )718        val adapter = VaultSyncAdapter(719            repo,720            ourDeviceId = "android-self",721            pairedDevices = paired,722            pendingVouched = FakePendingRegistry(),723            localCredentials = localCredentials("android-self"),724        )725726        adapter.applyIncomingDeviceManifest(727            buildSignedDeviceManifest(728                issuerDeviceId = "phone-issuer",729                devices = emptyList(),730                signingPrivateKey = issuerSigning.privateKey,731                revoked = listOf(732                    DeviceRevocation(733                        deviceId = "stolen-laptop",734                        longTermPublicKeyHex = revokedKey,735                        revokedAt = System.currentTimeMillis(),736                        revokedByDeviceId = "phone-issuer",737                    ),738                ),739            ),740            ByteArray(32) { 0x11 },741        )742743        // Re-admission dressed as a key rotation on a device we already trust.744        adapter.applyIncomingDeviceManifest(745            buildSignedDeviceManifest(746                issuerDeviceId = "phone-issuer",747                devices = listOf(748                    ManifestDeviceEntry(749                        deviceId = "trusted-tablet",750                        deviceName = "Tablet",751                        deviceType = "android",752                        longTermPublicKeyHex = revokedKey,753                        signingPublicKeyHex = "ff".repeat(32),754                        pairedAt = 2L,755                    ),756                    ManifestDeviceEntry(757                        deviceId = "vouched-laptop",758                        deviceName = "Laptop",759                        deviceType = "extension",760                        longTermPublicKeyHex = "55".repeat(32),761                        signingPublicKeyHex = "bb".repeat(32),762                        relayUrl = "wss://relay.peachpasswords.com",763                        pairedAt = 3L,764                    ),765                ),766                signingPrivateKey = issuerSigning.privateKey,767            ),768            ByteArray(32) { 0x11 },769        )770        assertEquals("77".repeat(32), paired.get("trusted-tablet")?.longTermPublicKeyHex)771        assertEquals("ee".repeat(32), paired.get("trusted-tablet")?.signingPublicKeyHex)772        assertEquals("66".repeat(32), paired.get("vouched-laptop")?.longTermPublicKeyHex)773        assertEquals("aa".repeat(32), paired.get("vouched-laptop")?.signingPublicKeyHex)774        master.fill(0)775    }776777    /** Pins the helper the manifest loop and SyncViewModel.confirmVouchedDevice share. */778    @Test fun `revocation matches on id or key but never on the empty-key sentinel`() {779        val registry = FakeDeviceRegistry()780        registry.mergeRevocations(781            listOf(782                DeviceRevocation("gone", "dd".repeat(32), 1L, "issuer"),783                DeviceRevocation("keyless", NO_KEY_SENTINEL, 2L, "issuer"),784            ),785        )786        assertTrue(registry.isRevoked("gone"))787        assertTrue(registry.isRevoked("fresh-id", "DD".repeat(32)))788        assertTrue(registry.isRevoked("keyless"))789        assertFalse(registry.isRevoked("fresh-id", "99".repeat(32)))790        // A device that genuinely never stored a key must not inherit the791        // sentinel's revocation.792        assertFalse(registry.isRevoked("innocent", NO_KEY_SENTINEL))793    }794795    @Test fun `public key decoder requires exactly 32 bytes`() {796        assertEquals(32, hexToPubkey("ab".repeat(32)).size)797        assertTrue(runCatching { hexToPubkey("ab".repeat(31)) }.isFailure)798        assertTrue(runCatching { hexToPubkey("ab".repeat(33)) }.isFailure)799        assertEquals(64, hexToBytes("ab".repeat(64)).size)800    }801802    @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    }854855856    @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    }876877878    @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    }925926}