12package com.peachpasswords.sync34import kotlinx.coroutines.Dispatchers5import kotlinx.coroutines.launch6import kotlinx.coroutines.runBlocking7import kotlinx.coroutines.withContext8import kotlinx.serialization.builtins.ListSerializer9import kotlinx.serialization.json.Json10import org.bouncycastle.crypto.params.X25519PrivateKeyParameters11import org.junit.Assert.assertArrayEquals12import org.junit.Assert.assertEquals13import org.junit.Assert.assertNotNull14import org.junit.Assert.assertTrue15import org.junit.Test16import java.io.PipedInputStream17import java.io.PipedOutputStream18import java.security.SecureRandom192021222324252627282930class C7ChirpTransportTest {3132 private val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }33 private val listSerializer = ListSerializer(PairedDevice.serializer())3435 private fun newKeyPair(): Pair<ByteArray, ByteArray> {36 val priv = X25519PrivateKeyParameters(SecureRandom())37 return priv.encoded to priv.generatePublicKey().encoded38 }3940 private fun device(id: String, name: String = "Peer") = PairedDevice(41 deviceId = id,42 deviceName = name,43 deviceType = "android",44 longTermPublicKeyHex = "ab".repeat(32),45 trustSource = "direct",46 pairedAt = 1_000L,47 lastSyncedAt = null,48 )4950 51 @Test52 fun `paired device list round-trips through json`() {53 val devices = listOf(device("a", "Alice"), device("b", "Bob"))54 val encoded = json.encodeToString(listSerializer, devices)55 val decoded = json.decodeFromString(listSerializer, encoded)56 assertEquals(devices, decoded)57 assertEquals("Alice", decoded[0].deviceName)58 assertEquals("ab".repeat(32), decoded[1].longTermPublicKeyHex)59 }6061 62 @Test63 fun `upsert by deviceId replaces rather than duplicates`() {64 65 fun upsert(list: List<PairedDevice>, d: PairedDevice) =66 list.filterNot { it.deviceId == d.deviceId } + d6768 var list = listOf(device("a", "Alice"))69 list = upsert(list, device("b", "Bob"))70 assertEquals(2, list.size)71 list = upsert(list, device("a", "Alice-renamed"))72 assertEquals(2, list.size)73 assertEquals("Alice-renamed", list.first { it.deviceId == "a" }.deviceName)74 }7576 77 @Test78 fun `frame codec round-trips for various sizes`() {79 for (size in intArrayOf(0, 1, 31, 64, 1500, 65_537)) {80 val payload = ByteArray(size) { (it % 251).toByte() }81 val pin = PipedInputStream(1 shl 18)82 val pout = PipedOutputStream(pin)83 writeFrame(pout, payload)84 val read = readFrame(pin)85 assertArrayEquals("size=$size", payload, read)86 }87 }8889 909192939495 @Test96 fun `noise NK handshake over frames yields matching SAS and decodable identity`() = runBlocking {97 val (responderPriv, responderPub) = newKeyPair()9899 100 val i2r = PipedInputStream(1 shl 18); val i2rOut = PipedOutputStream(i2r)101 val r2i = PipedInputStream(1 shl 18); val r2iOut = PipedOutputStream(r2i)102103 val initiator = SocketFrameIO(input = r2i, output = i2rOut)104 val responder = SocketFrameIO(input = i2r, output = r2iOut)105106 val localId = LocalChirpIdentity(107 deviceId = "client-1",108 deviceName = "Client",109 deviceType = DeviceType.ANDROID,110 longTermPublicKeyHex = "cd".repeat(32),111 signingPublicKeyHex = "ef".repeat(32),112 )113 val serverId = localId.copy(deviceId = "server-1", deviceName = "Server")114115 var initiatorSas: String? = null116 var responderSas: String? = null117 var receivedByServer: PairIdentity? = null118119 val responderJob = launch(Dispatchers.IO) {120 val session = noiseNKResponder(responderPriv, responderPub, responder::send, responder::receive)121 receivedByServer = parsePairIdentityFrame(session.decrypt(responder.receive()))122 responder.send(session.encrypt(encodePairIdentityFrame(serverId)))123 responderSas = SASDerivation.derive(session.handshakeHash)124 }125126 val initiatorJob = launch(Dispatchers.IO) {127 val session = noiseNKInitiator(responderPub, initiator::send, initiator::receive)128 initiator.send(session.encrypt(encodePairIdentityFrame(localId)))129 session.decrypt(initiator.receive()) 130 initiatorSas = SASDerivation.derive(session.handshakeHash)131 }132133 initiatorJob.join()134 responderJob.join()135136 assertNotNull(initiatorSas)137 assertEquals("both sides derive the same SAS", initiatorSas, responderSas)138 assertEquals("client-1", receivedByServer?.deviceId)139 assertEquals("cd".repeat(32), receivedByServer?.longTermPublicKeyHex)140 }141142 143144145146147 @Test148 fun `handshake fails when responder static key is wrong`() = runBlocking {149 val (responderPriv, responderPub) = newKeyPair()150 val (_, wrongPub) = newKeyPair()151152 val i2r = PipedInputStream(1 shl 18); val i2rOut = PipedOutputStream(i2r)153 val r2i = PipedInputStream(1 shl 18); val r2iOut = PipedOutputStream(r2i)154 val initiator = SocketFrameIO(input = r2i, output = i2rOut)155 val responder = SocketFrameIO(input = i2r, output = r2iOut)156157 val responderJob = launch(Dispatchers.IO) {158 runCatching { noiseNKResponder(responderPriv, responderPub, responder::send, responder::receive) }159 }160161 var initiatorFailed = false162 val initiatorJob = launch(Dispatchers.IO) {163 try {164 165 noiseNKInitiator(wrongPub, initiator::send, initiator::receive)166 } catch (_: Throwable) {167 initiatorFailed = true168 }169 }170171 withContext(Dispatchers.IO) {172 initiatorJob.join()173 responderJob.cancel()174 }175 assertTrue("initiator handshake must reject the wrong responder key", initiatorFailed)176 }177}