1package com.peachpasswords.sync23import kotlinx.coroutines.async4import kotlinx.coroutines.withTimeoutOrNull5import kotlinx.coroutines.runBlocking6import org.junit.Assert.assertEquals7import org.junit.Assert.assertFalse8import org.junit.Assert.assertNotNull9import org.junit.Assert.assertNull10import org.junit.Assert.assertTrue11import org.junit.Assert.fail12import org.junit.Test131415161718192021class RelayAdoptionInitiatorSourceTest {2223 242526272829 private val HANDSHAKE_TIMEOUT_MS = 5_000L3031 private fun identity(name: String, publicKey: ByteArray) = LocalDeviceIdentity(32 deviceId = "$name-id",33 deviceName = name,34 deviceType = if (name == "phone") DeviceType.ANDROID else DeviceType.EXTENSION,35 longTermPublicKeyHex = Rendezvous.bytesToHex(publicKey),36 signingPublicKeyHex = "cd".repeat(32),37 wsPort = 49142,38 relayUrl = "wss://relay.example.test",39 )4041 private class MemoryRelaySocket(42 private val inbound: kotlinx.coroutines.channels.Channel<ByteArray>,43 private val outbound: kotlinx.coroutines.channels.Channel<ByteArray>,44 ) : RelayBinarySocket {45 override fun send(frame: ByteArray) {46 check(outbound.trySend(frame.copyOf()).isSuccess)47 }4849 override suspend fun receive(): ByteArray = inbound.receive()50 override fun close(code: Int, reason: String) {51 outbound.close()52 }53 }5455 private fun socketPair(): Pair<RelayBinarySocket, RelayBinarySocket> {56 val leftToRight = kotlinx.coroutines.channels.Channel<ByteArray>(57 kotlinx.coroutines.channels.Channel.UNLIMITED,58 )59 val rightToLeft = kotlinx.coroutines.channels.Channel<ByteArray>(60 kotlinx.coroutines.channels.Channel.UNLIMITED,61 )62 return MemoryRelaySocket(rightToLeft, leftToRight) to63 MemoryRelaySocket(leftToRight, rightToLeft)64 }6566 @Test fun `phone source sends grant to empty responder over a real Noise channel`() = runBlocking {67 val (phoneSocket, responderSocket) = socketPair()68 val token = "AAECAwQFBgcICQoLDA0ODw"69 val relay = "wss://relay.example.test"70 val root = ByteArray(32) { (it + 5).toByte() }71 val phoneKeys = deriveLocalSyncKeypair(root, "phone-id")72 val responderKeys = deriveLocalSyncKeypair(root, "responder-id")73 val phoneIdentity = identity("phone", phoneKeys.publicKey)74 val responderIdentity = identity("responder", responderKeys.publicKey)75 var phoneStored: PairedDevice? = null7677 val phoneJob = async {78 runRelayAdoptionInitiatorSourceSession(79 socket = phoneSocket,80 invitation = PairingInvitation(81 relay,82 token,83 VaultStatus.EMPTY,84 Rendezvous.bytesToHex(responderKeys.publicKey),85 ),86 sourceDeps = object : AdoptionSourceDeps {87 override val sourceIdentity = phoneIdentity88 override suspend fun rootKeyHex() = Rendezvous.bytesToHex(root)89 override suspend fun vaultId() = computeVaultId(root)90 override suspend fun license() = "PPK-test"91 override suspend fun onConsent(request: AdoptionFrame.Request) = true92 override suspend fun upsertPairedDevice(device: PairedDevice) {93 phoneStored = device94 }95 },96 confirm = { sas, request ->97 assertEquals(responderIdentity.deviceName, request.deviceName)98 assertEquals("extension", request.deviceType)99 assertEquals(8, sas.length)100 true101 },102 )103 }104105 106 val hello = org.json.JSONObject(String(responderSocket.receive()))107 assertEquals("PEACH_HELLO", hello.optString("type"))108 assertEquals(token, hello.optString("token"))109 responderSocket.send(110 org.json.JSONObject().put("type", "PEACH_HELLO_ACK")111 .put("ephemeralPublicKeyHex", Rendezvous.bytesToHex(responderKeys.publicKey))112 .toString().toByteArray(),113 )114 val noise = noiseNKResponder(115 responderKeys.secretKey,116 responderKeys.publicKey,117 responderSocket::send,118 responderSocket::receive,119 )120 var responderStored: PairedDevice? = null121 try {122 val channel = object : PairingTransport {123 override suspend fun send(msg: ByteArray) = responderSocket.send(noise.encrypt(msg))124 override suspend fun receive(): ByteArray = noise.decrypt(responderSocket.receive())125 override suspend fun close() = responderSocket.close()126 }127 128 129 val responderJob = async {130 requestAdoption(131 channel = channel,132 deps = object : AdoptionReceiverDeps {133 override val deviceName = responderIdentity.deviceName134 override val deviceType = DeviceType.EXTENSION135 override fun generateDeviceId() = "session-only"136 override suspend fun confirmSas() = true137 override suspend fun createVaultFromRootKey(rootKeyHex: String): String {138 assertEquals(Rendezvous.bytesToHex(root), rootKeyHex)139 return computeVaultId(hexToPubkey(rootKeyHex))140 }141 override suspend fun deriveLocalIdentity() = responderIdentity142 override suspend fun upsertPairedDevice(device: PairedDevice) {143 responderStored = device144 }145 override fun onError(error: String) = throw AssertionError(error)146 },147 )148 }149 assertNotNull(responderJob.await())150 } finally {151 noise.close()152 }153154 assertNotNull(phoneJob.await())155 assertNotNull(phoneStored)156 assertNotNull(responderStored)157 assertEquals("responder-id", phoneStored?.deviceId)158 assertEquals(responderIdentity.deviceName, phoneStored?.deviceName)159 assertEquals(relay, phoneStored?.relayUrl)160 assertEquals(64, phoneStored?.rendezvousSecretHex?.length)161 162 assertEquals("phone-id", responderStored?.deviceId)163 assertEquals(phoneIdentity.deviceName, responderStored?.deviceName)164 }165166 @Test fun `phone source rotates after browser rejects its revoked identity`() = runBlocking {167 val (phoneSocket, responderSocket) = socketPair()168 val token = "AAECAwQFBgcICQoLDA0ODw"169 val relay = "wss://relay.example.test"170 val root = ByteArray(32) { (it + 19).toByte() }171 val phoneKeys = deriveLocalSyncKeypair(root, "phone-id")172 val responderKeys = deriveLocalSyncKeypair(root, "responder-id")173 val phoneIdentity = identity("phone", phoneKeys.publicKey)174 val rotatedPhoneIdentity = identity(175 "phone-fresh",176 deriveLocalSyncKeypair(root, "phone-fresh-id").publicKey,177 ).copy(deviceId = "phone-fresh-id")178 val responderIdentity = identity("responder", responderKeys.publicKey)179 var rotations = 0180181 val phoneJob = async {182 runRelayAdoptionInitiatorSourceSession(183 socket = phoneSocket,184 invitation = PairingInvitation(185 relay,186 token,187 VaultStatus.EMPTY,188 Rendezvous.bytesToHex(responderKeys.publicKey),189 ),190 sourceDeps = object : AdoptionSourceDeps {191 override val sourceIdentity = phoneIdentity192 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 rotateSourceIdentity(): LocalDeviceIdentity {197 rotations++198 return rotatedPhoneIdentity199 }200 override suspend fun upsertPairedDevice(device: PairedDevice) = Unit201 },202 confirm = { _, _ -> true },203 )204 }205206 val hello = org.json.JSONObject(String(responderSocket.receive()))207 assertEquals("PEACH_HELLO", hello.optString("type"))208 responderSocket.send(209 org.json.JSONObject().put("type", "PEACH_HELLO_ACK")210 .put("ephemeralPublicKeyHex", Rendezvous.bytesToHex(responderKeys.publicKey))211 .toString().toByteArray(),212 )213 val noise = noiseNKResponder(214 responderKeys.secretKey,215 responderKeys.publicKey,216 responderSocket::send,217 responderSocket::receive,218 )219 try {220 val channel = object : PairingTransport {221 override suspend fun send(msg: ByteArray) = responderSocket.send(noise.encrypt(msg))222 override suspend fun receive(): ByteArray = noise.decrypt(responderSocket.receive())223 override suspend fun close() = responderSocket.close()224 }225 val responderJob = async {226 requestAdoption(227 channel,228 object : AdoptionReceiverDeps {229 override val deviceName = responderIdentity.deviceName230 override val deviceType = DeviceType.EXTENSION231 override fun generateDeviceId() = "session-only"232 override suspend fun confirmSas() = true233 override suspend fun createVaultFromRootKey(rootKeyHex: String) =234 computeVaultId(hexToPubkey(rootKeyHex))235 override suspend fun deriveLocalIdentity() = responderIdentity236 override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source) =237 source.deviceId == phoneIdentity.deviceId238 override suspend fun upsertPairedDevice(device: PairedDevice) = Unit239 override fun onError(error: String) = throw AssertionError(error)240 },241 )242 }243 assertNotNull(withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { responderJob.await() })244 } finally {245 noise.close()246 }247248 assertNotNull(withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() })249 assertEquals(1, rotations)250 }251252 253 254 255 256 257 258 259260261262263264 private suspend fun attackerReceivesGrant(265 socket: RelayBinarySocket,266 keys: SyncIdentityKeypair,267 ) {268 val noise = noiseNKResponder(keys.secretKey, keys.publicKey, socket::send, socket::receive)269 try {270 val channel = object : PairingTransport {271 override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))272 override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())273 override suspend fun close() = socket.close()274 }275 sendFrame(channel, AdoptionFrame.Request("attacker-session", "Empty Browser", "extension"))276 receiveFrame(channel)277 } finally {278 noise.close()279 }280 }281282 @Test fun `phone source rejects a substituted ACK static`() = runBlocking {283 val (phoneSocket, mitmSocket) = socketPair()284 val token = "AAECAwQFBgcICQoLDA0ODw"285 val root = ByteArray(32) { (it + 7).toByte() }286 val responderKeys = deriveLocalSyncKeypair(root, "responder-id")287 val attackerKeys = deriveLocalSyncKeypair(root, "attacker-id")288 var rootRequested = false289290 291 292 val phoneJob = async {293 try {294 runRelayAdoptionInitiatorSourceSession(295 socket = phoneSocket,296 invitation = PairingInvitation(297 "wss://relay.example.test",298 token,299 VaultStatus.EMPTY,300 Rendezvous.bytesToHex(responderKeys.publicKey),301 ),302 sourceDeps = object : AdoptionSourceDeps {303 override val sourceIdentity =304 identity("phone", deriveLocalSyncKeypair(root, "phone-id").publicKey)305 override suspend fun rootKeyHex(): String {306 rootRequested = true307 return Rendezvous.bytesToHex(root)308 }309 override suspend fun vaultId() = computeVaultId(root)310 override suspend fun onConsent(request: AdoptionFrame.Request) = true311 override suspend fun upsertPairedDevice(device: PairedDevice) = Unit312 },313 confirm = { _, _ -> true },314 )315 "completed"316 } catch (expected: IllegalArgumentException) {317 expected.message318 }319 }320321 mitmSocket.receive() 322 323 mitmSocket.send(324 org.json.JSONObject().put("type", "PEACH_HELLO_ACK")325 .put("ephemeralPublicKeyHex", Rendezvous.bytesToHex(attackerKeys.publicKey))326 .toString().toByteArray(),327 )328 329 330 val attackerJob = async { attackerReceivesGrant(mitmSocket, attackerKeys) }331332 333 334 assertEquals(335 "pairing_static_key_mismatch",336 withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() },337 )338 attackerJob.cancel()339 assertFalse("root key must never be read against a substituted static", rootRequested)340 }341342 @Test fun `phone source rejects an invitation that pins no static key`() = runBlocking {343 val (phoneSocket, mitmSocket) = socketPair()344 val root = ByteArray(32) { (it + 23).toByte() }345 val attackerKeys = deriveLocalSyncKeypair(root, "attacker-id")346347 val phoneJob = async {348 try {349 runRelayAdoptionInitiatorSourceSession(350 socket = phoneSocket,351 352 353 invitation = PairingInvitation(354 "wss://relay.example.test",355 "AAECAwQFBgcICQoLDA0ODw",356 VaultStatus.EMPTY,357 ),358 sourceDeps = object : AdoptionSourceDeps {359 override val sourceIdentity =360 identity("phone", deriveLocalSyncKeypair(root, "phone-id").publicKey)361 override suspend fun rootKeyHex() = Rendezvous.bytesToHex(root)362 override suspend fun vaultId() = computeVaultId(root)363 override suspend fun onConsent(request: AdoptionFrame.Request) = true364 override suspend fun upsertPairedDevice(device: PairedDevice) = Unit365 },366 confirm = { _, _ -> true },367 )368 "completed"369 } catch (expected: IllegalArgumentException) {370 expected.message371 }372 }373374 mitmSocket.receive() 375 mitmSocket.send(376 org.json.JSONObject().put("type", "PEACH_HELLO_ACK")377 .put("ephemeralPublicKeyHex", Rendezvous.bytesToHex(attackerKeys.publicKey))378 .toString().toByteArray(),379 )380 val attackerJob = async { attackerReceivesGrant(mitmSocket, attackerKeys) }381382 assertEquals(383 "pairing_invitation_missing_static_key",384 withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) { phoneJob.await() },385 )386 attackerJob.cancel()387 }388389 @Test fun `phone source never reads or sends a grant when SAS is rejected`() = runBlocking {390 val (phoneSocket, responderSocket) = socketPair()391 val token = "AAECAwQFBgcICQoLDA0ODw"392 val root = ByteArray(32) { (it + 11).toByte() }393 val phoneKeys = deriveLocalSyncKeypair(root, "phone-id")394 val responderKeys = deriveLocalSyncKeypair(root, "responder-id")395 var rootRequested = false396 var upserted = false397398 val phoneJob = async {399 runRelayAdoptionInitiatorSourceSession(400 socket = phoneSocket,401 invitation = PairingInvitation(402 "wss://relay.example.test",403 token,404 VaultStatus.EMPTY,405 Rendezvous.bytesToHex(responderKeys.publicKey),406 ),407 sourceDeps = object : AdoptionSourceDeps {408 override val sourceIdentity = identity("phone", phoneKeys.publicKey)409 override suspend fun rootKeyHex(): String {410 rootRequested = true411 return Rendezvous.bytesToHex(root)412 }413 override suspend fun vaultId() = computeVaultId(root)414 override suspend fun onConsent(request: AdoptionFrame.Request) = true415 override suspend fun upsertPairedDevice(device: PairedDevice) {416 upserted = true417 }418 },419 confirm = { _, _ -> false },420 )421 }422423 424 responderSocket.receive() 425 responderSocket.send(426 org.json.JSONObject().put("type", "PEACH_HELLO_ACK")427 .put("ephemeralPublicKeyHex", Rendezvous.bytesToHex(responderKeys.publicKey))428 .toString().toByteArray(),429 )430 val noise = noiseNKResponder(431 responderKeys.secretKey,432 responderKeys.publicKey,433 responderSocket::send,434 responderSocket::receive,435 )436 try {437 val channel = object : PairingTransport {438 override suspend fun send(msg: ByteArray) = responderSocket.send(noise.encrypt(msg))439 override suspend fun receive(): ByteArray = noise.decrypt(responderSocket.receive())440 override suspend fun close() = responderSocket.close()441 }442 443 444 sendFrame(channel, AdoptionFrame.Request("session-only", "Empty Browser", "extension"))445 } finally {446 noise.close()447 }448449 assertNull(phoneJob.await())450 assertFalse("root key must stay on this device until SAS matches", rootRequested)451 assertFalse("paired-device store must not be touched on rejection", upserted)452 }453}454455456457458459460461462class RelayAdoptionReceiverDispatchTest {463464 @Test fun `adopt rejects empty invitations so the source path is used instead`() = runBlocking {465 val receiver = RelayAdoptionReceiver()466 val empty = createPairingInvitation(467 "wss://relay.example.test",468 "AAECAwQFBgcICQoLDA0ODw",469 VaultStatus.EMPTY,470 )471 try {472 receiver.adopt(473 encodedInvitation = empty,474 deps = object : AdoptionReceiverDeps {475 override val deviceName = "phone"476 override val deviceType = DeviceType.ANDROID477 override fun generateDeviceId() = "x"478 override suspend fun confirmSas() = true479 override suspend fun createVaultFromRootKey(rootKeyHex: String) = "v"480 override suspend fun deriveLocalIdentity() = error("unused")481 override suspend fun upsertPairedDevice(device: PairedDevice) = Unit482 override fun onError(error: String) = Unit483 },484 confirm = { true },485 )486 fail("adopt must reject empty invitations")487 } catch (expected: IllegalArgumentException) {488 assertTrue(489 "expected vaultStatus in the error, got: ${expected.message}",490 expected.message!!.contains("EMPTY", ignoreCase = true),491 )492 }493 }494495 @Test fun `grantFromInvitation rejects populated invitations so the receiver path is used instead`() = runBlocking {496 val receiver = RelayAdoptionReceiver()497 val populated = createPairingInvitation(498 "wss://relay.example.test",499 "AAECAwQFBgcICQoLDA0ODw",500 VaultStatus.POPULATED,501 )502 try {503 receiver.grantFromInvitation(504 encodedInvitation = populated,505 sourceDeps = object : AdoptionSourceDeps {506 override val sourceIdentity = LocalDeviceIdentity(507 "phone", "phone", DeviceType.ANDROID,508 "ab".repeat(32), "cd".repeat(32),509 )510 override suspend fun rootKeyHex() = "ab".repeat(32)511 override suspend fun vaultId() = "cd".repeat(32)512 override suspend fun onConsent(request: AdoptionFrame.Request) = true513 override suspend fun upsertPairedDevice(device: PairedDevice) = Unit514 },515 confirm = { _, _ -> true },516 )517 fail("grantFromInvitation must reject populated invitations")518 } catch (expected: IllegalArgumentException) {519 assertTrue(520 "expected vaultStatus in the error, got: ${expected.message}",521 expected.message!!.contains("POPULATED", ignoreCase = true),522 )523 }524 }525}