package com.peachpasswords.sync import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test /** * Inline vault snapshot protocol parity with the browser * `vault-adopt-snapshot.test.ts`. Round-trip, chunking, and validation * tests for the ADOPT_SNAPSHOT / ADOPT_SNAPSHOT_APPLIED frames. */ class VaultAdoptSnapshotTest { private fun memoryPair(): Pair { val a2b = Channel(Channel.UNLIMITED) val b2a = Channel(Channel.UNLIMITED) val a = object : PairingTransport { override suspend fun send(msg: ByteArray) { a2b.send(msg) } override suspend fun receive(): ByteArray = b2a.receive() override suspend fun close() {} } val b = object : PairingTransport { override suspend fun send(msg: ByteArray) { b2a.send(msg) } override suspend fun receive(): ByteArray = a2b.receive() override suspend fun close() {} } return a to b } @Test fun `round-trips an empty vault`() = runBlocking { val (source, receiver) = memoryPair() sendVaultSnapshot(source, emptyMap(), emptyMap()) val (entries, tombstones) = receiveVaultSnapshot(receiver) assertTrue(entries.isEmpty()) assertTrue(tombstones.isEmpty()) } @Test fun `round-trips 50 entries and 5 tombstones in a single chunk`() = runBlocking { val (source, receiver) = memoryPair() val entries = (0 until 50).associate { "id-$it" to "cipher-$it" } val tombstones = (0 until 5).associate { "dead-$it" to (1000L + it) } sendVaultSnapshot(source, entries, tombstones) val (receivedEntries, receivedTombstones) = receiveVaultSnapshot(receiver) assertEquals(entries, receivedEntries) assertEquals(tombstones, receivedTombstones) } @Test fun `splits a large vault into 3+ chunks and reassembles`() = runBlocking { val (source, receiver) = memoryPair() var frames = 0 val countingSource = object : PairingTransport { override suspend fun send(msg: ByteArray) { frames++; source.send(msg) } override suspend fun receive(): ByteArray = source.receive() override suspend fun close() {} } val big = "x".repeat(200 * 1024) val entries = (0 until 5).associate { "id-$it" to big } val tombstones = mapOf("dead-0" to 42L) sendVaultSnapshot(countingSource, entries, tombstones) val (receivedEntries, receivedTombstones) = receiveVaultSnapshot(receiver) assertTrue("expected 3+ chunks, got $frames", frames >= 3) assertEquals(entries, receivedEntries) assertEquals(tombstones, receivedTombstones) } @Test fun `rejects out-of-order chunks`() = runBlocking { val (source, receiver) = memoryPair() sendFrame(source, AdoptionFrame.Snapshot( chunkIndex = 1, chunkCount = 2, entries = mapOf("a" to "x"), tombstones = emptyMap(), )) val error = runCatching { receiveVaultSnapshot(receiver) }.exceptionOrNull() assertTrue(error is IllegalStateException) assertTrue(error!!.message!!.contains("OUT_OF_ORDER")) } @Test fun `rejects chunk_count exceeding MAX_SNAPSHOT_CHUNKS`() = runBlocking { val (source, receiver) = memoryPair() sendFrame(source, AdoptionFrame.Snapshot( chunkIndex = 0, chunkCount = MAX_SNAPSHOT_CHUNKS + 1, entries = emptyMap(), tombstones = emptyMap(), )) val error = runCatching { receiveVaultSnapshot(receiver) }.exceptionOrNull() assertTrue(error is IllegalStateException) assertTrue(error!!.message!!.contains("TOO_MANY_CHUNKS")) } @Test fun `validates ADOPT_SNAPSHOT frames`() { val valid = AdoptionFrame.Snapshot( chunkIndex = 0, chunkCount = 1, entries = mapOf("a" to "x"), tombstones = emptyMap(), ) assertTrue(isAdoptSnapshot(valid)) assertTrue(!isAdoptSnapshot(null)) assertTrue(!isAdoptSnapshot(AdoptionFrame.Complete)) } @Test fun `snapshot_capable serializes in ADOPT_REQUEST`() { val request = AdoptionFrame.Request( sessionRequestId = "req-1", deviceName = "test", deviceType = "extension", snapshotCapable = true, ) val json = AdoptJson.encodeToString(AdoptionFrame.serializer(), request) assertTrue(json.contains("\"snapshot_capable\":true")) // Absent when null (encodeDefaults = false) val noFlag = AdoptionFrame.Request( sessionRequestId = "req-2", deviceName = "test", deviceType = "extension", ) val jsonNoFlag = AdoptJson.encodeToString(AdoptionFrame.serializer(), noFlag) assertTrue(!jsonNoFlag.contains("snapshot_capable")) } @Test fun `rejects raw frame exceeding wire ceiling`() = runBlocking { // H-09: a hostile source could send an arbitrarily large frame to exhaust // receiver memory before JSON parsing. receiveVaultSnapshot checks the raw // byte length against SNAPSHOT_FRAME_WIRE_CEILING (512 KiB + 256 KiB = 768 KiB) // and throws before attempting deserialization. val ceiling = MAX_SNAPSHOT_CHUNK_BYTES + 256 * 1024 val oversized = ByteArray(ceiling + 1) val channel = object : PairingTransport { override suspend fun send(msg: ByteArray) {} override suspend fun receive(): ByteArray = oversized override suspend fun close() {} } val error = runCatching { receiveVaultSnapshot(channel) }.exceptionOrNull() assertTrue(error is IllegalStateException) assertTrue(error!!.message!!.contains("CHUNK_TOO_LARGE")) } @Test fun `rejects chunk_count mismatch on subsequent frame`() = runBlocking { val (source, receiver) = memoryPair() sendFrame(source, AdoptionFrame.Snapshot( chunkIndex = 0, chunkCount = 2, entries = mapOf("a" to "x"), tombstones = emptyMap(), )) sendFrame(source, AdoptionFrame.Snapshot( chunkIndex = 1, chunkCount = 3, entries = mapOf("b" to "y"), tombstones = emptyMap(), )) val error = runCatching { receiveVaultSnapshot(receiver) }.exceptionOrNull() assertTrue(error is IllegalStateException) assertTrue(error!!.message!!.contains("CHUNK_COUNT_MISMATCH")) } @Test fun `round-trips duress_slot on final chunk`() = runBlocking { val (source, receiver) = memoryPair() val entries = mapOf("id-0" to "cipher-0") val tombstones = mapOf("dead-0" to 42L) val duressJson = """{"version":1,"salt":"aa","nonce":"bb","ciphertext":"cc","tag":"dd"}""" sendVaultSnapshot(source, entries, tombstones, duressSlot = duressJson) val snapshot = receiveVaultSnapshot(receiver) assertEquals(entries, snapshot.entries) assertEquals(tombstones, snapshot.tombstones) assertEquals(duressJson, snapshot.duressSlot) } @Test fun `duress_slot absent returns null`() = runBlocking { val (source, receiver) = memoryPair() sendVaultSnapshot(source, mapOf("id-0" to "cipher-0"), emptyMap()) val snapshot = receiveVaultSnapshot(receiver) assertNull(snapshot.duressSlot) } @Test fun `duress_slot rides final chunk only in multi-chunk transfer`() = runBlocking { val (source, receiver) = memoryPair() val big = "x".repeat(200 * 1024) val entries = (0 until 5).associate { "id-$it" to big } val tombstones = mapOf("dead-0" to 42L) val duressJson = """{"version":1,"salt":"ff","nonce":"ee","ciphertext":"dd","tag":"cc"}""" sendVaultSnapshot(source, entries, tombstones, duressSlot = duressJson) val snapshot = receiveVaultSnapshot(receiver) assertEquals(entries, snapshot.entries) assertEquals(tombstones, snapshot.tombstones) assertEquals(duressJson, snapshot.duressSlot) } @Test fun `old frame without duress_slot deserializes`() { val oldJson = """{"type":"ADOPT_SNAPSHOT","chunk_index":0,"chunk_count":1,"entries":{"a":"x"},"tombstones":{}}""" val frame = runCatching { AdoptJson.decodeFromString(AdoptionFrame.serializer(), oldJson) }.getOrNull() assertTrue(isAdoptSnapshot(frame)) assertTrue((frame as AdoptionFrame.Snapshot).duressSlot == null) } // Mirrors browser v4.6.4 T-A33: post-fix regression. With duress on // its own frame after the entries chunks, a >768 KiB combined payload // round-trips intact; pre-fix this threw ADOPT_SNAPSHOT_CHUNK_TOO_LARGE. @Test fun `frame ceiling 768KiB duress on separate frame round-trips`() = runBlocking { val (source, receiver) = memoryPair() val entries = mapOf("id-0" to "x".repeat(450 * 1024)) val tombstones = mapOf("dead-0" to 1L) // Build a sealed-duress JSON literal with a 320 KiB ciphertext field // so combined raw payload (450 KiB entry + ~320 KiB duress + envelope) // crosses the 768 KiB SNAPSHOT_FRAME_WIRE_CEILING on the legacy wire. val duressJson = ("""{"version":1,"salt":"${"a".repeat(16)}",""" + """"nonce":"${"b".repeat(12)}",""" + """"ciphertext":"${"c".repeat(320 * 1024)}",""" + """"tag":"${"d".repeat(16)}"}""") sendVaultSnapshot(source, entries, tombstones, duressSlot = duressJson) val snapshot = receiveVaultSnapshot(receiver) assertEquals(entries, snapshot.entries) assertEquals(tombstones, snapshot.tombstones) assertEquals(duressJson, snapshot.duressSlot) } // Mirrors browser v4.6.4 T-A34: structural proof that the duress wire // change is real. With >768 KiB combined, intermediate frames each stay // under the ceiling and exactly two frames are sent (entries + duress). @Test fun `intermediate frame sizes stay under wire ceiling when duress rides its own frame`() = runBlocking { val (source, _) = memoryPair() val observedRawSizes = mutableListOf() val observedHasDuress = mutableListOf() val observedEntriesSize = mutableListOf() val probe = object : PairingTransport { override suspend fun send(msg: ByteArray) { observedRawSizes.add(msg.size) val parsed = runCatching { AdoptJson.decodeFromString(AdoptionFrame.Snapshot.serializer(), String(msg, Charsets.UTF_8)) }.getOrNull() observedHasDuress.add(parsed?.duressSlot != null) observedEntriesSize.add(parsed?.entries?.size ?: 0) source.send(msg) } override suspend fun receive(): ByteArray = source.receive() override suspend fun close() {} } val entries = mapOf("id-0" to "x".repeat(450 * 1024)) val duressJson = "y".repeat(320 * 1024) val ceiling = MAX_SNAPSHOT_CHUNK_BYTES + 256 * 1024 // SNAPSHOT_FRAME_WIRE_CEILING sendVaultSnapshot(probe, entries, mapOf("dead-0" to 1L), duressSlot = duressJson) assertEquals(2, observedRawSizes.size) // Entries frame carries entries, no duress, under ceiling. assertEquals(false, observedHasDuress[0]) assertEquals(1, observedEntriesSize[0]) org.junit.Assert.assertTrue( "entries frame ${observedRawSizes[0]} should be < ceiling $ceiling", observedRawSizes[0] < ceiling ) // Duress frame carries duress, no entries, under ceiling. assertEquals(true, observedHasDuress[1]) assertEquals(0, observedEntriesSize[1]) org.junit.Assert.assertTrue( "duress frame ${observedRawSizes[1]} should be < ceiling $ceiling", observedRawSizes[1] < ceiling ) // The point of the split: combined raw exceeds what a single frame // was permitted to carry on the old wire. org.junit.Assert.assertTrue( "combined raw ${observedRawSizes[0] + observedRawSizes[1]} should exceed ceiling $ceiling", observedRawSizes[0] + observedRawSizes[1] > ceiling ) } // Mirrors browser v4.6.4 T-A35: backward compat with pre-v2.9.9 senders // (duress on entries final chunk). The receiver merges per chunk so both // shapes decode. @Test fun `legacy duress on entries final chunk still decodes`() = runBlocking { val (source, receiver) = memoryPair() val duressJson = """{"version":1,"salt":"aa","nonce":"bb","ciphertext":"cc","tag":"dd"}""" // Manually construct the legacy v2.9.8 wire shape: a single chunk // with entries, tombstones AND duress_slot all on it. sendFrame(source, AdoptionFrame.Snapshot( chunkIndex = 0, chunkCount = 1, entries = mapOf("id-0" to "ciphertext"), tombstones = mapOf("dead-0" to 42L), duressSlot = duressJson, )) val snapshot = receiveVaultSnapshot(receiver) assertEquals(mapOf("id-0" to "ciphertext"), snapshot.entries) assertEquals(mapOf("dead-0" to 42L), snapshot.tombstones) assertEquals(duressJson, snapshot.duressSlot) } // Mirrors browser T-A36: cap boundary inclusive. With 199 entries and a // duress slot, the sender fits everything within MAX_SNAPSHOT_CHUNKS = 200 // (199 entries + 1 duress = 200 frames). Duress MUST arrive intact — sync // does not carry duress. Sequential pattern matches the rest of the file // (channels buffer via UNLIMITED capacity). @Test fun `duress is reserved a frame so 199 entries plus duress fits in MAX_SNAPSHOT_CHUNKS`() = runBlocking { val (source, receiver) = memoryPair() val duressJson = """{"version":1,"salt":"aa","nonce":"bb","ciphertext":"cc","tag":"dd"}""" val big = "x".repeat(450 * 1024) val entries = (0 until 199).associate { "id-$it" to big } sendVaultSnapshot(source, entries, mapOf("dead-0" to 1L), duressSlot = duressJson) val snapshot = receiveVaultSnapshot(receiver) assertEquals(entries, snapshot.entries) assertEquals(mapOf("dead-0" to 1L), snapshot.tombstones) assertEquals(duressJson, snapshot.duressSlot) } // Mirrors browser T-A37: cap boundary exceeded. With 200 entries + duress, // the duress frame is reserved (entry cap = MAX_SNAPSHOT_CHUNKS - 1 = 199), // so duress still arrives intact. Excess entries (one beyond 199) are // deferred to sync. Critically: duress MUST NOT be silently dropped, else // the adopted device lacks its duress vault permanently. @Test fun `200 entries plus duress does not silently drop duress at the chunk cap`() = runBlocking { val (source, receiver) = memoryPair() val duressJson = """{"version":1,"salt":"aa","nonce":"bb","ciphertext":"cc","tag":"dd"}""" val big = "x".repeat(450 * 1024) val entries = (0 until 200).associate { "id-$it" to big } sendVaultSnapshot(source, entries, mapOf("dead-0" to 1L), duressSlot = duressJson) val snapshot = receiveVaultSnapshot(receiver) // Duress MUST arrive intact. assertEquals(duressJson, snapshot.duressSlot) // The inline cap = MAX_SNAPSHOT_CHUNKS - 1 = 199 entries. assertEquals(199, snapshot.entries.size) assertEquals(mapOf("dead-0" to 1L), snapshot.tombstones) } // Cap-pre-check guardrail: a duress payload that itself exceeds the wire // ceiling throws ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE before any frame is // sent — adoption never silently loses duress. @Test fun `duress larger than wire ceiling throws loudly before sending`() = runBlocking { val (source, _) = memoryPair() var frames = 0 val countingSource = object : PairingTransport { override suspend fun send(msg: ByteArray) { frames++; source.send(msg) } override suspend fun receive(): ByteArray = source.receive() override suspend fun close() {} } val duressJson = "x".repeat(800 * 1024) // 800 KiB duress, exceeds 768 KiB ceiling val error = runCatching { sendVaultSnapshot(countingSource, mapOf("id-0" to "small"), emptyMap(), duressSlot = duressJson) }.exceptionOrNull() assertTrue(error is SnapshotDuressFrameTooLargeException) assertEquals(0, frames) } }