VaultSyncAdapterTest.kt

33.1 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() { slotA = null; slotB = null; ver = 0; settings = VaultSettings() }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        private val byId = devices.associateBy { it.deviceId }.toMutableMap()43        private val revocations = mutableListOf<DeviceRevocation>()44        override fun getAll(): List<PairedDevice> = byId.values.toList()45        override fun get(id: String): PairedDevice? = byId[id]46        override fun upsert(device: PairedDevice) { byId[device.deviceId] = device }47        override fun remove(deviceId: String) { byId.remove(deviceId) }48        override fun listRevocations(): List<DeviceRevocation> = revocations.toList()49        override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {50            if (failManifestCommit) return false51            val nextRevocations = mergeRevocationRecords(revocations, batch.incomingRevocations).records.toMutableList()52            val nextDevices = byId.toMutableMap()53            batch.removals.forEach(nextDevices::remove)54            batch.upserts.forEach { nextDevices[it.deviceId] = it }55            revocations.clear()56            revocations += nextRevocations57            byId.clear()58            byId.putAll(nextDevices)59            return true60        }61        override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {62            val merged = mergeRevocationRecords(revocations, incoming)63            revocations.clear()64            revocations += merged.records65            return merged.admitted.map { it.deviceId }66        }67        override fun clearRevocation(deviceId: String) {68            revocations.removeAll { it.deviceId == deviceId }69        }70    }7172    private class FakePendingRegistry : PendingVouchedRegistry {73        val devices = mutableListOf<PendingVouchedDevice>()74        override fun getAll(): List<PendingVouchedDevice> = devices.toList()75        override fun upsert(device: PendingVouchedDevice) {76            devices.removeAll { it.deviceId == device.deviceId }77            devices += device78        }79        override fun remove(id: String) { devices.removeAll { it.deviceId == id } }80    }8182    private fun localCredentials(deviceId: String) = randomLocalIdentityCredentials(deviceId)8384    private fun newAdapter(): Pair<VaultRepository, VaultSyncAdapter> {85        val repo = VaultRepository(FakeStorage())86        runBlocking { repo.createVault("correct horse") }87        return repo to VaultSyncAdapter(88            repo,89            ourDeviceId = "android-test",90            localCredentials = localCredentials("android-test"),91        )92    }9394    @Test fun manifest_and_vault_id_reflect_the_vault() = runBlocking {95        val (repo, adapter) = newAdapter()96        val e = repo.addEntry(VaultEntry(id = "", title = "GitHub", createdAt = 0, modifiedAt = 0, password = "p"))97        val manifest = adapter.buildEntryManifest()98        assertEquals(setOf(e.id), manifest.keys)99        assertTrue(adapter.computeVaultId().length == 64) // blake3-256 hex100    }101102    @Test fun envelope_round_trips_within_the_vault() = runBlocking {103        val (repo, adapter) = newAdapter()104        val e = repo.addEntry(VaultEntry(id = "", title = "Mail", createdAt = 0, modifiedAt = 0, password = "secret"))105        val envelopes = adapter.getEncryptedEntries(listOf(e.id))106        assertTrue(envelopes.containsKey(e.id))107        // Re-applying the same envelope is a safe no-op (same mtime, no overwrite).108        adapter.applyEntries(envelopes)109        assertEquals(1, repo.getEntries().size)110    }111112    @Test fun swapped_envelope_is_rejected_by_id_binding() = runBlocking {113        val (repo, adapter) = newAdapter()114        val e = repo.addEntry(VaultEntry(id = "", title = "Bank", createdAt = 0, modifiedAt = 0, password = "x"))115        val blob = adapter.getEncryptedEntries(listOf(e.id)).getValue(e.id)116        // Present the ciphertext under a different id — the decrypted entry.id117        // won't match, so it must be dropped, not poison a new slot.118        adapter.applyEntries(mapOf("attacker-chosen-id" to blob))119        assertNull(repo.getEntry("attacker-chosen-id"))120        assertEquals(1, repo.getEntries().size)121    }122123    // HKDF separator (coordinated with peach-browser): an envelope minted under124    // the OLD, unseparated info (`entryId + suffix`) must no longer decrypt. This125    // locks in the conscious wire break and asserts byte-for-byte parity with the126    // browser's matching `legacy_info_envelope_fails_closed` test.127    @Test fun legacy_info_envelope_fails_closed() = runBlocking {128        val (repo, adapter) = newAdapter()129        val master = repo.syncMasterKey()!!130        val entryId = "11111111-2222-4333-8444-555555555555"131        val entry = VaultEntry(id = entryId, title = "LegacyOnly", createdAt = 0, modifiedAt = 0, password = "pw")132133        // Legacy info: no U+0000 separator.134        val legacyInfo = (entryId + "sync-entry-v1").toByteArray(Charsets.UTF_8)135        val gen = org.bouncycastle.crypto.generators.HKDFBytesGenerator(org.bouncycastle.crypto.digests.SHA256Digest())136        gen.init(org.bouncycastle.crypto.params.HKDFParameters(master, ByteArray(0), legacyInfo))137        val key = ByteArray(32).also { gen.generateBytes(it, 0, it.size) }138139        val json = kotlinx.serialization.json.Json { encodeDefaults = false; ignoreUnknownKeys = true }140        val plaintext = json.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)141        val nonce = ByteArray(12).also { java.security.SecureRandom().nextBytes(it) }142        val cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding")143        cipher.init(144            javax.crypto.Cipher.ENCRYPT_MODE,145            javax.crypto.spec.SecretKeySpec(key, "AES"),146            javax.crypto.spec.GCMParameterSpec(128, nonce),147        )148        cipher.updateAAD("peach-sync-entry-v1".toByteArray(Charsets.UTF_8))149        val ct = cipher.doFinal(plaintext)150        val legacyEnvelope = java.util.Base64.getEncoder().encodeToString(nonce + ct)151152        adapter.applyEntries(mapOf(entryId to legacyEnvelope))153        // Patched adapter derives with the separated info → decrypt fails → dropped.154        assertNull(repo.getEntry(entryId))155    }156157    @Test fun signed_device_manifest_round_trips_through_canonical_signature() = runBlocking {158        val master = ByteArray(32) { it.toByte() }159        val signing = deriveSyncSigningKeypair(master, "extension-issuer")160        val manifest = buildSignedDeviceManifest(161            issuerDeviceId = "extension-issuer",162            devices = listOf(163                ManifestDeviceEntry(164                    deviceId = "android-peer",165                    deviceName = "Phone",166                    deviceType = "android",167                    longTermPublicKeyHex = "aa".repeat(32),168                    signingPublicKeyHex = "bb".repeat(32),169                    pairedAt = 123L,170                ),171            ),172            signingPrivateKey = signing.privateKey,173            nowMs = 1_000L,174        )175176        val verified = verifyDeviceManifest(177            manifest,178            signing.publicKeyRaw,179            nowMs = 1_000L,180        )181182        assertEquals("extension-issuer", verified?.issuerDeviceId)183        assertEquals("android-peer", verified?.devices?.single()?.deviceId)184        assertTrue(verifyDeviceManifest(manifest.copy(signatureHex = "00".repeat(64)), signing.publicKeyRaw, nowMs = 1_000L) == null)185    }186187    @Test fun `vouched peer revocation evicts the device and permanently blocks re-vouching`() = runBlocking {188        val repo = VaultRepository(FakeStorage())189        repo.createVault("correct horse")190        val master = repo.syncMasterKey()!!191        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")192        val paired = FakeDeviceRegistry(193            listOf(194                PairedDevice(195                    deviceId = "extension-issuer",196                    deviceName = "Peach Browser",197                    deviceType = "extension",198                    longTermPublicKeyHex = "11".repeat(32),199                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),200                    trustSource = "vouched",201                    pairedAt = 1L,202                ),203                PairedDevice(204                    deviceId = "stolen-laptop",205                    deviceName = "Old Laptop",206                    deviceType = "extension",207                    longTermPublicKeyHex = "dd".repeat(32),208                    signingPublicKeyHex = "ee".repeat(32),209                    trustSource = "direct",210                    pairedAt = 2L,211                ),212            ),213        )214        val pending = FakePendingRegistry()215        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))216217        val revocation = buildSignedDeviceManifest(218            issuerDeviceId = "extension-issuer",219            devices = emptyList(),220            signingPrivateKey = issuerSigning.privateKey,221            revoked = listOf(222                DeviceRevocation(223                    deviceId = "stolen-laptop",224                    longTermPublicKeyHex = "dd".repeat(32),225                    revokedAt = System.currentTimeMillis(),226                    revokedByDeviceId = "extension-issuer",227                ),228            ),229        )230        adapter.applyIncomingDeviceManifest(revocation, ByteArray(32) { 0x11 })231232        assertNull(paired.get("stolen-laptop"))233234        // A later manifest vouches it back with a fresh pairedAt — exactly the235        // resurrection a timestamp-ordered design would allow.236        val revouch = buildSignedDeviceManifest(237            issuerDeviceId = "extension-issuer",238            devices = listOf(239                ManifestDeviceEntry(240                    deviceId = "stolen-laptop",241                    deviceName = "Old Laptop",242                    deviceType = "extension",243                    longTermPublicKeyHex = "dd".repeat(32),244                    signingPublicKeyHex = "ee".repeat(32),245                    pairedAt = System.currentTimeMillis() + 60_000L,246                ),247            ),248            signingPrivateKey = issuerSigning.privateKey,249        )250        adapter.applyIncomingDeviceManifest(revouch, ByteArray(32) { 0x11 })251252        assertNull(paired.get("stolen-laptop"))253        assertEquals(0, pending.devices.size)254        master.fill(0)255    }256257    @Test fun `a peer cannot revoke this device`() = runBlocking {258        val repo = VaultRepository(FakeStorage())259        repo.createVault("correct horse")260        val master = repo.syncMasterKey()!!261        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")262        val paired = FakeDeviceRegistry(263            listOf(264                PairedDevice(265                    deviceId = "extension-issuer",266                    deviceName = "Peach Browser",267                    deviceType = "extension",268                    longTermPublicKeyHex = "11".repeat(32),269                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),270                    trustSource = "direct",271                    pairedAt = 1L,272                ),273            ),274        )275        val pending = FakePendingRegistry()276        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))277278        val selfRevoke = buildSignedDeviceManifest(279            issuerDeviceId = "extension-issuer",280            devices = emptyList(),281            signingPrivateKey = issuerSigning.privateKey,282            revoked = listOf(283                DeviceRevocation(284                    deviceId = "android-self",285                    longTermPublicKeyHex = "ff".repeat(32),286                    revokedAt = System.currentTimeMillis(),287                    revokedByDeviceId = "extension-issuer",288                ),289            ),290        )291        adapter.applyIncomingDeviceManifest(selfRevoke, ByteArray(32) { 0x11 })292293        assertTrue(paired.listRevocations().none { it.deviceId == "android-self" })294        master.fill(0)295    }296297    @Test fun incoming_extension_manifest_auto_admits_routable_same_vault_peer() = runBlocking {298        val repo = VaultRepository(FakeStorage())299        repo.createVault("correct horse")300        val master = repo.syncMasterKey()!!301        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")302        val paired = FakeDeviceRegistry(303            listOf(304                PairedDevice(305                    deviceId = "extension-issuer",306                    deviceName = "Peach Browser",307                    deviceType = "extension",308                    longTermPublicKeyHex = "11".repeat(32),309                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),310                    trustSource = "direct",311                    pairedAt = 1L,312                ),313            ),314        )315        val pending = FakePendingRegistry()316        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))317        val manifest = buildSignedDeviceManifest(318            issuerDeviceId = "extension-issuer",319            devices = listOf(320                ManifestDeviceEntry(321                    deviceId = "new-phone",322                    deviceName = "June's Phone",323                    deviceType = "android",324                    longTermPublicKeyHex = "aa".repeat(32),325                    signingPublicKeyHex = "bb".repeat(32),326                    relayUrl = meshRelay,327                    pairedAt = 44L,328                ),329            ),330            signingPrivateKey = issuerSigning.privateKey,331        )332333        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })334335        val admitted = paired.get("new-phone")336        assertEquals("vouched", admitted?.trustSource)337        assertEquals(meshRelay, admitted?.relayUrl)338        assertTrue(admitted?.rendezvousSecretHex?.matches(Regex("[0-9a-f]{64}")) == true)339        assertTrue(pending.devices.isEmpty())340        master.fill(0)341    }342343    @Test fun failed_manifest_commit_restores_pending_before_trust_can_land() = runBlocking {344        val repo = VaultRepository(FakeStorage())345        repo.createVault("correct horse")346        val master = repo.syncMasterKey()!!347        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")348        val paired = FakeDeviceRegistry(349            listOf(350                PairedDevice(351                    deviceId = "extension-issuer",352                    deviceName = "Peach Browser",353                    deviceType = "extension",354                    longTermPublicKeyHex = "11".repeat(32),355                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),356                    trustSource = "direct",357                    pairedAt = 1L,358                ),359            ),360        ).also { it.failManifestCommit = true }361        val pending = FakePendingRegistry().also {362            it.upsert(363                PendingVouchedDevice(364                    deviceId = "new-phone",365                    deviceName = "June's Phone",366                    deviceType = "android",367                    longTermPublicKeyHex = "aa".repeat(32),368                    signingPublicKeyHex = "bb".repeat(32),369                    pairedAt = 44L,370                    receivedAt = 45L,371                    vouchedByDeviceId = "extension-issuer",372                ),373            )374        }375        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))376        val manifest = buildSignedDeviceManifest(377            issuerDeviceId = "extension-issuer",378            devices = listOf(379                ManifestDeviceEntry(380                    deviceId = "new-phone",381                    deviceName = "June's Phone",382                    deviceType = "android",383                    longTermPublicKeyHex = "aa".repeat(32),384                    signingPublicKeyHex = "bb".repeat(32),385                    relayUrl = meshRelay,386                    pairedAt = 44L,387                ),388            ),389            signingPrivateKey = issuerSigning.privateKey,390        )391392        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })393394        assertNull("failed registry commit must not install trust", paired.get("new-phone"))395        assertEquals("pending introduction is restored for retry", 1, pending.devices.size)396        master.fill(0)397    }398    /**399     * Browser parity (`applyVerifiedPeerManifest`): trust is keyed on the issuer400     * being DIRECTLY paired, not on it being a browser. Android used to require401     * deviceType == "extension", which silently killed mesh propagation between402     * native devices — the case the mesh exists for now that phones are the403     * listening side.404     */405    @Test fun `a manifest from a directly paired phone is accepted`() = runBlocking {406        val repo = VaultRepository(FakeStorage())407        repo.createVault("correct horse")408        val master = repo.syncMasterKey()!!409        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")410        val paired = FakeDeviceRegistry(411            listOf(412                PairedDevice(413                    deviceId = "phone-issuer",414                    deviceName = "Other Phone",415                    deviceType = "android",416                    longTermPublicKeyHex = "11".repeat(32),417                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),418                    trustSource = "direct",419                    pairedAt = 1L,420                ),421            ),422        )423        val pending = FakePendingRegistry()424        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))425        val manifest = buildSignedDeviceManifest(426            issuerDeviceId = "phone-issuer",427            devices = listOf(428                ManifestDeviceEntry(429                    deviceId = "laptop-b",430                    deviceName = "Laptop B",431                    deviceType = "extension",432                    longTermPublicKeyHex = "aa".repeat(32),433                    signingPublicKeyHex = "bb".repeat(32),434                    relayUrl = meshRelay,435                    pairedAt = 44L,436                ),437            ),438            signingPrivateKey = issuerSigning.privateKey,439        )440441        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })442443        assertEquals("vouched", paired.get("laptop-b")?.trustSource)444        assertEquals(meshRelay, paired.get("laptop-b")?.relayUrl)445        assertTrue(pending.devices.isEmpty())446        master.fill(0)447    }448449    /** A vouched peer cannot extend the trust graph beyond one hop. */450    @Test fun `a vouched issuer cannot introduce further mesh devices`() = runBlocking {451        val repo = VaultRepository(FakeStorage())452        repo.createVault("correct horse")453        val master = repo.syncMasterKey()!!454        val issuerSigning = deriveSyncSigningKeypair(master, "vouched-issuer")455        val paired = FakeDeviceRegistry(456            listOf(457                PairedDevice(458                    deviceId = "vouched-issuer",459                    deviceName = "Vouched Device",460                    deviceType = "extension",461                    longTermPublicKeyHex = "11".repeat(32),462                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),463                    trustSource = "vouched",464                    vouchDepth = MAX_VOUCH_DEPTH,465                    pairedAt = 1L,466                ),467            ),468        )469        val pending = FakePendingRegistry()470        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))471        val manifest = buildSignedDeviceManifest(472            issuerDeviceId = "vouched-issuer",473            devices = listOf(474                ManifestDeviceEntry(475                    deviceId = "onward-mesh-device",476                    deviceName = "Onward mesh device",477                    deviceType = "extension",478                    longTermPublicKeyHex = "aa".repeat(32),479                    signingPublicKeyHex = "bb".repeat(32),480                    relayUrl = meshRelay,481                    pairedAt = 44L,482                ),483            ),484            signingPrivateKey = issuerSigning.privateKey,485        )486487        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })488489        assertNull(paired.get("onward-mesh-device"))490        assertEquals(0, pending.devices.size)491        master.fill(0)492    }493494    @Test fun `a self asserted manifest issuer cannot override the authenticated peer`() = runBlocking {495        val repo = VaultRepository(FakeStorage())496        repo.createVault("correct horse")497        val master = repo.syncMasterKey()!!498        val claimedSigning = deriveSyncSigningKeypair(master, "claimed-issuer")499        val paired = FakeDeviceRegistry(500            listOf(501                PairedDevice(502                    deviceId = "claimed-issuer",503                    deviceName = "Claimed Browser",504                    deviceType = "extension",505                    longTermPublicKeyHex = "11".repeat(32),506                    signingPublicKeyHex = pubkeyToHex(claimedSigning.publicKeyRaw),507                    trustSource = "direct",508                    pairedAt = 1L,509                ),510                PairedDevice(511                    deviceId = "authenticated-peer",512                    deviceName = "Authenticated Phone",513                    deviceType = "android",514                    longTermPublicKeyHex = "22".repeat(32),515                    signingPublicKeyHex = "33".repeat(32),516                    trustSource = "direct",517                    pairedAt = 2L,518                ),519            ),520        )521        val pending = FakePendingRegistry()522        val adapter = VaultSyncAdapter(523            repo,524            ourDeviceId = "android-self",525            pairedDevices = paired,526            pendingVouched = pending,527            localCredentials = localCredentials("android-self"),528        )529        val manifest = buildSignedDeviceManifest(530            issuerDeviceId = "claimed-issuer",531            devices = listOf(532                ManifestDeviceEntry(533                    deviceId = "smuggled-device",534                    deviceName = "Smuggled",535                    deviceType = "extension",536                    longTermPublicKeyHex = "aa".repeat(32),537                    signingPublicKeyHex = "bb".repeat(32),538                    relayUrl = meshRelay,539                    pairedAt = 44L,540                ),541            ),542            signingPrivateKey = claimedSigning.privateKey,543        )544545        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x22 })546547        assertEquals(0, pending.devices.size)548549        // Control: the same manifest over the claimed issuer's OWN session does550        // admit the device. Without it the assertion above could pass for any551        // reason — a malformed body, a bad signature, a dead code path.552        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })553        assertEquals("vouched", paired.get("smuggled-device")?.trustSource)554        assertTrue(pending.devices.isEmpty())555        master.fill(0)556    }557558    @Test fun `a revoked long term key cannot walk back in under a fresh deviceId`() = runBlocking {559        val repo = VaultRepository(FakeStorage())560        repo.createVault("correct horse")561        val master = repo.syncMasterKey()!!562        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")563        val stolenKey = "dd".repeat(32)564        val paired = FakeDeviceRegistry(565            listOf(566                PairedDevice(567                    deviceId = "phone-issuer",568                    deviceName = "Pixel",569                    deviceType = "android",570                    longTermPublicKeyHex = "11".repeat(32),571                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),572                    trustSource = "direct",573                    pairedAt = 1L,574                ),575                PairedDevice(576                    deviceId = "stolen-laptop",577                    deviceName = "Old Laptop",578                    deviceType = "extension",579                    longTermPublicKeyHex = stolenKey,580                    signingPublicKeyHex = "ee".repeat(32),581                    trustSource = "direct",582                    pairedAt = 2L,583                ),584            ),585        )586        val pending = FakePendingRegistry()587        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))588589        adapter.applyIncomingDeviceManifest(590            buildSignedDeviceManifest(591                issuerDeviceId = "phone-issuer",592                devices = emptyList(),593                signingPrivateKey = issuerSigning.privateKey,594                revoked = listOf(595                    DeviceRevocation(596                        deviceId = "stolen-laptop",597                        longTermPublicKeyHex = stolenKey,598                        revokedAt = System.currentTimeMillis(),599                        revokedByDeviceId = "phone-issuer",600                    ),601                ),602            ),603            ByteArray(32) { 0x11 },604        )605        assertNull(paired.get("stolen-laptop"))606607        // deviceId is the issuer's to choose, so re-vouching the same key under608        // a new one is free. Terminality has to follow the key, not the label.609        adapter.applyIncomingDeviceManifest(610            buildSignedDeviceManifest(611                issuerDeviceId = "phone-issuer",612                devices = listOf(613                    ManifestDeviceEntry(614                        deviceId = "stolen-laptop-mk2",615                        deviceName = "New Laptop",616                        deviceType = "extension",617                        longTermPublicKeyHex = stolenKey,618                        signingPublicKeyHex = "ee".repeat(32),619                        relayUrl = meshRelay,620                        pairedAt = System.currentTimeMillis(),621                    ),622                ),623                signingPrivateKey = issuerSigning.privateKey,624            ),625            ByteArray(32) { 0x11 },626        )627        assertEquals(0, pending.devices.size)628        assertNull(paired.get("stolen-laptop-mk2"))629630        // Control: the same fresh id carrying a key that was never revoked631        // queues normally, so the rejection above is the key check, not the id.632        adapter.applyIncomingDeviceManifest(633            buildSignedDeviceManifest(634                issuerDeviceId = "phone-issuer",635                devices = listOf(636                    ManifestDeviceEntry(637                        deviceId = "stolen-laptop-mk2",638                        deviceName = "New Laptop",639                        deviceType = "extension",640                        longTermPublicKeyHex = "99".repeat(32),641                        signingPublicKeyHex = "ee".repeat(32),642                        relayUrl = meshRelay,643                        pairedAt = System.currentTimeMillis(),644                    ),645                ),646                signingPrivateKey = issuerSigning.privateKey,647            ),648            ByteArray(32) { 0x11 },649        )650        assertEquals("vouched", paired.get("stolen-laptop-mk2")?.trustSource)651        assertTrue(pending.devices.isEmpty())652        master.fill(0)653    }654655    @Test fun `direct peer rejects long term and signing key rotation`() = runBlocking {656        val repo = VaultRepository(FakeStorage())657        repo.createVault("correct horse")658        val master = repo.syncMasterKey()!!659        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")660        val revokedKey = "dd".repeat(32)661        val paired = FakeDeviceRegistry(662            listOf(663                PairedDevice(664                    deviceId = "phone-issuer",665                    deviceName = "Pixel",666                    deviceType = "android",667                    longTermPublicKeyHex = "11".repeat(32),668                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),669                    trustSource = "direct",670                    pairedAt = 1L,671                ),672                PairedDevice(673                    deviceId = "trusted-tablet",674                    deviceName = "Tablet",675                    deviceType = "android",676                    longTermPublicKeyHex = "77".repeat(32),677                    signingPublicKeyHex = "ee".repeat(32),678                    trustSource = "direct",679                    pairedAt = 2L,680                ),681            ),682        )683        val adapter = VaultSyncAdapter(684            repo,685            ourDeviceId = "android-self",686            pairedDevices = paired,687            pendingVouched = FakePendingRegistry(),688            localCredentials = localCredentials("android-self"),689        )690691        adapter.applyIncomingDeviceManifest(692            buildSignedDeviceManifest(693                issuerDeviceId = "phone-issuer",694                devices = emptyList(),695                signingPrivateKey = issuerSigning.privateKey,696                revoked = listOf(697                    DeviceRevocation(698                        deviceId = "stolen-laptop",699                        longTermPublicKeyHex = revokedKey,700                        revokedAt = System.currentTimeMillis(),701                        revokedByDeviceId = "phone-issuer",702                    ),703                ),704            ),705            ByteArray(32) { 0x11 },706        )707708        // Re-admission dressed as a key rotation on a device we already trust.709        adapter.applyIncomingDeviceManifest(710            buildSignedDeviceManifest(711                issuerDeviceId = "phone-issuer",712                devices = listOf(713                    ManifestDeviceEntry(714                        deviceId = "trusted-tablet",715                        deviceName = "Tablet",716                        deviceType = "android",717                        longTermPublicKeyHex = revokedKey,718                        signingPublicKeyHex = "ff".repeat(32),719                        pairedAt = 2L,720                    ),721                ),722                signingPrivateKey = issuerSigning.privateKey,723            ),724            ByteArray(32) { 0x11 },725        )726        assertEquals("77".repeat(32), paired.get("trusted-tablet")?.longTermPublicKeyHex)727        assertEquals("ee".repeat(32), paired.get("trusted-tablet")?.signingPublicKeyHex)728        master.fill(0)729    }730731    /** Pins the helper the manifest loop and SyncViewModel.confirmVouchedDevice share. */732    @Test fun `revocation matches on id or key but never on the empty-key sentinel`() {733        val registry = FakeDeviceRegistry()734        registry.mergeRevocations(735            listOf(736                DeviceRevocation("gone", "dd".repeat(32), 1L, "issuer"),737                DeviceRevocation("keyless", NO_KEY_SENTINEL, 2L, "issuer"),738            ),739        )740        assertTrue(registry.isRevoked("gone"))741        assertTrue(registry.isRevoked("fresh-id", "DD".repeat(32)))742        assertTrue(registry.isRevoked("keyless"))743        assertFalse(registry.isRevoked("fresh-id", "99".repeat(32)))744        // A device that genuinely never stored a key must not inherit the745        // sentinel's revocation.746        assertFalse(registry.isRevoked("innocent", NO_KEY_SENTINEL))747    }748749    @Test fun `public key decoder requires exactly 32 bytes`() {750        assertEquals(32, hexToPubkey("ab".repeat(32)).size)751        assertTrue(runCatching { hexToPubkey("ab".repeat(31)) }.isFailure)752        assertTrue(runCatching { hexToPubkey("ab".repeat(33)) }.isFailure)753        assertEquals(64, hexToBytes("ab".repeat(64)).size)754    }755}