RelayAdoptionReceiverTest.kt

33.7 KB · raw

1package com.peachpasswords.sync23import kotlinx.coroutines.async4import kotlinx.coroutines.withTimeoutOrNull5import kotlinx.coroutines.channels.Channel6import kotlinx.coroutines.runBlocking7import org.junit.Assert.assertEquals8import org.junit.Assert.assertFalse9import org.junit.Assert.assertNotNull10import org.junit.Assert.assertTrue11import org.junit.Assert.assertNull12import org.junit.Assert.fail13import org.junit.Test14import kotlin.system.measureTimeMillis1516/**17 * Item 2 (REVIEW_DEFERRED_ITEMS_BRIEF.md): receiver inline-snapshot happy-path.18 *19 * The `sourceCanSendSnapshot` branch in `runRelayAdoptionReceiverSession` was20 * already reached by `RelayAdoptionHostTest` but only down the21 * catch-and-fallback path (source did not send a snapshot). What had no22 * coverage was the success path: a snapshot-capable source that actually23 * sends entries / tombstones / duress, the receiver applying them inline,24 * sending `ADOPT_SNAPSHOT_APPLIED`, and `markSynced` firing.25 *26 * These three tests cover the three sub-branches:27 * 1. snapshot_capable=true AND source sends a real snapshot -> applySnapshot28 *    called, SnapshotApplied sent, markSynced fired.29 * 2. snapshot_capable=true AND source sends nothing -> applySnapshot NOT30 *    called, session still returns paired device (sync fallback).31 * 3. snapshot_capable=false -> 15s wait is skipped, applySnapshot NOT called,32 *    session returns paired device quickly.33 */34class RelayAdoptionReceiverTest {35    private class MemoryRelaySocket(36        private val inbound: Channel<ByteArray>,37        private val outbound: Channel<ByteArray>,38    ) : RelayBinarySocket {39        override fun send(frame: ByteArray) {40            check(outbound.trySend(frame.copyOf()).isSuccess)41        }4243        override suspend fun receive(): ByteArray = inbound.receive()44        override fun close(code: Int, reason: String) {45            outbound.close()46        }4748        override fun closeAfterQueuedFrames(code: Int, reason: String) {49            outbound.close()50        }51    }5253    private fun socketPair(): Pair<RelayBinarySocket, RelayBinarySocket> {54        val leftToRight = Channel<ByteArray>(Channel.UNLIMITED)55        val rightToLeft = Channel<ByteArray>(Channel.UNLIMITED)56        return MemoryRelaySocket(rightToLeft, leftToRight) to57            MemoryRelaySocket(leftToRight, rightToLeft)58    }5960    private fun identity(name: String, publicKey: ByteArray, signingPublicKeyHex: String = "cd".repeat(32)) = LocalDeviceIdentity(61        deviceId = "$name-id",62        deviceName = name,63        deviceType = DeviceType.ANDROID,64        longTermPublicKeyHex = Rendezvous.bytesToHex(publicKey),65        signingPublicKeyHex = signingPublicKeyHex,66        wsPort = 49142,67        relayUrl = "wss://relay.example.test",68    )6970    private fun smallSnapshot(): Pair<Map<String, String>, Map<String, Long>> {71        val entries = mapOf("id-0" to "ciphertext-0", "id-1" to "ciphertext-1")72        val tombstones = mapOf("dead-0" to 1L)73        return entries to tombstones74    }7576    @Test fun `receiver applies an inline snapshot when the source is snapshot capable`() = runBlocking {77        val (sourceSocket, receiverSocket) = socketPair()78        val token = "AAECAwQFBgcICQoLDA0ODw"79        val relay = "wss://relay.example.test"80        val root = ByteArray(32) { (it + 3).toByte() }81        val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))82        val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))83        val sourceIdentity = identity("source", sourceKeys.publicKey)84        val receiverIdentity = identity("receiver", receiverKeys.publicKey)85        val (entries, tombstones) = smallSnapshot()86        val duressJson = "{\"duress\":true}"87        var sourceStored: PairedDevice? = null88        var receiverStored: PairedDevice? = null89        var sourceMarkedSynced = false90        var receiverAppliedEntries: Map<String, String>? = null91        var receiverAppliedTombstones: Map<String, Long>? = null92        var receiverAppliedDuress: String? = null93        var receiverMarkedSynced = false9495        val sourceJob = async {96            runRelayAdoptionSourceSession(97                sourceSocket,98                token,99                relay,100                sourceKeys.secretKey,101                sourceKeys.publicKey,102                sourceIdentity,103                object : AdoptionSourceDeps {104                    override val sourceIdentity = sourceIdentity105                    override suspend fun rootKeyHex() = Rendezvous.bytesToHex(root)106                    override suspend fun vaultId() = computeVaultId(root)107                    override suspend fun license() = "PPK-test"108                    override suspend fun onConsent(request: AdoptionFrame.Request) = true109                    override suspend fun upsertPairedDevice(device: PairedDevice) {110                        sourceStored = device111                    }112                    override suspend fun vaultSnapshot() = smallSnapshot()113                    override suspend fun duressSlotJson() = duressJson114                    override suspend fun markSynced(deviceId: String) {115                        sourceMarkedSynced = true116                    }117                },118                confirm = { _, _ -> true },119            )120        }121122        val received = runRelayAdoptionReceiverSession(123            receiverSocket,124            PairingInvitation(125                relay,126                token,127                noiseStaticPublicKeyHex = Rendezvous.bytesToHex(sourceKeys.publicKey),128            ),129            object : AdoptionReceiverDeps {130                override val deviceName = "receiver"131                override val deviceType = DeviceType.ANDROID132                override fun generateDeviceId() = "session-only-request"133                override suspend fun confirmSas() = true134                override suspend fun createVaultFromRootKey(rootKeyHex: String): String =135                    computeVaultId(hexToPubkey(rootKeyHex))136                override suspend fun deriveLocalIdentity() = receiverIdentity137                override suspend fun upsertPairedDevice(device: PairedDevice) {138                    receiverStored = device139                }140                override suspend fun applySnapshot(141                    entries: Map<String, String>,142                    tombstones: Map<String, Long>,143                    duressSlot: String?,144                ) {145                    receiverAppliedEntries = entries146                    receiverAppliedTombstones = tombstones147                    receiverAppliedDuress = duressSlot148                }149                override suspend fun markSynced(deviceId: String) {150                    receiverMarkedSynced = true151                }152                override fun onError(error: String) = throw AssertionError(error)153            },154            confirm = { true },155        )156157        assertNotNull(received)158        assertNotNull(sourceJob.await())159        assertEquals(entries, receiverAppliedEntries)160        assertEquals(tombstones, receiverAppliedTombstones)161        assertEquals(duressJson, receiverAppliedDuress)162        assertTrue("receiver should mark synced after applying snapshot", receiverMarkedSynced)163        assertTrue("source should mark synced after SnapshotApplied", sourceMarkedSynced)164        assertNotNull(receiverStored)165        assertNotNull(sourceStored)166    }167168    @Test fun `receiver falls back to sync when the source sends no snapshot`() = runBlocking {169        val (sourceSocket, receiverSocket) = socketPair()170        val token = "AAECAwQFBgcICQoLDA0ODw"171        val relay = "wss://relay.example.test"172        val root = ByteArray(32) { (it + 5).toByte() }173        val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))174        val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))175        val sourceIdentity = identity("source", sourceKeys.publicKey)176        val receiverIdentity = identity("receiver", receiverKeys.publicKey)177        var sourceStored: PairedDevice? = null178        var receiverStored: PairedDevice? = null179        var receiverApplied = false180        var receiverMarkedSynced = false181182        val sourceJob = async {183            runRelayAdoptionSourceSession(184                sourceSocket,185                token,186                relay,187                sourceKeys.secretKey,188                sourceKeys.publicKey,189                sourceIdentity,190                object : AdoptionSourceDeps {191                    override val sourceIdentity = sourceIdentity192                    override suspend fun rootKeyHex() = Rendezvous.bytesToHex(root)193                    override suspend fun vaultId() = computeVaultId(root)194                    override suspend fun license() = "PPK-test"195                    override suspend fun onConsent(request: AdoptionFrame.Request) = true196                    override suspend fun upsertPairedDevice(device: PairedDevice) {197                        sourceStored = device198                    }199                    // vaultSnapshot() returns null -> source does not send a snapshot.200                    override suspend fun vaultSnapshot() = null201                },202                confirm = { _, _ -> true },203            )204        }205206        val received = runRelayAdoptionReceiverSession(207            receiverSocket,208            PairingInvitation(209                relay,210                token,211                noiseStaticPublicKeyHex = Rendezvous.bytesToHex(sourceKeys.publicKey),212            ),213            object : AdoptionReceiverDeps {214                override val deviceName = "receiver"215                override val deviceType = DeviceType.ANDROID216                override fun generateDeviceId() = "session-only-request"217                override suspend fun confirmSas() = true218                override suspend fun createVaultFromRootKey(rootKeyHex: String): String =219                    computeVaultId(hexToPubkey(rootKeyHex))220                override suspend fun deriveLocalIdentity() = receiverIdentity221                override suspend fun upsertPairedDevice(device: PairedDevice) {222                    receiverStored = device223                }224                override suspend fun applySnapshot(225                    entries: Map<String, String>,226                    tombstones: Map<String, Long>,227                    duressSlot: String?,228                ) {229                    receiverApplied = true230                }231                override suspend fun markSynced(deviceId: String) {232                    receiverMarkedSynced = true233                }234                override fun onError(error: String) = throw AssertionError(error)235            },236            confirm = { true },237        )238239        assertNotNull(received)240        assertNotNull(sourceJob.await())241        assertFalse("applySnapshot must NOT be called when source sends none", receiverApplied)242        assertFalse("markSynced must NOT be called when no snapshot was applied", receiverMarkedSynced)243        assertNotNull(receiverStored)244        assertNotNull(sourceStored)245    }246247    @Test fun `receiver skips the inline wait when the grant is not snapshot capable`() = runBlocking {248        val (sourceSocket, receiverSocket) = socketPair()249        val token = "AAECAwQFBgcICQoLDA0ODw"250        val relay = "wss://relay.example.test"251        val root = ByteArray(32) { (it + 7).toByte() }252        val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("old-source-id"))253        val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))254        val sourceIdentity = identity("old-source", sourceKeys.publicKey)255        val receiverIdentity = identity("receiver", receiverKeys.publicKey)256        var receiverApplied = false257258        val sourceJob = async {259            sourceSocket.receive()260            sourceSocket.send(261                org.json.JSONObject().put("type", "PEACH_HELLO_ACK")262                    .put("ephemeralPublicKeyHex", Rendezvous.bytesToHex(sourceKeys.publicKey))263                    .toString().toByteArray(),264            )265            val noise = noiseNKResponder(266                sourceKeys.secretKey,267                sourceKeys.publicKey,268                sourceSocket::send,269                sourceSocket::receive,270            )271            try {272                val channel = object : PairingTransport {273                    override suspend fun send(msg: ByteArray) = sourceSocket.send(noise.encrypt(msg))274                    override suspend fun receive(): ByteArray = noise.decrypt(sourceSocket.receive())275                    override suspend fun close() = sourceSocket.close()276                }277                assertTrue(receiveFrame(channel) is AdoptionFrame.Request)278                assertTrue(receiveFrame(channel) is AdoptionFrame.Confirm)279                sendFrame(channel, AdoptionFrame.Grant(280                    rootKeyHex = Rendezvous.bytesToHex(root),281                    vaultId = computeVaultId(root),282                    license = "PPK-test",283                    source = AdoptionFrame.Source(284                        deviceId = sourceIdentity.deviceId,285                        deviceName = sourceIdentity.deviceName,286                        deviceType = sourceIdentity.deviceType.wireValue,287                        longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,288                        signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,289                    ),290                    snapshotCapable = false,291                ))292                assertTrue(receiveFrame(channel) is AdoptionFrame.Identity)293                sendFrame(channel, AdoptionFrame.Complete)294                assertTrue(receiveFrame(channel) is AdoptionFrame.Applied)295            } finally {296                noise.close()297            }298        }299300        var received: PairedDevice? = null301        val elapsedMs = measureTimeMillis {302            received = runRelayAdoptionReceiverSession(303                receiverSocket,304                PairingInvitation(305                    relay,306                    token,307                    noiseStaticPublicKeyHex = Rendezvous.bytesToHex(sourceKeys.publicKey),308                ),309                object : AdoptionReceiverDeps {310                    override val deviceName = "receiver"311                    override val deviceType = DeviceType.ANDROID312                    override fun generateDeviceId() = "session-only-request"313                    override suspend fun confirmSas() = true314                    override suspend fun createVaultFromRootKey(rootKeyHex: String) =315                        computeVaultId(hexToPubkey(rootKeyHex))316                    override suspend fun deriveLocalIdentity() = receiverIdentity317                    override suspend fun upsertPairedDevice(device: PairedDevice) = Unit318                    override suspend fun applySnapshot(319                        entries: Map<String, String>,320                        tombstones: Map<String, Long>,321                        duressSlot: String?,322                    ) {323                        receiverApplied = true324                    }325                    override fun onError(error: String) = throw AssertionError(error)326                },327                confirm = { true },328            )329        }330331        assertNotNull(received)332        sourceJob.await()333        assertFalse(receiverApplied)334        assertTrue("legacy grant should skip the 15s snapshot wait", elapsedMs < 5_000)335    }336337    @Test fun `receiver graduates into the mesh when the source sends a device manifest`() = runBlocking {338        // Mesh propagation: a 3rd device pairs with a pool of 2 already-paired339        // devices. The third must graduate into the full mesh during the same340        // adoption session, not just learn about the source. Verifies the341        // adoption-receiver apply path wires applyIncomingDeviceManifest to342        // the adapter and the adapter puts the vouched peers into the local343        // registry.344        val (sourceSocket, receiverSocket) = socketPair()345        val token = "AAECAwQFBgcICQoLDA0ODw"346        val relay = "wss://relay.example.test"347        val root = ByteArray(32) { (it + 13).toByte() }348        val sourceCredentials = randomLocalIdentityCredentials("source-id")349        val sourceKeys = localSyncKeypair(sourceCredentials)350        val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))351        val sourceSigning = localSigningKeypair(sourceCredentials)352        val sourceIdentity = identity("source", sourceKeys.publicKey, pubkeyToHex(sourceSigning.publicKeyRaw))353        val receiverIdentity = identity("receiver", receiverKeys.publicKey)354355        // The source's pool already contains two direct-trust peers (B and C).356        // The signed manifest is what the source transmits during adoption.357        val manifest = buildSignedDeviceManifest(358            issuerDeviceId = "source-id",359            devices = listOf(360                ManifestDeviceEntry(361                    deviceId = "peer-b",362                    deviceName = "Pool B",363                    deviceType = "extension",364                    longTermPublicKeyHex = "11".repeat(32),365                    signingPublicKeyHex = "22".repeat(32),366                    relayUrl = "wss://relay.example.test",367                    pairedAt = 1L,368                ),369                ManifestDeviceEntry(370                    deviceId = "peer-c",371                    deviceName = "Pool C",372                    deviceType = "android",373                    longTermPublicKeyHex = "aa".repeat(32),374                    signingPublicKeyHex = "bb".repeat(32),375                    relayUrl = "wss://relay.example.test",376                    pairedAt = 2L,377                ),378            ),379            signingPrivateKey = sourceSigning.privateKey,380        )381382        // Receiver's in-memory registry. Starts empty; the source gets added383        // by the Grant path during adoption, and the two vouched peers get384        // appended when the manifest is applied.385        val receiverRegistry = mutableMapOf<String, PairedDevice>()386        val receiverPending = mutableListOf<com.peachpasswords.sync.PendingVouchedDevice>()387        val receiverRegistryStore = object : PairedDeviceRegistry {388            override fun getAll(): List<PairedDevice> = receiverRegistry.values.toList()389            override fun get(id: String): PairedDevice? = receiverRegistry[id]390            override fun getByPubkey(pubkeyHex: String): PairedDevice? =391                receiverRegistry.values.firstOrNull { it.longTermPublicKeyHex?.lowercase() == pubkeyHex.lowercase() }392            override fun upsert(device: PairedDevice) { receiverRegistry[device.deviceId] = device }393            override fun remove(deviceId: String) { receiverRegistry.remove(deviceId) }394            override fun listRevocations(): List<DeviceRevocation> = emptyList()395            override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {396                batch.removals.forEach { receiverRegistry.remove(it) }397                batch.upserts.forEach { receiverRegistry[it.deviceId] = it }398                return true399            }400            override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> = emptyList()401            override fun isRevoked(deviceId: String, longTermPublicKeyHex: String?): Boolean = false402            override fun clearRevocation(deviceId: String) {}403        }404        val receiverPendingStore = object : PendingVouchedRegistry {405            override fun getAll(): List<com.peachpasswords.sync.PendingVouchedDevice> = receiverPending.toList()406            override fun upsert(device: com.peachpasswords.sync.PendingVouchedDevice) { receiverPending += device }407            override fun remove(id: String) { receiverPending.removeAll { it.deviceId == id } }408            override fun removeBatch(ids: Set<String>): Boolean {409                receiverPending.removeAll { it.deviceId in ids }410                return true411            }412            override fun restoreBatch(devices: List<com.peachpasswords.sync.PendingVouchedDevice>): Boolean = true413        }414        var receiverAppliedManifest: SignedDeviceManifest? = null415416        val sourceJob = async {417            runRelayAdoptionSourceSession(418                sourceSocket,419                token,420                relay,421                sourceKeys.secretKey,422                sourceKeys.publicKey,423                sourceIdentity,424                object : AdoptionSourceDeps {425                    override val sourceIdentity = sourceIdentity426                    override suspend fun rootKeyHex() = Rendezvous.bytesToHex(root)427                    override suspend fun vaultId() = computeVaultId(root)428                    override suspend fun license() = "PPK-test"429                    override suspend fun onConsent(request: AdoptionFrame.Request) = true430                    override suspend fun upsertPairedDevice(device: PairedDevice) {}431                    override suspend fun vaultSnapshot() = smallSnapshot()432                    override suspend fun duressSlotJson() = null433                    override suspend fun outgoingDeviceManifest() = manifest434                    override suspend fun markSynced(deviceId: String) {}435                },436                confirm = { _, _ -> true },437            )438        }439440        val received = runRelayAdoptionReceiverSession(441            receiverSocket,442            PairingInvitation(443                relay,444                token,445                noiseStaticPublicKeyHex = Rendezvous.bytesToHex(sourceKeys.publicKey),446            ),447            object : AdoptionReceiverDeps {448                override val deviceName = "receiver"449                override val deviceType = DeviceType.ANDROID450                override fun generateDeviceId() = "session-only-request"451                override suspend fun confirmSas() = true452                override suspend fun createVaultFromRootKey(rootKeyHex: String) =453                    computeVaultId(hexToPubkey(rootKeyHex))454                override suspend fun deriveLocalIdentity() = receiverIdentity455                override suspend fun upsertPairedDevice(device: PairedDevice) {456                    receiverRegistry[device.deviceId] = device457                }458                override suspend fun applySnapshot(459                    entries: Map<String, String>,460                    tombstones: Map<String, Long>,461                    duressSlot: String?,462                ) {}463                override suspend fun applyIncomingDeviceManifest(464                    manifest: SignedDeviceManifest,465                    authenticatedRemoteStaticPublicKey: ByteArray,466                ) {467                    receiverAppliedManifest = manifest468                    val adapter = VaultSyncAdapter(469                        repo = createReceiverVault(root),470                        ourDeviceId = "receiver-id",471                        pairedDevices = receiverRegistryStore,472                        pendingVouched = receiverPendingStore,473                    )474                    adapter.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)475                }476                override suspend fun markSynced(deviceId: String) {}477                override fun onError(error: String) = throw AssertionError(error)478            },479            confirm = { true },480        )481482        assertNotNull(received)483        sourceJob.await()484        assertNotNull("source must have delivered the manifest frame", receiverAppliedManifest)485        // After the adoption + manifest apply, the receiver's registry must486        // contain the source (added by Grant) AND the two vouched peers.487        val deviceIds = receiverRegistry.keys.toSet()488        assertEquals(489            "receiver should see the source + both vouched peers",490            setOf("source-id", "peer-b", "peer-c"),491            deviceIds,492        )493        // The two vouched peers arrive with trustSource=vouched, not direct.494        assertEquals("vouched", receiverRegistry["peer-b"]?.trustSource)495        assertEquals("vouched", receiverRegistry["peer-c"]?.trustSource)496        // The pending store is drained after a successful commit.497        assertTrue("pending vouched should be cleared", receiverPending.isEmpty())498    }499500    private suspend fun createReceiverVault(root: ByteArray): com.peachpasswords.vault.VaultRepository {501        val repo = com.peachpasswords.vault.VaultRepository(ReceiverFakeStorage())502        repo.createVault(root.joinToString("") { "%02x".format(it) })503        return repo504    }505506    private class ReceiverFakeStorage : com.peachpasswords.vault.VaultStorage {507        private var slotA: com.peachpasswords.vault.StoredVault? = null508        private var slotB: String? = null509        private var decoy: com.peachpasswords.vault.StoredVault? = null510        private var ver: Long = 0511        private var settings = com.peachpasswords.vault.VaultSettings()512        override fun loadSlotA() = slotA513        override fun hasVault() = slotA != null514        override fun writeSlotA(slot: com.peachpasswords.vault.StoredVault): Boolean { slotA = slot; return true }515        override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }516        override fun loadDecoySlot() = decoy517        override fun writeDecoySlot(slot: com.peachpasswords.vault.StoredVault): Boolean { decoy = slot; return true }518        override fun hasDecoySlot() = decoy != null519        override fun clearDecoySlot() { decoy = null }520        override fun version() = ver521        override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }522        override fun loadSettings() = settings523        override fun writeSettings(s: com.peachpasswords.vault.VaultSettings): Boolean { settings = s; return true }524        override fun clearVault() { slotA = null; slotB = null; ver = 0; settings = com.peachpasswords.vault.VaultSettings() }525    }526}527528/**529 * PB-26-103: the invitation pins the responder's Noise static so the scanner530 * can authenticate the cleartext PEACH_HELLO_ACK before running Noise. Without531 * the pin a relay can terminate both sessions and present its own key to each532 * side, which is only detectable today by a human comparing the SAS.533 *534 * These cover both failure shapes in the receiver direction, matching the535 * phone-source direction tests in RelayAdoptionInitiatorSourceTest.536 */537class RelayAdoptionInvitationPinTest {538539    /**540     * Time-boxed so these adversarial tests fail rather than hang: without the541     * pin check the receiver completes a handshake against the substituted key542     * and then stalls on a protocol step the attacker never performs.543     */544    private val HANDSHAKE_TIMEOUT_MS = 5_000L545546    private class MemoryRelaySocket(547        private val inbound: Channel<ByteArray>,548        private val outbound: Channel<ByteArray>,549    ) : RelayBinarySocket {550        override fun send(frame: ByteArray) {551            check(outbound.trySend(frame.copyOf()).isSuccess)552        }553554        override suspend fun receive(): ByteArray = inbound.receive()555        override fun close(code: Int, reason: String) {556            outbound.close()557        }558559        override fun closeAfterQueuedFrames(code: Int, reason: String) {560            outbound.close()561        }562    }563564    private fun socketPair(): Pair<RelayBinarySocket, RelayBinarySocket> {565        val leftToRight = Channel<ByteArray>(Channel.UNLIMITED)566        val rightToLeft = Channel<ByteArray>(Channel.UNLIMITED)567        return MemoryRelaySocket(rightToLeft, leftToRight) to568            MemoryRelaySocket(leftToRight, rightToLeft)569    }570571    /**572     * Every protocol member throws: reaching any of them means we got past the573     * pin check. `onError` only records, so the positive control below can end574     * the session cleanly at the SAS gate.575     */576    private fun abortingDeps(577        confirmSas: Boolean = false,578        generateDeviceId: () -> String = { error("past the pin check") },579    ) = object : AdoptionReceiverDeps {580        override val deviceName = "phone"581        override val deviceType = DeviceType.ANDROID582        override fun generateDeviceId() = generateDeviceId()583        override suspend fun confirmSas() = confirmSas584        override suspend fun createVaultFromRootKey(rootKeyHex: String): String =585            error("past the pin check")586        override suspend fun deriveLocalIdentity(): LocalDeviceIdentity = error("past the pin check")587        override suspend fun upsertPairedDevice(device: PairedDevice) = error("past the pin check")588        override fun onError(error: String) = Unit589    }590591    private fun ack(publicKey: ByteArray) = org.json.JSONObject()592        .put("type", "PEACH_HELLO_ACK")593        .put("ephemeralPublicKeyHex", Rendezvous.bytesToHex(publicKey))594        .toString()595        .toByteArray()596597    @Test fun `receiver rejects an ACK static that does not match the pinned key`() = runBlocking {598        val (phoneSocket, mitmSocket) = socketPair()599        val root = ByteArray(32) { (it + 3).toByte() }600        val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))601        val attackerKeys = localSyncKeypair(randomLocalIdentityCredentials("attacker-id"))602603        // The result is captured inside the job: an exception escaping a child604        // coroutine cancels the parent scope before await() can observe it.605        val phoneJob = async {606            try {607                runRelayAdoptionReceiverSession(608                    socket = phoneSocket,609                    invitation = PairingInvitation(610                        "wss://relay.example.test",611                        "AAECAwQFBgcICQoLDA0ODw",612                        VaultStatus.POPULATED,613                        Rendezvous.bytesToHex(sourceKeys.publicKey),614                    ),615                    receiverDeps = abortingDeps(),616                    confirm = { error("past the pin check") },617                )618                "completed"619            } catch (expected: IllegalArgumentException) {620                expected.message621            }622        }623624        mitmSocket.receive() // PEACH_HELLO625        mitmSocket.send(ack(attackerKeys.publicKey))626627        val outcome = withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() }628        phoneJob.cancel()629        assertEquals("pairing_static_key_mismatch", outcome)630    }631632    @Test fun `receiver rejects an invitation that pins no static key`() = runBlocking {633        val (phoneSocket, mitmSocket) = socketPair()634        val root = ByteArray(32) { (it + 13).toByte() }635        val attackerKeys = localSyncKeypair(randomLocalIdentityCredentials("attacker-id"))636637        val phoneJob = async {638            try {639                runRelayAdoptionReceiverSession(640                    socket = phoneSocket,641                    // A pre-fix invitation. Accepting it here reopens the hole.642                    invitation = PairingInvitation(643                        "wss://relay.example.test",644                        "AAECAwQFBgcICQoLDA0ODw",645                        VaultStatus.POPULATED,646                    ),647                    receiverDeps = abortingDeps(),648                    confirm = { error("past the pin check") },649                )650                "completed"651            } catch (expected: IllegalArgumentException) {652                expected.message653            }654        }655656        mitmSocket.receive() // PEACH_HELLO657        mitmSocket.send(ack(attackerKeys.publicKey))658659        val outcome = withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() }660        phoneJob.cancel()661        assertEquals("pairing_invitation_missing_static_key", outcome)662    }663664    // Positive control: the honest source sends exactly the pinned static, so665    // the check must let the handshake through to the SAS gate.666    @Test fun `receiver proceeds when the ACK static matches the pinned key`() = runBlocking {667        val (phoneSocket, sourceSocket) = socketPair()668        val root = ByteArray(32) { (it + 17).toByte() }669        val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))670        val reached = java.util.concurrent.atomic.AtomicBoolean(false)671672        val phoneJob = async {673            runRelayAdoptionReceiverSession(674                socket = phoneSocket,675                invitation = PairingInvitation(676                    "wss://relay.example.test",677                    "AAECAwQFBgcICQoLDA0ODw",678                    VaultStatus.POPULATED,679                    Rendezvous.bytesToHex(sourceKeys.publicKey),680                ),681                receiverDeps = abortingDeps(682                    confirmSas = false,683                    // requestAdoption mints the device id to build its frame, so684                    // reaching this call proves the handshake ran.685                    generateDeviceId = { reached.set(true); "session-only" },686                ),687                confirm = { true },688            )689        }690691        sourceSocket.receive() // PEACH_HELLO692        sourceSocket.send(ack(sourceKeys.publicKey))693        val noise = noiseNKResponder(694            sourceKeys.secretKey,695            sourceKeys.publicKey,696            sourceSocket::send,697            sourceSocket::receive,698        )699        try {700            val channel = object : PairingTransport {701                override suspend fun send(msg: ByteArray) = sourceSocket.send(noise.encrypt(msg))702                override suspend fun receive(): ByteArray = noise.decrypt(sourceSocket.receive())703                override suspend fun close() = sourceSocket.close()704            }705            // Read and discard the receiver's request: the handshake completing706            // at all is what this control asserts.707            receiveFrame(channel)708        } finally {709            noise.close()710        }711712        // Declining at the SAS gate ends the session without pairing, which713        // proves the pin check let the matching static through.714        val outcome = withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() }715        // runBlocking waits for its children, and the receiver side may still716        // be parked on the protocol.717        phoneJob.cancel()718        assertNull(outcome)719        assertTrue(720            "the matching static must reach the adoption request, not be refused",721            reached.get(),722        )723    }724}