VaultSyncAdapterTest.kt

32.4 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 newAdapter(): Pair<VaultRepository, VaultSyncAdapter> {83        val repo = VaultRepository(FakeStorage())84        runBlocking { repo.createVault("correct horse") }85        return repo to VaultSyncAdapter(repo, ourDeviceId = "android-test")86    }8788    @Test fun manifest_and_vault_id_reflect_the_vault() = runBlocking {89        val (repo, adapter) = newAdapter()90        val e = repo.addEntry(VaultEntry(id = "", title = "GitHub", createdAt = 0, modifiedAt = 0, password = "p"))91        val manifest = adapter.buildEntryManifest()92        assertEquals(setOf(e.id), manifest.keys)93        assertTrue(adapter.computeVaultId().length == 64) // blake3-256 hex94    }9596    @Test fun envelope_round_trips_within_the_vault() = runBlocking {97        val (repo, adapter) = newAdapter()98        val e = repo.addEntry(VaultEntry(id = "", title = "Mail", createdAt = 0, modifiedAt = 0, password = "secret"))99        val envelopes = adapter.getEncryptedEntries(listOf(e.id))100        assertTrue(envelopes.containsKey(e.id))101        // Re-applying the same envelope is a safe no-op (same mtime, no overwrite).102        adapter.applyEntries(envelopes)103        assertEquals(1, repo.getEntries().size)104    }105106    @Test fun swapped_envelope_is_rejected_by_id_binding() = runBlocking {107        val (repo, adapter) = newAdapter()108        val e = repo.addEntry(VaultEntry(id = "", title = "Bank", createdAt = 0, modifiedAt = 0, password = "x"))109        val blob = adapter.getEncryptedEntries(listOf(e.id)).getValue(e.id)110        // Present the ciphertext under a different id — the decrypted entry.id111        // won't match, so it must be dropped, not poison a new slot.112        adapter.applyEntries(mapOf("attacker-chosen-id" to blob))113        assertNull(repo.getEntry("attacker-chosen-id"))114        assertEquals(1, repo.getEntries().size)115    }116117    // HKDF separator (coordinated with peach-browser): an envelope minted under118    // the OLD, unseparated info (`entryId + suffix`) must no longer decrypt. This119    // locks in the conscious wire break and asserts byte-for-byte parity with the120    // browser's matching `legacy_info_envelope_fails_closed` test.121    @Test fun legacy_info_envelope_fails_closed() = runBlocking {122        val (repo, adapter) = newAdapter()123        val master = repo.syncMasterKey()!!124        val entryId = "11111111-2222-4333-8444-555555555555"125        val entry = VaultEntry(id = entryId, title = "LegacyOnly", createdAt = 0, modifiedAt = 0, password = "pw")126127        // Legacy info: no U+0000 separator.128        val legacyInfo = (entryId + "sync-entry-v1").toByteArray(Charsets.UTF_8)129        val gen = org.bouncycastle.crypto.generators.HKDFBytesGenerator(org.bouncycastle.crypto.digests.SHA256Digest())130        gen.init(org.bouncycastle.crypto.params.HKDFParameters(master, ByteArray(0), legacyInfo))131        val key = ByteArray(32).also { gen.generateBytes(it, 0, it.size) }132133        val json = kotlinx.serialization.json.Json { encodeDefaults = false; ignoreUnknownKeys = true }134        val plaintext = json.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)135        val nonce = ByteArray(12).also { java.security.SecureRandom().nextBytes(it) }136        val cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding")137        cipher.init(138            javax.crypto.Cipher.ENCRYPT_MODE,139            javax.crypto.spec.SecretKeySpec(key, "AES"),140            javax.crypto.spec.GCMParameterSpec(128, nonce),141        )142        cipher.updateAAD("peach-sync-entry-v1".toByteArray(Charsets.UTF_8))143        val ct = cipher.doFinal(plaintext)144        val legacyEnvelope = java.util.Base64.getEncoder().encodeToString(nonce + ct)145146        adapter.applyEntries(mapOf(entryId to legacyEnvelope))147        // Patched adapter derives with the separated info → decrypt fails → dropped.148        assertNull(repo.getEntry(entryId))149    }150151    @Test fun signed_device_manifest_round_trips_through_canonical_signature() = runBlocking {152        val master = ByteArray(32) { it.toByte() }153        val signing = deriveSyncSigningKeypair(master, "extension-issuer")154        val manifest = buildSignedDeviceManifest(155            issuerDeviceId = "extension-issuer",156            devices = listOf(157                ManifestDeviceEntry(158                    deviceId = "android-peer",159                    deviceName = "Phone",160                    deviceType = "android",161                    longTermPublicKeyHex = "aa".repeat(32),162                    signingPublicKeyHex = "bb".repeat(32),163                    pairedAt = 123L,164                ),165            ),166            signingPrivateKey = signing.privateKey,167            nowMs = 1_000L,168        )169170        val verified = verifyDeviceManifest(171            manifest,172            signing.publicKeyRaw,173            nowMs = 1_000L,174        )175176        assertEquals("extension-issuer", verified?.issuerDeviceId)177        assertEquals("android-peer", verified?.devices?.single()?.deviceId)178        assertTrue(verifyDeviceManifest(manifest.copy(signatureHex = "00".repeat(64)), signing.publicKeyRaw, nowMs = 1_000L) == null)179    }180181    @Test fun `vouched peer revocation evicts the device and permanently blocks re-vouching`() = runBlocking {182        val repo = VaultRepository(FakeStorage())183        repo.createVault("correct horse")184        val master = repo.syncMasterKey()!!185        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")186        val paired = FakeDeviceRegistry(187            listOf(188                PairedDevice(189                    deviceId = "extension-issuer",190                    deviceName = "Peach Browser",191                    deviceType = "extension",192                    longTermPublicKeyHex = "11".repeat(32),193                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),194                    trustSource = "vouched",195                    pairedAt = 1L,196                ),197                PairedDevice(198                    deviceId = "stolen-laptop",199                    deviceName = "Old Laptop",200                    deviceType = "extension",201                    longTermPublicKeyHex = "dd".repeat(32),202                    signingPublicKeyHex = "ee".repeat(32),203                    trustSource = "direct",204                    pairedAt = 2L,205                ),206            ),207        )208        val pending = FakePendingRegistry()209        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)210211        val revocation = buildSignedDeviceManifest(212            issuerDeviceId = "extension-issuer",213            devices = emptyList(),214            signingPrivateKey = issuerSigning.privateKey,215            revoked = listOf(216                DeviceRevocation(217                    deviceId = "stolen-laptop",218                    longTermPublicKeyHex = "dd".repeat(32),219                    revokedAt = System.currentTimeMillis(),220                    revokedByDeviceId = "extension-issuer",221                ),222            ),223        )224        adapter.applyIncomingDeviceManifest(revocation, ByteArray(32) { 0x11 })225226        assertNull(paired.get("stolen-laptop"))227228        // A later manifest vouches it back with a fresh pairedAt — exactly the229        // resurrection a timestamp-ordered design would allow.230        val revouch = buildSignedDeviceManifest(231            issuerDeviceId = "extension-issuer",232            devices = listOf(233                ManifestDeviceEntry(234                    deviceId = "stolen-laptop",235                    deviceName = "Old Laptop",236                    deviceType = "extension",237                    longTermPublicKeyHex = "dd".repeat(32),238                    signingPublicKeyHex = "ee".repeat(32),239                    pairedAt = System.currentTimeMillis() + 60_000L,240                ),241            ),242            signingPrivateKey = issuerSigning.privateKey,243        )244        adapter.applyIncomingDeviceManifest(revouch, ByteArray(32) { 0x11 })245246        assertNull(paired.get("stolen-laptop"))247        assertEquals(0, pending.devices.size)248        master.fill(0)249    }250251    @Test fun `a peer cannot revoke this device`() = runBlocking {252        val repo = VaultRepository(FakeStorage())253        repo.createVault("correct horse")254        val master = repo.syncMasterKey()!!255        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")256        val paired = FakeDeviceRegistry(257            listOf(258                PairedDevice(259                    deviceId = "extension-issuer",260                    deviceName = "Peach Browser",261                    deviceType = "extension",262                    longTermPublicKeyHex = "11".repeat(32),263                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),264                    trustSource = "direct",265                    pairedAt = 1L,266                ),267            ),268        )269        val pending = FakePendingRegistry()270        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)271272        val selfRevoke = buildSignedDeviceManifest(273            issuerDeviceId = "extension-issuer",274            devices = emptyList(),275            signingPrivateKey = issuerSigning.privateKey,276            revoked = listOf(277                DeviceRevocation(278                    deviceId = "android-self",279                    longTermPublicKeyHex = "ff".repeat(32),280                    revokedAt = System.currentTimeMillis(),281                    revokedByDeviceId = "extension-issuer",282                ),283            ),284        )285        adapter.applyIncomingDeviceManifest(selfRevoke, ByteArray(32) { 0x11 })286287        assertTrue(paired.listRevocations().none { it.deviceId == "android-self" })288        master.fill(0)289    }290291    @Test fun incoming_extension_manifest_auto_admits_routable_same_vault_peer() = runBlocking {292        val repo = VaultRepository(FakeStorage())293        repo.createVault("correct horse")294        val master = repo.syncMasterKey()!!295        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")296        val paired = FakeDeviceRegistry(297            listOf(298                PairedDevice(299                    deviceId = "extension-issuer",300                    deviceName = "Peach Browser",301                    deviceType = "extension",302                    longTermPublicKeyHex = "11".repeat(32),303                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),304                    trustSource = "direct",305                    pairedAt = 1L,306                ),307            ),308        )309        val pending = FakePendingRegistry()310        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)311        val manifest = buildSignedDeviceManifest(312            issuerDeviceId = "extension-issuer",313            devices = listOf(314                ManifestDeviceEntry(315                    deviceId = "new-phone",316                    deviceName = "June's Phone",317                    deviceType = "android",318                    longTermPublicKeyHex = "aa".repeat(32),319                    signingPublicKeyHex = "bb".repeat(32),320                    relayUrl = meshRelay,321                    pairedAt = 44L,322                ),323            ),324            signingPrivateKey = issuerSigning.privateKey,325        )326327        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })328329        val admitted = paired.get("new-phone")330        assertEquals("vouched", admitted?.trustSource)331        assertEquals(meshRelay, admitted?.relayUrl)332        assertTrue(admitted?.rendezvousSecretHex?.matches(Regex("[0-9a-f]{64}")) == true)333        assertTrue(pending.devices.isEmpty())334        master.fill(0)335    }336337    @Test fun failed_manifest_commit_restores_pending_before_trust_can_land() = runBlocking {338        val repo = VaultRepository(FakeStorage())339        repo.createVault("correct horse")340        val master = repo.syncMasterKey()!!341        val issuerSigning = deriveSyncSigningKeypair(master, "extension-issuer")342        val paired = FakeDeviceRegistry(343            listOf(344                PairedDevice(345                    deviceId = "extension-issuer",346                    deviceName = "Peach Browser",347                    deviceType = "extension",348                    longTermPublicKeyHex = "11".repeat(32),349                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),350                    trustSource = "direct",351                    pairedAt = 1L,352                ),353            ),354        ).also { it.failManifestCommit = true }355        val pending = FakePendingRegistry().also {356            it.upsert(357                PendingVouchedDevice(358                    deviceId = "new-phone",359                    deviceName = "June's Phone",360                    deviceType = "android",361                    longTermPublicKeyHex = "aa".repeat(32),362                    signingPublicKeyHex = "bb".repeat(32),363                    pairedAt = 44L,364                    receivedAt = 45L,365                    vouchedByDeviceId = "extension-issuer",366                ),367            )368        }369        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)370        val manifest = buildSignedDeviceManifest(371            issuerDeviceId = "extension-issuer",372            devices = listOf(373                ManifestDeviceEntry(374                    deviceId = "new-phone",375                    deviceName = "June's Phone",376                    deviceType = "android",377                    longTermPublicKeyHex = "aa".repeat(32),378                    signingPublicKeyHex = "bb".repeat(32),379                    relayUrl = meshRelay,380                    pairedAt = 44L,381                ),382            ),383            signingPrivateKey = issuerSigning.privateKey,384        )385386        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })387388        assertNull("failed registry commit must not install trust", paired.get("new-phone"))389        assertEquals("pending introduction is restored for retry", 1, pending.devices.size)390        master.fill(0)391    }392    /**393     * Browser parity (`applyVerifiedPeerManifest`): trust is keyed on the issuer394     * being DIRECTLY paired, not on it being a browser. Android used to require395     * deviceType == "extension", which silently killed mesh propagation between396     * native devices — the case the mesh exists for now that phones are the397     * listening side.398     */399    @Test fun `a manifest from a directly paired phone is accepted`() = runBlocking {400        val repo = VaultRepository(FakeStorage())401        repo.createVault("correct horse")402        val master = repo.syncMasterKey()!!403        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")404        val paired = FakeDeviceRegistry(405            listOf(406                PairedDevice(407                    deviceId = "phone-issuer",408                    deviceName = "Other Phone",409                    deviceType = "android",410                    longTermPublicKeyHex = "11".repeat(32),411                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),412                    trustSource = "direct",413                    pairedAt = 1L,414                ),415            ),416        )417        val pending = FakePendingRegistry()418        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)419        val manifest = buildSignedDeviceManifest(420            issuerDeviceId = "phone-issuer",421            devices = listOf(422                ManifestDeviceEntry(423                    deviceId = "laptop-b",424                    deviceName = "Laptop B",425                    deviceType = "extension",426                    longTermPublicKeyHex = "aa".repeat(32),427                    signingPublicKeyHex = "bb".repeat(32),428                    relayUrl = meshRelay,429                    pairedAt = 44L,430                ),431            ),432            signingPrivateKey = issuerSigning.privateKey,433        )434435        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })436437        assertEquals("vouched", paired.get("laptop-b")?.trustSource)438        assertEquals(meshRelay, paired.get("laptop-b")?.relayUrl)439        assertTrue(pending.devices.isEmpty())440        master.fill(0)441    }442443    /** A vouched peer cannot extend the trust graph beyond one hop. */444    @Test fun `a vouched issuer cannot introduce further mesh devices`() = runBlocking {445        val repo = VaultRepository(FakeStorage())446        repo.createVault("correct horse")447        val master = repo.syncMasterKey()!!448        val issuerSigning = deriveSyncSigningKeypair(master, "vouched-issuer")449        val paired = FakeDeviceRegistry(450            listOf(451                PairedDevice(452                    deviceId = "vouched-issuer",453                    deviceName = "Vouched Device",454                    deviceType = "extension",455                    longTermPublicKeyHex = "11".repeat(32),456                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),457                    trustSource = "vouched",458                    vouchDepth = MAX_VOUCH_DEPTH,459                    pairedAt = 1L,460                ),461            ),462        )463        val pending = FakePendingRegistry()464        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)465        val manifest = buildSignedDeviceManifest(466            issuerDeviceId = "vouched-issuer",467            devices = listOf(468                ManifestDeviceEntry(469                    deviceId = "onward-mesh-device",470                    deviceName = "Onward mesh device",471                    deviceType = "extension",472                    longTermPublicKeyHex = "aa".repeat(32),473                    signingPublicKeyHex = "bb".repeat(32),474                    relayUrl = meshRelay,475                    pairedAt = 44L,476                ),477            ),478            signingPrivateKey = issuerSigning.privateKey,479        )480481        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })482483        assertNull(paired.get("onward-mesh-device"))484        assertEquals(0, pending.devices.size)485        master.fill(0)486    }487488    @Test fun `a self asserted manifest issuer cannot override the authenticated peer`() = runBlocking {489        val repo = VaultRepository(FakeStorage())490        repo.createVault("correct horse")491        val master = repo.syncMasterKey()!!492        val claimedSigning = deriveSyncSigningKeypair(master, "claimed-issuer")493        val paired = FakeDeviceRegistry(494            listOf(495                PairedDevice(496                    deviceId = "claimed-issuer",497                    deviceName = "Claimed Browser",498                    deviceType = "extension",499                    longTermPublicKeyHex = "11".repeat(32),500                    signingPublicKeyHex = pubkeyToHex(claimedSigning.publicKeyRaw),501                    trustSource = "direct",502                    pairedAt = 1L,503                ),504                PairedDevice(505                    deviceId = "authenticated-peer",506                    deviceName = "Authenticated Phone",507                    deviceType = "android",508                    longTermPublicKeyHex = "22".repeat(32),509                    signingPublicKeyHex = "33".repeat(32),510                    trustSource = "direct",511                    pairedAt = 2L,512                ),513            ),514        )515        val pending = FakePendingRegistry()516        val adapter = VaultSyncAdapter(517            repo,518            ourDeviceId = "android-self",519            pairedDevices = paired,520            pendingVouched = pending,521        )522        val manifest = buildSignedDeviceManifest(523            issuerDeviceId = "claimed-issuer",524            devices = listOf(525                ManifestDeviceEntry(526                    deviceId = "smuggled-device",527                    deviceName = "Smuggled",528                    deviceType = "extension",529                    longTermPublicKeyHex = "aa".repeat(32),530                    signingPublicKeyHex = "bb".repeat(32),531                    relayUrl = meshRelay,532                    pairedAt = 44L,533                ),534            ),535            signingPrivateKey = claimedSigning.privateKey,536        )537538        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x22 })539540        assertEquals(0, pending.devices.size)541542        // Control: the same manifest over the claimed issuer's OWN session does543        // admit the device. Without it the assertion above could pass for any544        // reason — a malformed body, a bad signature, a dead code path.545        adapter.applyIncomingDeviceManifest(manifest, ByteArray(32) { 0x11 })546        assertEquals("vouched", paired.get("smuggled-device")?.trustSource)547        assertTrue(pending.devices.isEmpty())548        master.fill(0)549    }550551    @Test fun `a revoked long term key cannot walk back in under a fresh deviceId`() = runBlocking {552        val repo = VaultRepository(FakeStorage())553        repo.createVault("correct horse")554        val master = repo.syncMasterKey()!!555        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")556        val stolenKey = "dd".repeat(32)557        val paired = FakeDeviceRegistry(558            listOf(559                PairedDevice(560                    deviceId = "phone-issuer",561                    deviceName = "Pixel",562                    deviceType = "android",563                    longTermPublicKeyHex = "11".repeat(32),564                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),565                    trustSource = "direct",566                    pairedAt = 1L,567                ),568                PairedDevice(569                    deviceId = "stolen-laptop",570                    deviceName = "Old Laptop",571                    deviceType = "extension",572                    longTermPublicKeyHex = stolenKey,573                    signingPublicKeyHex = "ee".repeat(32),574                    trustSource = "direct",575                    pairedAt = 2L,576                ),577            ),578        )579        val pending = FakePendingRegistry()580        val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)581582        adapter.applyIncomingDeviceManifest(583            buildSignedDeviceManifest(584                issuerDeviceId = "phone-issuer",585                devices = emptyList(),586                signingPrivateKey = issuerSigning.privateKey,587                revoked = listOf(588                    DeviceRevocation(589                        deviceId = "stolen-laptop",590                        longTermPublicKeyHex = stolenKey,591                        revokedAt = System.currentTimeMillis(),592                        revokedByDeviceId = "phone-issuer",593                    ),594                ),595            ),596            ByteArray(32) { 0x11 },597        )598        assertNull(paired.get("stolen-laptop"))599600        // deviceId is the issuer's to choose, so re-vouching the same key under601        // a new one is free. Terminality has to follow the key, not the label.602        adapter.applyIncomingDeviceManifest(603            buildSignedDeviceManifest(604                issuerDeviceId = "phone-issuer",605                devices = listOf(606                    ManifestDeviceEntry(607                        deviceId = "stolen-laptop-mk2",608                        deviceName = "New Laptop",609                        deviceType = "extension",610                        longTermPublicKeyHex = stolenKey,611                        signingPublicKeyHex = "ee".repeat(32),612                        relayUrl = meshRelay,613                        pairedAt = System.currentTimeMillis(),614                    ),615                ),616                signingPrivateKey = issuerSigning.privateKey,617            ),618            ByteArray(32) { 0x11 },619        )620        assertEquals(0, pending.devices.size)621        assertNull(paired.get("stolen-laptop-mk2"))622623        // Control: the same fresh id carrying a key that was never revoked624        // queues normally, so the rejection above is the key check, not the id.625        adapter.applyIncomingDeviceManifest(626            buildSignedDeviceManifest(627                issuerDeviceId = "phone-issuer",628                devices = listOf(629                    ManifestDeviceEntry(630                        deviceId = "stolen-laptop-mk2",631                        deviceName = "New Laptop",632                        deviceType = "extension",633                        longTermPublicKeyHex = "99".repeat(32),634                        signingPublicKeyHex = "ee".repeat(32),635                        relayUrl = meshRelay,636                        pairedAt = System.currentTimeMillis(),637                    ),638                ),639                signingPrivateKey = issuerSigning.privateKey,640            ),641            ByteArray(32) { 0x11 },642        )643        assertEquals("vouched", paired.get("stolen-laptop-mk2")?.trustSource)644        assertTrue(pending.devices.isEmpty())645        master.fill(0)646    }647648    @Test fun `a revoked key cannot be written onto a device we still trust`() = runBlocking {649        val repo = VaultRepository(FakeStorage())650        repo.createVault("correct horse")651        val master = repo.syncMasterKey()!!652        val issuerSigning = deriveSyncSigningKeypair(master, "phone-issuer")653        val revokedKey = "dd".repeat(32)654        val paired = FakeDeviceRegistry(655            listOf(656                PairedDevice(657                    deviceId = "phone-issuer",658                    deviceName = "Pixel",659                    deviceType = "android",660                    longTermPublicKeyHex = "11".repeat(32),661                    signingPublicKeyHex = pubkeyToHex(issuerSigning.publicKeyRaw),662                    trustSource = "direct",663                    pairedAt = 1L,664                ),665                PairedDevice(666                    deviceId = "trusted-tablet",667                    deviceName = "Tablet",668                    deviceType = "android",669                    longTermPublicKeyHex = "77".repeat(32),670                    signingPublicKeyHex = "ee".repeat(32),671                    trustSource = "direct",672                    pairedAt = 2L,673                ),674            ),675        )676        val adapter = VaultSyncAdapter(677            repo,678            ourDeviceId = "android-self",679            pairedDevices = paired,680            pendingVouched = FakePendingRegistry(),681        )682683        adapter.applyIncomingDeviceManifest(684            buildSignedDeviceManifest(685                issuerDeviceId = "phone-issuer",686                devices = emptyList(),687                signingPrivateKey = issuerSigning.privateKey,688                revoked = listOf(689                    DeviceRevocation(690                        deviceId = "stolen-laptop",691                        longTermPublicKeyHex = revokedKey,692                        revokedAt = System.currentTimeMillis(),693                        revokedByDeviceId = "phone-issuer",694                    ),695                ),696            ),697            ByteArray(32) { 0x11 },698        )699700        // Re-admission dressed as a key rotation on a device we already trust.701        adapter.applyIncomingDeviceManifest(702            buildSignedDeviceManifest(703                issuerDeviceId = "phone-issuer",704                devices = listOf(705                    ManifestDeviceEntry(706                        deviceId = "trusted-tablet",707                        deviceName = "Tablet",708                        deviceType = "android",709                        longTermPublicKeyHex = revokedKey,710                        signingPublicKeyHex = "ee".repeat(32),711                        pairedAt = 2L,712                    ),713                ),714                signingPrivateKey = issuerSigning.privateKey,715            ),716            ByteArray(32) { 0x11 },717        )718        assertEquals("77".repeat(32), paired.get("trusted-tablet")?.longTermPublicKeyHex)719        master.fill(0)720    }721722    /** Pins the helper the manifest loop and SyncViewModel.confirmVouchedDevice share. */723    @Test fun `revocation matches on id or key but never on the empty-key sentinel`() {724        val registry = FakeDeviceRegistry()725        registry.mergeRevocations(726            listOf(727                DeviceRevocation("gone", "dd".repeat(32), 1L, "issuer"),728                DeviceRevocation("keyless", NO_KEY_SENTINEL, 2L, "issuer"),729            ),730        )731        assertTrue(registry.isRevoked("gone"))732        assertTrue(registry.isRevoked("fresh-id", "DD".repeat(32)))733        assertTrue(registry.isRevoked("keyless"))734        assertFalse(registry.isRevoked("fresh-id", "99".repeat(32)))735        // A device that genuinely never stored a key must not inherit the736        // sentinel's revocation.737        assertFalse(registry.isRevoked("innocent", NO_KEY_SENTINEL))738    }739740    @Test fun `public key decoder requires exactly 32 bytes`() {741        assertEquals(32, hexToPubkey("ab".repeat(32)).size)742        assertTrue(runCatching { hexToPubkey("ab".repeat(31)) }.isFailure)743        assertTrue(runCatching { hexToPubkey("ab".repeat(33)) }.isFailure)744        assertEquals(64, hexToBytes("ab".repeat(64)).size)745    }746}