1package com.peachpasswords.sync23import kotlinx.coroutines.async4import kotlinx.coroutines.channels.Channel5import kotlinx.coroutines.runBlocking6import kotlinx.coroutines.withTimeoutOrNull7import org.junit.Assert.assertEquals8import org.junit.Assert.assertFalse9import org.junit.Assert.assertNull10import org.junit.Assert.assertTrue11import org.junit.Test12131415161718class VaultAdoptTest {1920 private fun memoryPair(): Pair<PairingTransport, PairingTransport> {21 val a2b = Channel<ByteArray>(Channel.UNLIMITED)22 val b2a = Channel<ByteArray>(Channel.UNLIMITED)23 val a = object : PairingTransport {24 override suspend fun send(msg: ByteArray) { a2b.send(msg) }25 override suspend fun receive(): ByteArray = b2a.receive()26 override suspend fun close() {}27 }28 val b = object : PairingTransport {29 override suspend fun send(msg: ByteArray) { b2a.send(msg) }30 override suspend fun receive(): ByteArray = a2b.receive()31 override suspend fun close() {}32 }33 return a to b34 }3536 private fun identity(name: String) = LocalDeviceIdentity(37 deviceId = "$name-id",38 deviceName = name,39 deviceType = DeviceType.EXTENSION,40 longTermPublicKeyHex = "ab".repeat(32),41 signingPublicKeyHex = "cd".repeat(32),42 )4344 private fun vaultIdFor(rootKeyHex: String): String {45 val bytes = hexToPubkey(rootKeyHex)46 return try {47 computeVaultId(bytes)48 } finally {49 bytes.fill(0)50 }51 }5253 private open class RecorderReceiver(54 override val deviceName: String,55 override val deviceType: DeviceType,56 private val vaultId: String?,57 private val createThrows: Boolean = false,58 private val derived: LocalDeviceIdentity? = null,59 private val sasConfirmed: Boolean = true,60 private val localLicense: String? = "PPK-test",61 ) : AdoptionReceiverDeps {62 var createCalledWith: String? = null63 var licenseApplied: String? = null64 val revocationsCleared = mutableListOf<String>()65 val upserted = mutableListOf<PairedDevice>()66 val errors = mutableListOf<String>()67 override fun generateDeviceId(): String = "receiver-ephemeral"68 override suspend fun confirmSas(): Boolean = sasConfirmed69 override suspend fun createVaultFromRootKey(rootKeyHex: String): String {70 createCalledWith = rootKeyHex71 if (createThrows) throw IllegalStateException("commit_failed")72 return vaultId ?: error("no vault id")73 }74 override suspend fun deriveLocalIdentity(): LocalDeviceIdentity = derived ?: error("no identity")75 override suspend fun clearPairedDeviceRevocation(deviceId: String) {76 revocationsCleared += deviceId77 }78 override suspend fun upsertPairedDevice(device: PairedDevice) { upserted += device }79 override suspend fun applyLicense(license: String) { licenseApplied = license }80 override suspend fun license(): String? = localLicense81 override fun onError(error: String) { errors += error }82 }8384 private class RecorderSource(85 override val sourceIdentity: LocalDeviceIdentity,86 private val rootKeyHex: String,87 private val vaultId: String,88 license: String? = "PPK-test",89 private val consent: Boolean = true,90 ) : AdoptionSourceDeps {91 private var storedLicense: String? = license92 val upserted = mutableListOf<PairedDevice>()93 var licenseApplied: String? = null94 var consentAsked = false95 var rootRequested = false96 var collidingDeviceId: String? = null97 override suspend fun rootKeyHex(): String {98 rootRequested = true99 return rootKeyHex100 }101 override suspend fun vaultId(): String = vaultId102 override suspend fun license(): String? = storedLicense103 override suspend fun applyLicense(license: String) {104 licenseApplied = license105 storedLicense = license106 }107 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean {108 consentAsked = true109 return consent110 }111 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =112 device.deviceId == collidingDeviceId113 override suspend fun upsertPairedDevice(device: PairedDevice) { upserted += device }114 }115116 @Test fun completes_request_through_mutual_completion_acknowledgements() = runBlocking {117 val (receiverCh, sourceCh) = memoryPair()118 val rootKeyHex = "11".repeat(32)119 val vaultId = vaultIdFor(rootKeyHex)120 val receiverIdentity = identity("receiver").copy(deviceType = DeviceType.ANDROID)121 val receiver = RecorderReceiver(122 "Receiver",123 DeviceType.ANDROID,124 vaultId,125 derived = receiverIdentity,126 localLicense = null,127 )128 val source = RecorderSource(identity("source"), rootKeyHex, vaultId, license = "PPK-test")129130 val recvJob = async { requestAdoption(receiverCh, receiver) { 111L } }131 val grantJob = async {132 val request = receiveFrame(sourceCh) as AdoptionFrame.Request133 grantAdoption(sourceCh, request, source) { 222L }134 }135 recvJob.await()136 grantJob.await()137138 assertEquals(rootKeyHex, receiver.createCalledWith)139 assertEquals("PPK-test", receiver.licenseApplied)140 assertEquals(listOf("source-id"), receiver.revocationsCleared)141 assertEquals("source-id", receiver.upserted.single().deviceId)142 assertEquals("receiver-id", source.upserted.single().deviceId)143 assertEquals("android", source.upserted.single().deviceType)144 }145146 @Test fun source_preserves_existing_peer_and_accepts_rotated_identity_after_collision() = runBlocking {147 val (receiverCh, sourceCh) = memoryPair()148 val rootKeyHex = "13".repeat(32)149 val vaultId = vaultIdFor(rootKeyHex)150 val source = RecorderSource(identity("android"), rootKeyHex, vaultId).apply {151 collidingDeviceId = "chrome-id"152 }153154 val sourcePromise = async {155 grantAdoption(sourceCh, AdoptionFrame.Request(156 sessionRequestId = "receiver-ephemeral",157 deviceName = "Firefox",158 deviceType = DeviceType.EXTENSION.wireValue,159 ), source)160 }161 sendFrame(receiverCh, AdoptionFrame.Confirm(true))162 assertTrue(receiveFrame(receiverCh) is AdoptionFrame.Grant)163 sendFrame(receiverCh, AdoptionFrame.Identity(164 deviceId = "chrome-id",165 deviceName = "Firefox",166 deviceType = DeviceType.EXTENSION.wireValue,167 longTermPublicKeyHex = "11".repeat(32),168 ))169 val rejection = receiveFrame(receiverCh)170 assertTrue(rejection is AdoptionFrame.Reject)171 assertEquals("ADOPT_DEVICE_ID_COLLISION", (rejection as AdoptionFrame.Reject).reason)172 source.collidingDeviceId = null173 sendFrame(receiverCh, AdoptionFrame.Identity(174 deviceId = "firefox-id",175 deviceName = "Firefox",176 deviceType = DeviceType.EXTENSION.wireValue,177 longTermPublicKeyHex = "22".repeat(32),178 ))179 assertTrue(receiveFrame(receiverCh) is AdoptionFrame.Complete)180 sendFrame(receiverCh, AdoptionFrame.Applied)181182 assertEquals("firefox-id", sourcePromise.await()?.deviceId)183 assertEquals(listOf("firefox-id"), source.upserted.map { it.deviceId })184 }185186 @Test fun rejects_without_creating_or_pairing_when_neither_peer_has_pro() = runBlocking {187 val (receiverCh, sourceCh) = memoryPair()188 val rootKeyHex = "12".repeat(32)189 val vaultId = vaultIdFor(rootKeyHex)190 val receiver = RecorderReceiver(191 "Free receiver",192 DeviceType.ANDROID,193 vaultId,194 localLicense = null,195 )196 val source = RecorderSource(197 identity("free-source"),198 rootKeyHex,199 vaultId,200 license = null,201 )202203 val receiverJob = async { requestAdoption(receiverCh, receiver) { 0L } }204 val sourceJob = async {205 val request = receiveFrame(sourceCh) as AdoptionFrame.Request206 runCatching { grantAdoption(sourceCh, request, source) { 0L } }207 }208209 assertNull(receiverJob.await())210 val sourceOutcome = sourceJob.await()211 assertTrue(sourceOutcome.isFailure)212 assertEquals("ADOPT_PRO_REQUIRED", sourceOutcome.exceptionOrNull()?.message)213 assertEquals(listOf("ADOPT_PRO_REQUIRED"), receiver.errors)214 assertNull(receiver.createCalledWith)215 assertTrue(receiver.upserted.isEmpty())216 assertTrue(source.upserted.isEmpty())217 }218219 @Test fun receiver_pro_license_is_transferred_to_a_free_source() = runBlocking {220 val (receiverCh, sourceCh) = memoryPair()221 val rootKeyHex = "13".repeat(32)222 val vaultId = vaultIdFor(rootKeyHex)223 val receiver = RecorderReceiver(224 "Pro receiver",225 DeviceType.ANDROID,226 vaultId,227 derived = identity("receiver").copy(deviceType = DeviceType.ANDROID),228 localLicense = "PPK-receiver",229 )230 val source = RecorderSource(231 identity("free-source"),232 rootKeyHex,233 vaultId,234 license = null,235 )236237 val receiverJob = async { requestAdoption(receiverCh, receiver) { 1L } }238 val sourceJob = async {239 val request = receiveFrame(sourceCh) as AdoptionFrame.Request240 grantAdoption(sourceCh, request, source) { 2L }241 }242243 assertEquals("free-source-id", receiverJob.await()?.deviceId)244 assertEquals("receiver-id", sourceJob.await()?.deviceId)245 assertEquals("PPK-receiver", source.licenseApplied)246 }247248 249250251252253254 @Test fun request_label_is_never_what_gets_persisted() = runBlocking {255 val (receiverCh, sourceCh) = memoryPair()256 val rootKeyHex = "55".repeat(32)257 val source = RecorderSource(identity("source"), rootKeyHex, vaultIdFor(rootKeyHex))258 259 val request = AdoptionFrame.Request("ephemeral-label-not-an-identity", "Receiver", "extension")260261 val grantJob = async { grantAdoption(sourceCh, request, source) { 0L } }262 sendFrame(receiverCh, AdoptionFrame.Confirm(true))263 receiveFrame(receiverCh) 264 sendFrame(265 receiverCh,266 AdoptionFrame.Identity(267 deviceId = "receiver-id",268 deviceName = "Receiver",269 deviceType = "extension",270 longTermPublicKeyHex = "aa".repeat(32),271 signingPublicKeyHex = "bb".repeat(32),272 ),273 )274 receiveFrame(receiverCh) 275 sendFrame(receiverCh, AdoptionFrame.Applied)276 grantJob.await()277278 val persisted = source.upserted.single()279 assertEquals("receiver-id", persisted.deviceId)280 assertEquals("aa".repeat(32), persisted.longTermPublicKeyHex)281 assertTrue(282 "the ephemeral request label must not reach the paired-device store",283 source.upserted.none { it.deviceId == "ephemeral-label-not-an-identity" },284 )285 }286287 @Test fun request_carries_receiver_device_type() = runBlocking {288 val (receiverCh, sourceCh) = memoryPair()289 val receiver = RecorderReceiver("Receiver", DeviceType.ANDROID, vaultId = null)290 val recvJob = async { requestAdoption(receiverCh, receiver) { 0L } }291 val request = receiveFrame(sourceCh) as AdoptionFrame.Request292 recvJob.cancel()293294 assertEquals("android", request.deviceType)295 assertEquals("receiver-ephemeral", request.sessionRequestId)296 assertEquals("Receiver", request.deviceName)297 }298299 @Test fun denied_consent_grants_nothing() = runBlocking {300 val (receiverCh, sourceCh) = memoryPair()301 val rootKeyHex = "33".repeat(32)302 val receiver = RecorderReceiver("Receiver", DeviceType.ANDROID, vaultIdFor(rootKeyHex))303 val source = RecorderSource(identity("source"), rootKeyHex, vaultIdFor(rootKeyHex), consent = false)304305 val recvJob = async { requestAdoption(receiverCh, receiver) { 0L } }306 val request = receiveFrame(sourceCh) as AdoptionFrame.Request307 val granted = grantAdoption(sourceCh, request, source) { 0L }308 recvJob.cancel()309310 assertNull(granted)311 assertTrue(source.consentAsked)312 assertFalse(source.rootRequested)313 assertTrue(source.upserted.isEmpty())314 assertNull(receiver.createCalledWith)315 }316317 @Test fun receiver_sas_rejection_grants_no_root_key() = runBlocking {318 val (receiverCh, sourceCh) = memoryPair()319 val rootKeyHex = "66".repeat(32)320 val receiver = RecorderReceiver(321 "Receiver",322 DeviceType.ANDROID,323 vaultIdFor(rootKeyHex),324 sasConfirmed = false,325 )326 val source = RecorderSource(identity("source"), rootKeyHex, vaultIdFor(rootKeyHex))327328 val receiverJob = async { requestAdoption(receiverCh, receiver) { 0L } }329 val request = receiveFrame(sourceCh) as AdoptionFrame.Request330 val sourceJob = async { grantAdoption(sourceCh, request, source) { 0L } }331332 assertNull(receiverJob.await())333 assertNull(sourceJob.await())334 assertFalse(source.rootRequested)335 assertNull(receiver.createCalledWith)336 assertTrue(receiver.revocationsCleared.isEmpty())337 assertEquals(listOf("ADOPT_SAS_REJECTED"), receiver.errors)338 }339340 @Test fun invalid_root_key_hex_aborts_as_unexpected_frame() = runBlocking {341 val (receiverCh, sourceCh) = memoryPair()342 val receiver = RecorderReceiver("Receiver", DeviceType.ANDROID, vaultId = null)343 val recvJob = async { requestAdoption(receiverCh, receiver) { 0L } }344 receiveFrame(sourceCh)345 sendFrame(sourceCh, AdoptionFrame.Grant(346 rootKeyHex = "bad",347 vaultId = "00".repeat(32),348 source = AdoptionFrame.Source("source", "Source", "extension", "ab".repeat(32)),349 ))350 recvJob.await()351352 assertEquals(listOf("ADOPT_UNEXPECTED_FRAME"), receiver.errors)353 assertNull(receiver.createCalledWith)354 }355356 @Test fun vault_id_mismatch_aborts_before_vault_creation() = runBlocking {357 val (receiverCh, sourceCh) = memoryPair()358 val receiver = RecorderReceiver("Receiver", DeviceType.ANDROID, vaultId = null)359 val recvJob = async { requestAdoption(receiverCh, receiver) { 0L } }360 receiveFrame(sourceCh)361 sendFrame(sourceCh, AdoptionFrame.Grant(362 rootKeyHex = "22".repeat(32),363 vaultId = "00".repeat(32),364 source = AdoptionFrame.Source("source", "Source", "extension", "ab".repeat(32)),365 ))366 recvJob.await()367368 assertEquals(listOf("ADOPT_VAULT_ID_MISMATCH"), receiver.errors)369 assertNull(receiver.createCalledWith)370 }371372 @Test fun source_waits_for_identity_before_persisting_receiver() = runBlocking {373 val (receiverCh, sourceCh) = memoryPair()374 val rootKeyHex = "33".repeat(32)375 val source = RecorderSource(identity("source"), rootKeyHex, vaultIdFor(rootKeyHex))376 val request = AdoptionFrame.Request("receiver-ephemeral", "Receiver", "extension")377378 sendFrame(receiverCh, AdoptionFrame.Confirm(true))379 val result = withTimeoutOrNull(150) {380 381 grantAdoption(sourceCh, request, source) { 0L }382 }383384 assertNull(result)385 assertTrue(source.upserted.isEmpty())386 }387388 @Test fun receiver_does_not_persist_source_without_complete() = runBlocking {389 val (receiverCh, sourceCh) = memoryPair()390 val rootKeyHex = "77".repeat(32)391 val vaultId = vaultIdFor(rootKeyHex)392 val receiver = RecorderReceiver(393 "Receiver",394 DeviceType.ANDROID,395 vaultId,396 derived = identity("receiver").copy(deviceType = DeviceType.ANDROID),397 )398 val receiverJob = async { requestAdoption(receiverCh, receiver) { 0L } }399400 receiveFrame(sourceCh) 401 receiveFrame(sourceCh) 402 sendFrame(403 sourceCh,404 AdoptionFrame.Grant(405 rootKeyHex = rootKeyHex,406 vaultId = vaultId,407 source = AdoptionFrame.Source(408 "source-id",409 "Source",410 "extension",411 "ab".repeat(32),412 ),413 ),414 )415 receiveFrame(sourceCh) 416 sendFrame(sourceCh, AdoptionFrame.Confirm(true))417418 assertNull(receiverJob.await())419 assertEquals(listOf("ADOPT_COMPLETION_MISSING"), receiver.errors)420 assertTrue(receiver.revocationsCleared.isEmpty())421 assertTrue(receiver.upserted.isEmpty())422 }423424 @Test fun receiver_safety_policy_runs_before_vault_creation() = runBlocking {425 val (receiverCh, sourceCh) = memoryPair()426 val rootKeyHex = "78".repeat(32)427 val vaultId = vaultIdFor(rootKeyHex)428 val receiver = object : RecorderReceiver(429 "Receiver",430 DeviceType.ANDROID,431 vaultId,432 derived = identity("receiver").copy(deviceType = DeviceType.ANDROID),433 ) {434 override suspend fun validateSource(source: AdoptionFrame.Source) {435 throw IllegalStateException("JOIN_POPULATED_VAULT_BLOCKED")436 }437 }438 val receiverJob = async {439 runCatching { requestAdoption(receiverCh, receiver) { 0L } }440 }441442 receiveFrame(sourceCh) 443 receiveFrame(sourceCh) 444 sendFrame(445 sourceCh,446 AdoptionFrame.Grant(447 rootKeyHex = rootKeyHex,448 vaultId = vaultId,449 source = AdoptionFrame.Source(450 "new-source",451 "Source",452 "extension",453 "ab".repeat(32),454 ),455 ),456 )457458 val outcome = receiverJob.await()459 assertTrue(outcome.isFailure)460 assertEquals("JOIN_POPULATED_VAULT_BLOCKED", outcome.exceptionOrNull()?.message)461 assertNull(receiver.createCalledWith)462 }463464 @Test fun does_not_apply_license_when_vault_creation_fails() = runBlocking {465 val (receiverCh, sourceCh) = memoryPair()466 val rootKeyHex = "44".repeat(32)467 val vaultId = vaultIdFor(rootKeyHex)468 val receiver = RecorderReceiver("Receiver", DeviceType.ANDROID, vaultId, createThrows = true)469 val recvJob = async {470 runCatching { requestAdoption(receiverCh, receiver) { 0L } }471 }472 receiveFrame(sourceCh)473 sendFrame(sourceCh, AdoptionFrame.Grant(474 rootKeyHex = rootKeyHex,475 vaultId = vaultId,476 license = "PPK-test",477 source = AdoptionFrame.Source("source", "Source", "extension", "ab".repeat(32)),478 ))479 val outcome = recvJob.await()480481 assertTrue(outcome.isFailure)482 assertNull(receiver.licenseApplied)483 }484485 @Test fun validator_rejects_short_and_uppercase_root_keys() {486 assertTrue(validateRootKeyHex("ab".repeat(32)))487 assertFalse(validateRootKeyHex("ab".repeat(31)))488 assertFalse(validateRootKeyHex("AB".repeat(32)))489 assertFalse(validateRootKeyHex("zz".repeat(32)))490 assertFalse(validateRootKeyHex(null))491 }492493 @Test fun grant_omits_absent_optionals_like_json_stringify() {494 val grant = AdoptionFrame.Grant(495 rootKeyHex = "11".repeat(32),496 vaultId = "22".repeat(32),497 source = AdoptionFrame.Source("source", "Source", "extension", "ab".repeat(32)),498 )499 val json = AdoptJson.encodeToString(AdoptionFrame.serializer(), grant)500501 assertFalse(json.contains("license"))502 assertFalse(json.contains("ws_port"))503 assertFalse(json.contains("signing_public_key_hex"))504 assertTrue(json.contains("\"type\":\"ADOPT_GRANT\""))505 assertTrue(json.contains("\"root_key_hex\""))506 }507508 @Test fun grant_json_carries_snapshot_capable_true_when_request_advertised_it() {509 val grant = AdoptionFrame.Grant(510 rootKeyHex = "11".repeat(32),511 vaultId = "22".repeat(32),512 source = AdoptionFrame.Source("source", "Source", "extension", "ab".repeat(32)),513 snapshotCapable = true,514 )515 val json = AdoptJson.encodeToString(AdoptionFrame.serializer(), grant)516 assertTrue(517 "explicit snapshot_capable: true must serialize",518 json.contains("\"snapshot_capable\":true"),519 )520 }521522 @Test fun grant_decodes_snapshot_capable_false_when_field_absent() {523 524 525 526 527 528 529 530 531 532 533 val withoutField = AdoptJson.decodeFromString(534 AdoptionFrame.serializer(),535 "{\"type\":\"ADOPT_GRANT\",\"root_key_hex\":\"${"11".repeat(32)}\",\"vault_id\":\"${"22".repeat(32)}\",\"source\":{\"device_id\":\"source\",\"device_name\":\"Source\",\"device_type\":\"extension\",\"long_term_public_key_hex\":\"${"ab".repeat(32)}\"}}",536 ) as AdoptionFrame.Grant537 assertFalse(538 "missing field must decode to default false (receiver skips 15s wait)",539 withoutField.snapshotCapable,540 )541 542 543 val withFieldFalse = AdoptJson.decodeFromString(544 AdoptionFrame.serializer(),545 "{\"type\":\"ADOPT_GRANT\",\"root_key_hex\":\"${"11".repeat(32)}\",\"vault_id\":\"${"22".repeat(32)}\",\"snapshot_capable\":false,\"source\":{\"device_id\":\"source\",\"device_name\":\"Source\",\"device_type\":\"extension\",\"long_term_public_key_hex\":\"${"ab".repeat(32)}\"}}",546 ) as AdoptionFrame.Grant547 assertFalse(548 "explicit false must decode to false",549 withFieldFalse.snapshotCapable,550 )551 }552553 @Test fun requestAdoption_invokes_onGrant_with_decoded_grant() = runBlocking {554 555 556 557 558 val (receiverCh, sourceCh) = memoryPair()559 val rootKeyHex = "55".repeat(32)560 val vaultId = vaultIdFor(rootKeyHex)561 val receiverIdentity = identity("receiver").copy(deviceType = DeviceType.ANDROID)562 val receiver = RecorderReceiver(563 "Receiver",564 DeviceType.ANDROID,565 vaultId,566 derived = receiverIdentity,567 localLicense = null,568 )569 val source = RecorderSource(identity("source"), rootKeyHex, vaultId, license = "PPK-test")570 val seenGrants = mutableListOf<AdoptionFrame.Grant>()571572 val recvJob = async {573 requestAdoption(574 receiverCh,575 receiver,576 onGrant = { grant -> seenGrants += grant },577 )578 }579 val grantJob = async {580 val request = receiveFrame(sourceCh) as AdoptionFrame.Request581 assertTrue(582 "receiver must advertise snapshot_capable in ADOPT_REQUEST",583 request.snapshotCapable == true,584 )585 grantAdoption(sourceCh, request, source) { 0L }586 }587 recvJob.await()588 grantJob.await()589590 assertEquals(1, seenGrants.size)591 assertEquals(rootKeyHex, seenGrants.single().rootKeyHex)592 593 594 595 596 assertTrue(597 "grant must echo request.snapshot_capable === true",598 seenGrants.single().snapshotCapable,599 )600 }601}