1package com.peachpasswords.sync23import java.io.BufferedReader4import java.io.BufferedWriter5import java.io.File6import java.io.InputStreamReader7import java.io.OutputStreamWriter8import java.net.InetSocketAddress9import java.net.ServerSocket10import java.net.Socket11import java.util.Base6412import kotlin.system.exitProcess13import kotlinx.coroutines.runBlocking14import org.junit.Assert.assertEquals15import org.junit.Test16171819202122232425262728class CrossClientSyncProcessTest {29 @Test30 fun exchange_production_frames_with_browser_process() {31 val mode = configured("PEACH_SYNC_HARNESS_MODE") ?: return32 val portFile = File(requireConfigured("PEACH_SYNC_HARNESS_PORT_FILE"))33 val transcriptFile = File(requireConfigured("PEACH_SYNC_HARNESS_TRANSCRIPT_FILE"))34 val config = HarnessConfig.read(if (mode == "initiator") "android" else "browser", ::configured)35 val socket = if (mode == "initiator") {36 ServerSocket(0).also {37 portFile.writeText(it.localPort.toString())38 }.accept().also { portFile.delete() }39 } else {40 Socket().also {41 it.connect(InetSocketAddress("127.0.0.1", requireConfigured("PEACH_SYNC_HARNESS_PORT").toInt()), 5_000)42 }43 }4445 socket.use { raw ->46 val input = BufferedReader(InputStreamReader(raw.getInputStream(), Charsets.UTF_8))47 val output = BufferedWriter(OutputStreamWriter(raw.getOutputStream(), Charsets.UTF_8))48 val transcript = mutableListOf<String>()49 val vault = ProcessVault(config)50 51 52 val die: () -> Nothing = {53 transcriptFile.writeText(renderTranscript("DIED", null, vault, transcript))54 exitProcess(7)55 }56 val session = SyncSession(57 remoteStaticPublicKey = ByteArray(32) { 7 },58 send = { bytes ->59 val message = decodeSyncMessage(bytes)60 val wireMessage = if (config.mismatch && message is SyncMessage.Manifest) {61 SyncMessage.Request(emptyList())62 } else {63 message64 }65 transcript += "send:${messageType(wireMessage)}"66 if (config.stopAfter == messageType(wireMessage)) die()67 val padded = SyncPadding.pad(wireMessage.encodeToBytes())68 output.write(Base64.getEncoder().encodeToString(padded))69 output.newLine()70 output.flush()71 },72 receive = {73 val line = input.readLine() ?: error("cross-client peer closed")74 val payload = SyncPadding.unpad(Base64.getDecoder().decode(line))75 transcript += "recv:${messageType(decodeSyncMessage(payload))}"76 payload77 },78 close = {},79 )80 val outcome = runBlocking {81 if (mode == "initiator") {82 runSyncInitiator(session, vault, nowMs = System.currentTimeMillis())83 } else {84 runSyncResponder(session, vault, nowMs = System.currentTimeMillis())85 }86 }87 88 89 90 if (config.drain) {91 runCatching {92 raw.soTimeout = 2_00093 while (input.readLine() != null) Unit94 }95 }96 transcriptFile.writeText(renderTranscript(outcome.status.name, outcome, vault, transcript))97 assertEquals(98 "Android process sync outcome",99 config.expectStatus,100 outcome.status,101 )102 }103 }104105 private fun renderTranscript(106 status: String,107 outcome: SyncOutcome?,108 vault: ProcessVault,109 transcript: List<String>,110 ): String = buildString {111 append("{\"status\":\"").append(status).append("\"")112 outcome?.error?.let { append(",\"error\":\"").append(it.replace("\"", "\\\"")).append("\"") }113 append(",\"entriesSent\":").append(outcome?.entriesSent ?: 0)114 append(",\"entriesReceived\":").append(outcome?.entriesReceived ?: 0)115 append(",\"applied\":").append(vault.appliedCount)116 append(",\"staged\":").append(vault.stagedCount)117 append(",\"events\":[")118 transcript.forEachIndexed { index, event ->119 if (index > 0) append(',')120 append('"').append(event).append('"')121 }122 append("]}")123 }124125 private fun configured(name: String): String? =126 System.getenv(name) ?: System.getProperty(name.lowercase().replace('_', '.'))127128 private fun requireConfigured(name: String): String =129 configured(name) ?: error("missing $name")130131 private fun messageType(message: SyncMessage): String = when (message) {132 is SyncMessage.Hello -> "SYNC_HELLO"133 is SyncMessage.Manifest -> "SYNC_MANIFEST"134 is SyncMessage.Request -> "SYNC_REQUEST"135 is SyncMessage.Entries -> "SYNC_ENTRIES"136 is SyncMessage.Tombstones -> "SYNC_TOMBSTONES"137 is SyncMessage.DeviceManifest -> "SYNC_DEVICE_MANIFEST"138 is SyncMessage.Done -> "SYNC_DONE"139 is SyncMessage.Error -> "SYNC_ERROR"140 }141142 143 private class HarnessConfig(144 val id: String,145 val parity: String,146 val localVersion: Long,147 val vaultId: String,148 val manifestSupport: Boolean,149 val entryCount: Int,150 val expectStatus: SyncOutcomeStatus,151 val drain: Boolean,152 val mismatch: Boolean,153 val locked: Boolean,154 val stopAfter: String?,155 ) {156 companion object {157 fun read(id: String, configured: (String) -> String?) = HarnessConfig(158 id = id,159 parity = configured("PEACH_SYNC_HARNESS_MTIME_PARITY") ?: "",160 localVersion = configured("PEACH_SYNC_HARNESS_LOCAL_VERSION")?.toLongOrNull() ?: 7L,161 vaultId = configured("PEACH_SYNC_HARNESS_VAULT_ID") ?: "cross-client-vault",162 manifestSupport = configured("PEACH_SYNC_HARNESS_MANIFEST_VERSION") != "3",163 entryCount = configured("PEACH_SYNC_HARNESS_ENTRY_COUNT")?.toIntOrNull() ?: 1,164 expectStatus = SyncOutcomeStatus.valueOf(165 configured("PEACH_SYNC_HARNESS_EXPECT_STATUS") ?: "COMPLETED",166 ),167 drain = configured("PEACH_SYNC_HARNESS_DRAIN") == "1",168 mismatch = configured("PEACH_SYNC_HARNESS_MISMATCH") == "message-order",169 170 171 172 locked = configured("PEACH_SYNC_HARNESS_LOCKED") == "1",173 stopAfter = configured("PEACH_SYNC_HARNESS_STOP_AFTER")?.takeIf(String::isNotEmpty),174 )175 }176 }177178 private class ProcessVault(private val config: HarnessConfig) : SyncVaultAdapter {179 private val id = config.id180 181 182 183 184 private val ids = (0 until config.entryCount).map { "shared-entry-$it" }185 private val entries = linkedMapOf<String, Long>().apply {186 ids.forEachIndexed { index, entryId -> put(entryId, mtimeFor(index)) }187 }188 private val blobs = linkedMapOf<String, String>().apply {189 ids.forEachIndexed { index, entryId -> put(entryId, "$id-frame-${index % 8}") }190 }191192 private fun mtimeFor(index: Int): Long {193 if (config.parity.isEmpty()) return 10L194 return if (index % 2 == config.parity.toInt()) 15L else 10L195 }196 private val tombstones = emptyMap<String, Long>()197 private val manifest = SignedDeviceManifest(198 DeviceManifestBody(DEVICE_MANIFEST_VERSION, id, 1_700_000_000_000L, emptyList()),199 "11".repeat(64),200 )201202 203 var appliedCount = 0204 private set205206 207 var stagedCount = 0208 private set209210 private val staged = linkedMapOf<String, String>()211212 override suspend fun computeVaultId() = config.vaultId213 override suspend fun getOurDeviceId() = id214 override suspend fun getLocalVersion() = config.localVersion215 override suspend fun buildEntryManifest() = entries.toMap()216 override suspend fun buildTombstoneManifest() = tombstones217218 override suspend fun getEncryptedEntries(entryIds: List<String>) =219 entryIds.mapNotNull { key -> blobs[key]?.let { key to it } }.toMap()220221 override suspend fun applyEntries(entries: Map<String, String>, remoteManifest: Map<String, Long>) {222 if (config.locked) {223 staged.putAll(entries)224 stagedCount += entries.size225 return226 }227 appliedCount += entries.size228 this.entries.putAll(entries.mapValues { remoteManifest[it.key] ?: 0L })229 blobs.putAll(entries)230 }231232 override suspend fun applyTombstones(tombstones: Map<String, Long>) = Unit233234 override suspend fun buildOutgoingDeviceManifest() =235 if (config.manifestSupport && !config.locked) manifest else null236 override suspend fun applyIncomingDeviceManifest(237 manifest: SignedDeviceManifest,238 authenticatedRemoteStaticPublicKey: ByteArray,239 ) = Unit240241 override val supportsDeviceManifest = config.manifestSupport && !config.locked242 }243}