C7-ChirpTransportTest.kt

7.5 KB · raw

1// Intended source path: app/src/test/java/com/peachpasswords/sync/C7ChirpTransportTest.kt2package 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.SecureRandom1920/**21 * C7 transport tests. Mirrors the existing ChirpSyncTransportTest idiom: plain22 * JUnit + runBlocking, no Robolectric. PairedDeviceStore itself needs an Android23 * Context (EncryptedSharedPreferences), so its persistence is exercised by the24 * orchestrator's instrumentation tests; here we test the pure-JVM serialization25 * layer the store round-trips through (test 1) plus its upsert/replace semantics26 * against an in-memory list (test 2), the frame codec (test 3), the full27 * Noise-NK-over-frames exchange the server/client share (test 4), and the28 * timeout/error path (test 5).29 */30class 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    /** Test 1: PairedDevice list survives JSON round-trip (the store's wire form). */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    /** Test 2: upsert replaces an existing entry by deviceId (store semantics). */62    @Test63    fun `upsert by deviceId replaces rather than duplicates`() {64        // Mirror PairedDeviceStore.upsert's pure list transform.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    /** Test 3: writeFrame/readFrame round-trip across payload sizes. */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    /**90     * Test 4: a full Noise NK handshake + identity frame exchange over a Piped91     * socket pair — the exact wire the server (responder) and client (initiator)92     * share. Proves the handshake completes, both sides derive the SAME SAS, and93     * an encrypted identity frame decrypts correctly. No real network.94     */95    @Test96    fun `noise NK handshake over frames yields matching SAS and decodable identity`() = runBlocking {97        val (responderPriv, responderPub) = newKeyPair()9899        // Cross-wired pipes: initiator's out -> responder's in and vice versa.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()) // server identity (discarded here)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    /**143     * Test 5: a wrong responder static key fails the initiator handshake — the144     * NK auth tag rejects a MITM / mismatched key, which connectAndSync surfaces145     * as PairingError.HANDSHAKE_FAILED.146     */147    @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                // Initiator pins the WRONG static key; NK msg2 auth must fail.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}