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.measureTimeMillis1516171819202122232425262728293031323334class 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 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 339 340 341 342 343 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 356 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 383 384 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 localCredentials = randomLocalIdentityCredentials("receiver-id"),474 )475 adapter.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)476 }477 override suspend fun markSynced(deviceId: String) {}478 override fun onError(error: String) = throw AssertionError(error)479 },480 confirm = { true },481 )482483 assertNotNull(received)484 sourceJob.await()485 assertNotNull("source must have delivered the manifest frame", receiverAppliedManifest)486 487 488 val deviceIds = receiverRegistry.keys.toSet()489 assertEquals(490 "receiver should see the source + both vouched peers",491 setOf("source-id", "peer-b", "peer-c"),492 deviceIds,493 )494 495 assertEquals("vouched", receiverRegistry["peer-b"]?.trustSource)496 assertEquals("vouched", receiverRegistry["peer-c"]?.trustSource)497 498 assertTrue("pending vouched should be cleared", receiverPending.isEmpty())499 }500501 private suspend fun createReceiverVault(root: ByteArray): com.peachpasswords.vault.VaultRepository {502 val repo = com.peachpasswords.vault.VaultRepository(ReceiverFakeStorage())503 repo.createVault(root.joinToString("") { "%02x".format(it) })504 return repo505 }506507 private class ReceiverFakeStorage : com.peachpasswords.vault.VaultStorage {508 private var slotA: com.peachpasswords.vault.StoredVault? = null509 private var slotB: String? = null510 private var decoy: com.peachpasswords.vault.StoredVault? = null511 private var ver: Long = 0512 private var settings = com.peachpasswords.vault.VaultSettings()513 override fun loadSlotA() = slotA514 override fun hasVault() = slotA != null515 override fun writeSlotA(slot: com.peachpasswords.vault.StoredVault): Boolean { slotA = slot; return true }516 override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }517 override fun loadDecoySlot() = decoy518 override fun writeDecoySlot(slot: com.peachpasswords.vault.StoredVault): Boolean { decoy = slot; return true }519 override fun hasDecoySlot() = decoy != null520 override fun clearDecoySlot() { decoy = null }521 override fun version() = ver522 override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }523 override fun loadSettings() = settings524 override fun writeSettings(s: com.peachpasswords.vault.VaultSettings): Boolean { settings = s; return true }525 override fun clearVault() { slotA = null; slotB = null; ver = 0; settings = com.peachpasswords.vault.VaultSettings() }526 }527}528529530531532533534535536537538class RelayAdoptionInvitationPinTest {539540 541542543544545 private val HANDSHAKE_TIMEOUT_MS = 5_000L546547 private class MemoryRelaySocket(548 private val inbound: Channel<ByteArray>,549 private val outbound: Channel<ByteArray>,550 ) : RelayBinarySocket {551 override fun send(frame: ByteArray) {552 check(outbound.trySend(frame.copyOf()).isSuccess)553 }554555 override suspend fun receive(): ByteArray = inbound.receive()556 override fun close(code: Int, reason: String) {557 outbound.close()558 }559560 override fun closeAfterQueuedFrames(code: Int, reason: String) {561 outbound.close()562 }563 }564565 private fun socketPair(): Pair<RelayBinarySocket, RelayBinarySocket> {566 val leftToRight = Channel<ByteArray>(Channel.UNLIMITED)567 val rightToLeft = Channel<ByteArray>(Channel.UNLIMITED)568 return MemoryRelaySocket(rightToLeft, leftToRight) to569 MemoryRelaySocket(leftToRight, rightToLeft)570 }571572 573574575576577 private fun abortingDeps(578 confirmSas: Boolean = false,579 generateDeviceId: () -> String = { error("past the pin check") },580 ) = object : AdoptionReceiverDeps {581 override val deviceName = "phone"582 override val deviceType = DeviceType.ANDROID583 override fun generateDeviceId() = generateDeviceId()584 override suspend fun confirmSas() = confirmSas585 override suspend fun createVaultFromRootKey(rootKeyHex: String): String =586 error("past the pin check")587 override suspend fun deriveLocalIdentity(): LocalDeviceIdentity = error("past the pin check")588 override suspend fun upsertPairedDevice(device: PairedDevice) = error("past the pin check")589 override fun onError(error: String) = Unit590 }591592 private fun ack(publicKey: ByteArray) = org.json.JSONObject()593 .put("type", "PEACH_HELLO_ACK")594 .put("ephemeralPublicKeyHex", Rendezvous.bytesToHex(publicKey))595 .toString()596 .toByteArray()597598 @Test fun `receiver rejects an ACK static that does not match the pinned key`() = runBlocking {599 val (phoneSocket, mitmSocket) = socketPair()600 val root = ByteArray(32) { (it + 3).toByte() }601 val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))602 val attackerKeys = localSyncKeypair(randomLocalIdentityCredentials("attacker-id"))603604 605 606 val phoneJob = async {607 try {608 runRelayAdoptionReceiverSession(609 socket = phoneSocket,610 invitation = PairingInvitation(611 "wss://relay.example.test",612 "AAECAwQFBgcICQoLDA0ODw",613 VaultStatus.POPULATED,614 Rendezvous.bytesToHex(sourceKeys.publicKey),615 ),616 receiverDeps = abortingDeps(),617 confirm = { error("past the pin check") },618 )619 "completed"620 } catch (expected: IllegalArgumentException) {621 expected.message622 }623 }624625 mitmSocket.receive() 626 mitmSocket.send(ack(attackerKeys.publicKey))627628 val outcome = withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() }629 phoneJob.cancel()630 assertEquals("pairing_static_key_mismatch", outcome)631 }632633 @Test fun `receiver rejects an invitation that pins no static key`() = runBlocking {634 val (phoneSocket, mitmSocket) = socketPair()635 val root = ByteArray(32) { (it + 13).toByte() }636 val attackerKeys = localSyncKeypair(randomLocalIdentityCredentials("attacker-id"))637638 val phoneJob = async {639 try {640 runRelayAdoptionReceiverSession(641 socket = phoneSocket,642 643 invitation = PairingInvitation(644 "wss://relay.example.test",645 "AAECAwQFBgcICQoLDA0ODw",646 VaultStatus.POPULATED,647 ),648 receiverDeps = abortingDeps(),649 confirm = { error("past the pin check") },650 )651 "completed"652 } catch (expected: IllegalArgumentException) {653 expected.message654 }655 }656657 mitmSocket.receive() 658 mitmSocket.send(ack(attackerKeys.publicKey))659660 val outcome = withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() }661 phoneJob.cancel()662 assertEquals("pairing_invitation_missing_static_key", outcome)663 }664665 666 667 @Test fun `receiver proceeds when the ACK static matches the pinned key`() = runBlocking {668 val (phoneSocket, sourceSocket) = socketPair()669 val root = ByteArray(32) { (it + 17).toByte() }670 val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))671 val reached = java.util.concurrent.atomic.AtomicBoolean(false)672673 val phoneJob = async {674 runRelayAdoptionReceiverSession(675 socket = phoneSocket,676 invitation = PairingInvitation(677 "wss://relay.example.test",678 "AAECAwQFBgcICQoLDA0ODw",679 VaultStatus.POPULATED,680 Rendezvous.bytesToHex(sourceKeys.publicKey),681 ),682 receiverDeps = abortingDeps(683 confirmSas = false,684 685 686 generateDeviceId = { reached.set(true); "session-only" },687 ),688 confirm = { true },689 )690 }691692 sourceSocket.receive() 693 sourceSocket.send(ack(sourceKeys.publicKey))694 val noise = noiseNKResponder(695 sourceKeys.secretKey,696 sourceKeys.publicKey,697 sourceSocket::send,698 sourceSocket::receive,699 )700 try {701 val channel = object : PairingTransport {702 override suspend fun send(msg: ByteArray) = sourceSocket.send(noise.encrypt(msg))703 override suspend fun receive(): ByteArray = noise.decrypt(sourceSocket.receive())704 override suspend fun close() = sourceSocket.close()705 }706 707 708 receiveFrame(channel)709 } finally {710 noise.close()711 }712713 714 715 val outcome = withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() }716 717 718 phoneJob.cancel()719 assertNull(outcome)720 assertTrue(721 "the matching static must reach the adoption request, not be refused",722 reached.get(),723 )724 }725}