CrossClientSyncProcessTest.kt

12.8 KB · raw

1package com.peachpasswords.sync23import java.io.BufferedReader4import kotlinx.serialization.json.Json5import java.io.BufferedWriter6import java.io.File7import java.io.InputStreamReader8import java.io.OutputStreamWriter9import java.net.InetSocketAddress10import java.net.ServerSocket11import java.net.Socket12import java.util.Base6413import kotlin.system.exitProcess14import kotlinx.coroutines.runBlocking15import org.junit.Assert.assertEquals16import org.junit.Test1718/**19 * Process endpoint for scripts/check-cross-client-sync.mjs. The socket carries20 * one base64-encoded, production-padded SyncMessage frame per line; the21 * transcript is kept separately so the parent process can assert every ordered22 * wire type.23 *24 * Scenario shape is supplied entirely by the parent — this endpoint reads knobs25 * and does not know what a "scenario" is. Keeping the semantics in the harness26 * is what lets both clients be configured identically and lets a reviewer read27 * the matrix in one place.28 */29class CrossClientSyncProcessTest {30    @Test31    fun exchange_production_frames_with_browser_process() {32        val mode = configured("PEACH_SYNC_HARNESS_MODE") ?: return33        val portFile = File(requireConfigured("PEACH_SYNC_HARNESS_PORT_FILE"))34        val transcriptFile = File(requireConfigured("PEACH_SYNC_HARNESS_TRANSCRIPT_FILE"))35        val config = HarnessConfig.read(if (mode == "initiator") "android" else "browser", ::configured)36        val socket = if (mode == "initiator") {37            ServerSocket(0).also {38                portFile.writeText(it.localPort.toString())39            }.accept().also { portFile.delete() }40        } else {41            Socket().also {42                it.connect(InetSocketAddress("127.0.0.1", requireConfigured("PEACH_SYNC_HARNESS_PORT").toInt()), 5_000)43            }44        }4546        socket.use { raw ->47            val input = BufferedReader(InputStreamReader(raw.getInputStream(), Charsets.UTF_8))48            val output = BufferedWriter(OutputStreamWriter(raw.getOutputStream(), Charsets.UTF_8))49            val transcript = mutableListOf<String>()50            val vault = ProcessVault(config)51            // Simulated process death: the transcript is on disk before the52            // process goes, so the parent can still say what the peer had seen.53            val die: () -> Nothing = {54                transcriptFile.writeText(renderTranscript("DIED", null, vault, transcript))55                exitProcess(7)56            }57            val session = SyncSession(58                remoteStaticPublicKey = ByteArray(32) { 7 },59                send = { bytes ->60                    val message = decodeSyncMessage(bytes)61                    val wireMessage = if (config.mismatch && message is SyncMessage.Manifest) {62                        SyncMessage.Request(emptyList())63                    } else {64                        message65                    }66                    transcript += "send:${messageType(wireMessage)}"67                    if (config.stopAfter == messageType(wireMessage)) die()68                    val padded = SyncPadding.pad(wireMessage.encodeToBytes())69                    output.write(Base64.getEncoder().encodeToString(padded))70                    output.newLine()71                    output.flush()72                },73                receive = {74                    val line = input.readLine() ?: error("cross-client peer closed")75                    val payload = SyncPadding.unpad(Base64.getDecoder().decode(line))76                    transcript += "recv:${messageType(decodeSyncMessage(payload))}"77                    payload78                },79                close = {},80            )81            val outcome = runBlocking {82                if (mode == "initiator") {83                    runSyncInitiator(session, vault, nowMs = System.currentTimeMillis())84                } else {85                    runSyncResponder(session, vault, nowMs = System.currentTimeMillis())86                }87            }88            // A clean stop is only deterministic if our socket is still up when89            // the peer writes its last frame, so hold it open until the peer90            // goes away rather than exiting the instant the round ends.91            if (config.drain) {92                runCatching {93                    raw.soTimeout = 2_00094                    while (input.readLine() != null) Unit95                }96            }97            transcriptFile.writeText(renderTranscript(outcome.status.name, outcome, vault, transcript))98            assertEquals(99                "Android process sync outcome",100                config.expectStatus,101                outcome.status,102            )103        }104    }105106    private fun craftedManifest(config: HarnessConfig): SignedDeviceManifest? =107        config.signedManifestJson?.let {108            json.decodeFromString(SignedDeviceManifest.serializer(), it)109        }110111    /**112     * The production verdict on the peer's manifest. The trusted key stands in113     * for this device's stored issuer key, and every known issuer resolves to114     * it, so a revocation signed by another key fails closed.115     */116    private fun manifestVerdict(config: HarnessConfig, manifest: SignedDeviceManifest, nowMs: Long): String {117        val trustedHex = config.trustedPubkeyHex ?: return "not-checked"118        val accepted = verifyDeviceManifest(119            manifest = manifest,120            issuerSigningPublicKey = hexToPubkey(trustedHex),121            resolveIssuerSigningKeys = { setOf(trustedHex.lowercase()) },122            nowMs = nowMs,123        )124        return if (accepted != null) "accepted" else "rejected"125    }126127    private fun renderTranscript(128        status: String,129        outcome: SyncOutcome?,130        vault: ProcessVault,131        transcript: List<String>,132    ): String = buildString {133        append("{\"status\":\"").append(status).append("\"")134        outcome?.error?.let { append(",\"error\":\"").append(it.replace("\"", "\\\"")).append("\"") }135        append(",\"entriesSent\":").append(outcome?.entriesSent ?: 0)136        append(",\"entriesReceived\":").append(outcome?.entriesReceived ?: 0)137        append(",\"applied\":").append(vault.appliedCount)138        append(",\"staged\":").append(vault.stagedCount)139        append(",\"manifestAccepted\":").append(140            vault.manifestVerdict?.let { it == "accepted" } ?: "null",141        )142        append(",\"events\":[")143        transcript.forEachIndexed { index, event ->144            if (index > 0) append(',')145            append('"').append(event).append('"')146        }147        append("]}")148    }149150    private val json = Json { ignoreUnknownKeys = true }151152    private fun configured(name: String): String? =153        System.getenv(name) ?: System.getProperty(name.lowercase().replace('_', '.'))154155    private fun requireConfigured(name: String): String =156        configured(name) ?: error("missing $name")157158    private fun messageType(message: SyncMessage): String = when (message) {159        is SyncMessage.Hello -> "SYNC_HELLO"160        is SyncMessage.Manifest -> "SYNC_MANIFEST"161        is SyncMessage.Request -> "SYNC_REQUEST"162        is SyncMessage.Entries -> "SYNC_ENTRIES"163        is SyncMessage.Tombstones -> "SYNC_TOMBSTONES"164        is SyncMessage.DeviceManifest -> "SYNC_DEVICE_MANIFEST"165        is SyncMessage.Done -> "SYNC_DONE"166        is SyncMessage.Error -> "SYNC_ERROR"167    }168169    /** Every knob the matrix can set, in one place. Defaults reproduce a plain round. */170    private class HarnessConfig(171        val id: String,172        val parity: String,173        val localVersion: Long,174        val vaultId: String,175        val manifestSupport: Boolean,176        val entryCount: Int,177        val expectStatus: SyncOutcomeStatus,178        val drain: Boolean,179        val mismatch: Boolean,180        val locked: Boolean,181        val stopAfter: String?,182        /**183         * A manifest the harness signed: the wire shape IS the scenario, and one184         * signer keeps both clients verifying the same bytes rather than each185         * signing its own.186         */187        val signedManifestJson: String?,188        val trustedPubkeyHex: String?,189    ) {190        companion object {191            fun read(id: String, configured: (String) -> String?) = HarnessConfig(192                id = id,193                parity = configured("PEACH_SYNC_HARNESS_MTIME_PARITY") ?: "",194                localVersion = configured("PEACH_SYNC_HARNESS_LOCAL_VERSION")?.toLongOrNull() ?: 7L,195                vaultId = configured("PEACH_SYNC_HARNESS_VAULT_ID") ?: "cross-client-vault",196                manifestSupport = configured("PEACH_SYNC_HARNESS_MANIFEST_VERSION") != "3",197                entryCount = configured("PEACH_SYNC_HARNESS_ENTRY_COUNT")?.toIntOrNull() ?: 1,198                expectStatus = SyncOutcomeStatus.valueOf(199                    configured("PEACH_SYNC_HARNESS_EXPECT_STATUS") ?: "COMPLETED",200                ),201                drain = configured("PEACH_SYNC_HARNESS_DRAIN") == "1",202                mismatch = configured("PEACH_SYNC_HARNESS_MISMATCH") == "message-order",203                // A locked session may hold the transport key and stage204                // ciphertext, but it never authors or applies a device manifest205                // and never merges entries into the live vault (PB-26-112 C).206                locked = configured("PEACH_SYNC_HARNESS_LOCKED") == "1",207                stopAfter = configured("PEACH_SYNC_HARNESS_STOP_AFTER")?.takeIf(String::isNotEmpty),208                signedManifestJson = configured("PEACH_SYNC_HARNESS_SIGNED_MANIFEST")?.takeIf(String::isNotEmpty),209                trustedPubkeyHex = configured("PEACH_SYNC_HARNESS_TRUSTED_PUBKEY")?.takeIf(String::isNotEmpty),210            )211        }212    }213214    private inner class ProcessVault(private val config: HarnessConfig) : SyncVaultAdapter {215        private val id = config.id216        // Entries are shared ids so a diff can actually flow. Parity decides217        // which side is newer for a given index: the same parity on both sides218        // means equal data versions, opposite parities means entries flow both219        // ways. Must stay identical to the Browser endpoint's rule.220        private val ids = (0 until config.entryCount).map { "shared-entry-$it" }221        private val entries = linkedMapOf<String, Long>().apply {222            ids.forEachIndexed { index, entryId -> put(entryId, mtimeFor(index)) }223        }224        private val blobs = linkedMapOf<String, String>().apply {225            ids.forEachIndexed { index, entryId -> put(entryId, "$id-frame-${index % 8}") }226        }227228        private fun mtimeFor(index: Int): Long {229            if (config.parity.isEmpty()) return 10L230            return if (index % 2 == config.parity.toInt()) 15L else 10L231        }232        private val tombstones = emptyMap<String, Long>()233        private val manifest = SignedDeviceManifest(234            DeviceManifestBody(DEVICE_MANIFEST_VERSION, id, 1_700_000_000_000L, emptyList()),235            "11".repeat(64),236        )237238        /** The production verdict on the peer's manifest, or null if none arrived. */239        var manifestVerdict: String? = null240            private set241242        private val nowMs = System.currentTimeMillis()243        private val crafted: SignedDeviceManifest? = craftedManifest(config)244245        /** Entries this side merged into its live vault. */246        var appliedCount = 0247            private set248249        /** Entries this side only staged because the vault is locked. */250        var stagedCount = 0251            private set252253        private val staged = linkedMapOf<String, String>()254255        override suspend fun computeVaultId() = config.vaultId256        override suspend fun getOurDeviceId() = id257        override suspend fun getLocalVersion() = config.localVersion258        override suspend fun buildEntryManifest() = entries.toMap()259        override suspend fun buildTombstoneManifest() = tombstones260261        override suspend fun getEncryptedEntries(entryIds: List<String>) =262            entryIds.mapNotNull { key -> blobs[key]?.let { key to it } }.toMap()263264        override suspend fun applyEntries(entries: Map<String, String>, remoteManifest: Map<String, Long>) {265            if (config.locked) {266                staged.putAll(entries)267                stagedCount += entries.size268                return269            }270            appliedCount += entries.size271            this.entries.putAll(entries.mapValues { remoteManifest[it.key] ?: 0L })272            blobs.putAll(entries)273        }274275        override suspend fun applyTombstones(tombstones: Map<String, Long>) = Unit276277        override suspend fun buildOutgoingDeviceManifest() =278            if (!config.manifestSupport || config.locked) null else crafted ?: manifest279280        override suspend fun applyIncomingDeviceManifest(281            manifest: SignedDeviceManifest,282            authenticatedRemoteStaticPublicKey: ByteArray,283        ) {284            manifestVerdict = manifestVerdict(config, manifest, nowMs)285        }286287        override val supportsDeviceManifest = config.manifestSupport && !config.locked288    }289}