Modern Apps git

← Modern-Apps.git

passwords: add tests for sync, cable and view model (168 tests)

Commit
74e3fae498c15089a42f726eb42c7ca13400c28a
Author
Vayun Mathur <[email protected]>
When
2026-11-15 19:00 UTC (20 days ago)
Parents
4b5216e
Add unit tests covering PasswordsViewModel import/clipboard/draft logic, repository/migrations, KdbxSyncEngine and Relay provider sync, KdbxBackupFormat, CBOR/TOTP/domain-match/merge domain logic, caBLE CBOR/Noise/CTAP pure layers, credential services, and Robolectric Compose vault/passkey pages. Two detekt findings in the new tests (EqualsNullCall, destructuring limits) were fixed by using componentN() calls.

Skipped: SQLCipher-backed DAO paths (native library unavailable under Robolectric), PasswordAutofillService framework fixtures, CableSession live WebSocket/BLE, and biometric assertion bodies.

Coverage (JaCoCo INSTRUCTION): covered 20,899 -> 24,405 (+3,506), missed 14,838 -> 11,332 (58.5% -> 68.3%).
Verified: :passwords:testDevUnitTest (389 tests, 0 failures) :passwords:detekt :passwords:lint green.

Diff

passwords/src/test/java/com/vayunmathur/passwords/data/MigrationsExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/data/MigrationsExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/data/MigrationsExtraTest.ktnew file mode 100644index 0000000000..6670e9564b--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/data/MigrationsExtraTest.kt@@ -0,0 +1,79 @@+package com.vayunmathur.passwords.data++import androidx.sqlite.SQLiteConnection+import androidx.sqlite.driver.AndroidSQLiteDriver+import androidx.sqlite.execSQL+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Runs the real v1 -> v5 upgrade path against an in-memory SQLite connection+ * and checks the data survives: a legacy `userId` becomes the `username`, and+ * the passkey table gains its sync + link columns.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class MigrationsExtraTest {++    @Test fun fullUpgradePathPreservesRows() = runBlocking {+        val connection = AndroidSQLiteDriver().open(":memory:")+        try {+            // v1 schema for Password (pre username/email split, pre sync columns).+            connection.execSQL(+                "CREATE TABLE `Password` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++                    "`name` TEXT NOT NULL, `userId` TEXT NOT NULL, `password` TEXT NOT NULL, " ++                    "`totpSecret` TEXT, `websites` TEXT NOT NULL)",+            )+            connection.execSQL(+                "INSERT INTO `Password` (`id`, `name`, `userId`, `password`, `totpSecret`, `websites`) " ++                    "VALUES (1, 'GitHub', 'octocat', 'pw', NULL, 'github.com')",+            )++            val migrations = PasswordDatabase.migrations.sortedBy { it.startVersion }+            assertEquals(listOf(1, 2, 3, 4), migrations.map { it.startVersion })+            for (migration in migrations) {+                migration.migrate(connection)+            }++            // The legacy login survived the table-recreate migration as the username.+            val passwordColumns = columnNames(connection, "Password")+            assertTrue("username" in passwordColumns)+            assertTrue("syncId" in passwordColumns)+            connection.prepare("SELECT `username`, `email`, `password` FROM `Password` WHERE `id` = 1").use { stmt ->+                assertTrue(stmt.step())+                assertEquals("octocat", stmt.getText(0))+                assertEquals("", stmt.getText(1))+                assertEquals("pw", stmt.getText(2))+            }+            // Passkey was created by 1->2 and gained sync + link columns by 2->3 and 4->5.+            val passkeyColumns = columnNames(connection, "Passkey")+            assertTrue("syncId" in passkeyColumns)+            assertTrue("linkedPasswordSyncId" in passkeyColumns)+            // The snapshot baseline table exists after the upgrade.+            assertTrue("SyncSnapshot" in tableNames(connection))+        } finally {+            connection.close()+        }+    }++    private fun tableNames(connection: SQLiteConnection): Set<String> {+        val names = mutableSetOf<String>()+        connection.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").use { stmt ->+            while (stmt.step()) names += stmt.getText(0)+        }+        return names+    }++    private fun columnNames(connection: SQLiteConnection, table: String): Set<String> {+        val names = mutableSetOf<String>()+        connection.prepare("PRAGMA table_info(`$table`)").use { stmt ->+            while (stmt.step()) names += stmt.getText(1)+        }+        return names+    }+}
passwords/src/test/java/com/vayunmathur/passwords/data/RepositoryAndEntitiesExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/data/RepositoryAndEntitiesExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/data/RepositoryAndEntitiesExtraTest.ktnew file mode 100644index 0000000000..baf8a786c9--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/data/RepositoryAndEntitiesExtraTest.kt@@ -0,0 +1,138 @@+package com.vayunmathur.passwords.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertSame+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class RepositoryAndEntitiesExtraTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun repositoryGetReturnsSingleton() {+        val first = PasswordRepository.get(ctx)+        val second = PasswordRepository.get(ctx.applicationContext)+        assertSame(first, second)+    }++    @Test fun snapshotStoreDelegatesEveryOperation() = runBlocking {+        val dao = FakeSnapshotDao()+        val store = SnapshotStore(dao)+        store.upsert(SyncSnapshot("a", SyncSnapshot.KIND_PASSWORD, "h1", 1, 2, 3))+        store.upsert(SyncSnapshot("b", SyncSnapshot.KIND_PASSKEY, "h2", 4, 5, 6))+        store.upsert(SyncSnapshot("c", SyncSnapshot.KIND_PASSWORD, "h3", 7, 8, 9))+        assertEquals(listOf("a", "b", "c"), store.getAll().map { it.syncId })+        // Upsert replaces by primary key.+        store.upsert(SyncSnapshot("a", SyncSnapshot.KIND_PASSWORD, "h1b", 10, 2, 3))+        assertEquals("h1b", store.getAll().first { it.syncId == "a" }.contentHash)+        store.deleteByKind(SyncSnapshot.KIND_PASSWORD)+        assertEquals(listOf("b"), store.getAll().map { it.syncId })+        store.deleteBySyncId("b")+        assertTrue(store.getAll().isEmpty())+        store.upsert(SyncSnapshot("z", SyncSnapshot.KIND_PASSKEY, "hz", 0, 0, 0))+        store.deleteAll()+        assertTrue(store.getAll().isEmpty())+        assertEquals("password", SyncSnapshot.KIND_PASSWORD)+        assertEquals("passkey", SyncSnapshot.KIND_PASSKEY)+    }++    @Test fun passkeyEqualityAndHashCoverEveryField() {+        val base = Passkey(+            id = 1, rpId = "r", rpName = "R", credentialId = "c", userId = "u",+            userName = "n", userDisplayName = "d", privateKeyBytes = byteArrayOf(1, 2),+            creationTime = 1, lastUsedTime = 2, signCount = 3,+            linkedPasswordSyncId = "link", syncId = "s", updatedAt = 4,+        )+        val identical = base.copy(privateKeyBytes = byteArrayOf(1, 2))+        assertEquals(base, identical)+        assertEquals(base.hashCode(), identical.hashCode())+        assertFalse(base == null)+        assertFalse(base.equals("not a passkey"))+        assertEquals(base, base)+        // Each single-field change makes the row unequal (StateFlow conflation guard).+        assertNotEquals(base, base.copy(id = 2))+        assertNotEquals(base, base.copy(rpId = "x"))+        assertNotEquals(base, base.copy(rpName = "x"))+        assertNotEquals(base, base.copy(credentialId = "x"))+        assertNotEquals(base, base.copy(userId = "x"))+        assertNotEquals(base, base.copy(userName = "x"))+        assertNotEquals(base, base.copy(userDisplayName = "x"))+        assertNotEquals(base, base.copy(privateKeyBytes = byteArrayOf(9)))+        assertNotEquals(base, base.copy(creationTime = 99))+        assertNotEquals(base, base.copy(lastUsedTime = 99))+        assertNotEquals(base, base.copy(signCount = 99))+        assertNotEquals(base, base.copy(linkedPasswordSyncId = null))+        assertNotEquals(base, base.copy(syncId = "x"))+        assertNotEquals(base, base.copy(updatedAt = 99))+        assertNotEquals(base.hashCode(), base.copy(signCount = 99).hashCode())+    }++    @Test fun passwordEntityDefaultsAndCopy() {+        val blank = Password()+        assertEquals(0L, blank.id)+        assertEquals("", blank.name)+        assertEquals(emptyList(), blank.websites)+        assertEquals(null, blank.totpSecret)+        assertEquals(32, blank.syncId.length)+        assertTrue(blank.syncId.all { it in '0'..'9' || it in 'a'..'f' })+        val named = blank.copy(name = "Named", websites = listOf("a.com"))+        assertEquals("Named", named.name)+        assertEquals(blank.syncId, named.syncId) // copy preserves identity+        assertNotEquals(blank, named)+        assertEquals(named, named.copy())+        assertEquals(named.hashCode(), named.copy().hashCode())+        assertTrue(named.toString().contains("Named"))+    }++    @Test fun daoUpsertBumpsTimestampButRawPreservesIt() = runBlocking {+        // The DAO default methods are the only place the "upsert bumps, raw preserves"+        // contract lives; exercising them against a fake raw store pins both halves.+        val raw = mutableMapOf<Long, Password>()+        val dao = object : PasswordDao() {+            override fun getAllFlow(): Flow<List<Password>> = flowOf(raw.values.toList())+            override suspend fun getAll(): List<Password> = raw.values.toList()+            override fun getByIdFlow(id: Long): Flow<Password?> = flowOf(raw[id])+            override suspend fun getById(id: Long): Password? = raw[id]+            override suspend fun getBySyncId(syncId: String): Password? =+                raw.values.firstOrNull { it.syncId == syncId }+            override suspend fun getUpdatedSince(since: Long): List<Password> =+                raw.values.filter { it.updatedAt > since }+            override suspend fun upsertRaw(value: Password): Long {+                raw[value.id] = value+                return value.id+            }+            override suspend fun delete(value: Password): Int = if (raw.remove(value.id) != null) 1 else 0+            override suspend fun deleteBySyncId(syncId: String): Int {+                val victim = raw.values.firstOrNull { it.syncId == syncId } ?: return 0+                raw.remove(victim.id)+                return 1+            }+            override suspend fun deleteAll() = raw.clear()+        }+        dao.upsertRaw(Password(id = 1, name = "A", syncId = "s", updatedAt = 123))+        assertEquals(123L, dao.getById(1)?.updatedAt)+        dao.upsert(Password(id = 1, name = "A", syncId = "s", updatedAt = 123))+        assertTrue((dao.getById(1)?.updatedAt ?: 0) > 123)+    }++    private class FakeSnapshotDao : SyncSnapshotDao {+        val store = linkedMapOf<String, SyncSnapshot>()+        override suspend fun getAll(): List<SyncSnapshot> = store.values.toList()+        override suspend fun upsert(snapshot: SyncSnapshot) { store[snapshot.syncId] = snapshot }+        override suspend fun deleteBySyncId(syncId: String) { store.remove(syncId) }+        override suspend fun deleteByKind(kind: String) { store.entries.removeAll { it.value.kind == kind } }+        override suspend fun deleteAll() = store.clear()+    }+}
passwords/src/test/java/com/vayunmathur/passwords/data/RepositoryFlowGettersTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/data/RepositoryFlowGettersTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/data/RepositoryFlowGettersTest.ktnew file mode 100644index 0000000000..e84d09e54c--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/data/RepositoryFlowGettersTest.kt@@ -0,0 +1,42 @@+package com.vayunmathur.passwords.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlin.test.assertNotSame+import kotlin.test.assertSame++/**+ * The repository's read *flows* are cold: obtaining them builds the (lazy)+ * database handle but does not open it, so they can be handed to the UI+ * before the vault is unlocked. Actually collecting them is what opens+ * SQLCipher, which is unavailable under Robolectric — that part is on-device.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class RepositoryFlowGettersTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    @Test fun flowGettersReturnColdFlowsWithoutOpeningVault() {+        val repo = PasswordRepository.get(ctx)+        assertNotNull(repo.passwords)+        assertNotNull(repo.passkeys)+        assertNotNull(repo.getPasswordByIdFlow(42))+        // Each access builds a fresh cold flow (Room semantics), not a shared stream.+        assertNotSame(repo.passwords, repo.passwords)+    }++    @Test fun snapshotStoreIsStableAndLazy() {+        val repo = PasswordRepository.get(ctx)+        assertSame(repo.snapshots, repo.snapshots)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/domain/DataClassesExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/domain/DataClassesExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/domain/DataClassesExtraTest.ktnew file mode 100644index 0000000000..987e1e6ce8--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/domain/DataClassesExtraTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.passwords.domain++import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.SyncSnapshot+import com.vayunmathur.passwords.platform.MenuUiState+import com.vayunmathur.passwords.platform.PasswordEditUiState+import com.vayunmathur.passwords.platform.PasswordUiState+import com.vayunmathur.passwords.sync.KdbxSyncResult+import com.vayunmathur.passwords.sync.PasswordPasskeyPayload+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++class DataClassesExtraTest {++    @Test fun mergeResultOrderingAndPasskeysFor() {+        val host = Password(id = 1, name = "GitHub", username = "octo", websites = listOf("github.com"), syncId = "host")+        val late = Passkey(id = 2, rpId = "github.com", userName = "octo", creationTime = 200, syncId = "pk-b")+        val early = Passkey(id = 3, rpId = "github.com", userName = "octo", creationTime = 100, syncId = "pk-a")+        val sameTime = Passkey(id = 4, rpId = "github.com", userName = "octo", creationTime = 100, syncId = "pk-0")+        val result = mergeCredentials(listOf(host), listOf(late, sameTime, early))+        // Attached passkeys sort by creation time, then syncId as a stable tiebreak.+        assertEquals(listOf("pk-0", "pk-a", "pk-b"), result.passkeysByPasswordSyncId["host"]!!.map { it.syncId })+        assertEquals(result.passkeysByPasswordSyncId["host"], passkeysFor(host, listOf(host), listOf(late, early, sameTime)))+        // A password that does not exist in the list has no merged passkeys.+        assertEquals(emptyList(), passkeysFor(Password(syncId = "ghost"), listOf(host), listOf(early)))+        assertEquals(MergeResult(mapOf("host" to listOf(early)), emptyList()).hashCode(),+            MergeResult(mapOf("host" to listOf(early.copy())), emptyList()).hashCode())+    }++    @Test fun uiStateDataClassesBehaveAsValues() {+        val now = { 42L }+        val menu = MenuUiState(passwords = listOf(Password(name = "A")), loading = true, now = now)+        assertEquals(menu, menu.copy())+        assertEquals(menu.hashCode(), menu.copy().hashCode())+        assertNotEquals(menu, menu.copy(loading = false))+        assertTrue(menu.toString().contains("loading=true"))+        assertEquals(42L, menu.now())++        val detail = PasswordUiState(password = Password(name = "B"), now = now)+        assertEquals(detail, detail.copy())+        assertNotEquals(detail, detail.copy(password = Password(name = "C")))++        val edit = PasswordEditUiState(saved = Password(name = "S"), draft = null)+        assertEquals(edit, edit.copy())+        assertNotEquals(edit, edit.copy(draft = Password()))+        assertTrue(edit.toString().contains("draft=null"))+    }++    @Test fun syncResultAndSnapshotValues() {+        assertEquals(KdbxSyncResult.Success(1, 2, 3, 4), KdbxSyncResult.Success(1, 2, 3, 4).copy())+        assertNotEquals(KdbxSyncResult.Success(1, 2, 3, 4), KdbxSyncResult.Success(1, 2, 3, 5))+        assertEquals(KdbxSyncResult.Quarantined(3), KdbxSyncResult.Quarantined(3).copy(count = 3))+        assertEquals("Quarantined(count=3)", KdbxSyncResult.Quarantined(3).toString())+        assertEquals(KdbxSyncResult.Error("x"), KdbxSyncResult.Error("x").copy())++        val snap = SyncSnapshot("s", SyncSnapshot.KIND_PASSKEY, "h", 1, 2, 3)+        assertEquals(snap, snap.copy())+        assertEquals(snap.hashCode(), snap.copy().hashCode())+        assertNotEquals(snap, snap.copy(kind = SyncSnapshot.KIND_PASSWORD))+        assertEquals("s", snap.component1())+        assertEquals("passkey", snap.component2())+        assertEquals("h", snap.component3())+        assertEquals(1L, snap.component4())+        assertEquals(2L, snap.component5())+        assertEquals(3L, snap.component6())+    }++    @Test fun passkeyPayloadDataClassSemantics() {+        val payload = PasswordPasskeyPayload(+            id = 1, rpId = "example.com", credentialId = "cred", privateKeyBase64 = "AQID",+            signCount = 2, syncId = "pk-1", updatedAt = 9,+        )+        assertEquals(payload, payload.copy())+        assertEquals(payload.hashCode(), payload.copy().hashCode())+        assertNotEquals(payload, payload.copy(signCount = 3))+        assertTrue(payload.toString().contains("example.com"))+        val changed = payload.copy(rpId = "other.example", signCount = 7)+        assertEquals("other.example", changed.rpId)+        assertEquals(7, changed.signCount)+        assertEquals("cred", changed.credentialId) // untouched fields survive copy+    }++    @Test fun relayEnvelopeAndPayloadDestructuring() {+        val payload = PasswordPasskeyPayload(+            id = 1, rpId = "r", rpName = "R", credentialId = "c", userId = "u",+            userName = "n", userDisplayName = "d", privateKeyBase64 = "AQ==",+            creationTime = 1, lastUsedTime = 2, signCount = 3,+            linkedPasswordSyncId = "link", syncId = "s", updatedAt = 4,+        )+        assertEquals(1L, payload.component1())+        assertEquals("r", payload.component2())+        assertEquals("R", payload.component3())+        assertEquals("c", payload.component4())+        assertEquals("u", payload.component5())+        assertEquals("n", payload.component6())+        assertEquals("d", payload.component7())+        assertEquals("AQ==", payload.component8())+        assertEquals(1L, payload.component9())+        assertEquals(2L, payload.component10())+        assertEquals(3, payload.component11())+        assertEquals("link", payload.component12())+        assertEquals("s", payload.component13())+        assertEquals(4L, payload.component14())++        val relay = com.vayunmathur.passwords.sync.RelayPasswordJson(+            uid = "u1", isPasskey = true, name = "N", username = "un", email = "e",+            password = "p", note = "nt", totpSecret = "ts", websites = listOf("w"),+            rpId = "rp", rpName = "rpn", credentialId = "cid", userId = "uid",+            userName = "una", userDisplayName = "udn", privateKeyB64 = "a2V5",+            creationTime = 5, lastUsedTime = 6, signCount = 7,+            linkedPasswordSyncId = "lp", deleted = true, updatedAt = 8,+        )+        assertEquals("u1", relay.component1())+        assertEquals(true, relay.component2())+        assertEquals("N", relay.component3())+        assertEquals("un", relay.component4())+        assertEquals("e", relay.component5())+        assertEquals("p", relay.component6())+        assertEquals("nt", relay.component7())+        assertEquals("ts", relay.component8())+        assertEquals(listOf("w"), relay.component9())+        assertEquals("rp", relay.component10())+        assertEquals("rpn", relay.component11())+        assertEquals("cid", relay.component12())+        assertEquals("uid", relay.component13())+        assertEquals("una", relay.component14())+        assertEquals("udn", relay.component15())+        assertEquals("a2V5", relay.component16())+        assertEquals(5L, relay.component17())+        assertEquals(6L, relay.component18())+        assertEquals(7, relay.component19())+        assertEquals("lp", relay.component20())+        assertEquals(true, relay.component21())+        assertEquals(8L, relay.component22())+        assertEquals(relay, relay.copy())+        assertNotEquals(relay, relay.copy(uid = "other"))+    }+}
passwords/src/test/java/com/vayunmathur/passwords/domain/DomainPureExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/domain/DomainPureExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/domain/DomainPureExtraTest.ktnew file mode 100644index 0000000000..0d5340927f--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/domain/DomainPureExtraTest.kt@@ -0,0 +1,127 @@+package com.vayunmathur.passwords.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class DomainPureExtraTest {++    // ---- Cbor encoder: argument widths and containers ----++    @Test fun cborArgumentWidths() {+        fun ints(b: ByteArray) = b.map { it.toInt() and 0xFF }+        assertEquals(listOf(0x18, 0xFF), ints(Cbor.encode(255)))+        assertEquals(listOf(0x19, 0x01, 0x00), ints(Cbor.encode(256)))+        assertEquals(listOf(0x19, 0xFF, 0xFF), ints(Cbor.encode(65_535)))+        assertEquals(listOf(0x1A, 0x00, 0x01, 0x00, 0x00), ints(Cbor.encode(65_536)))+        assertEquals(listOf(0x1A, 0xFF, 0xFF, 0xFF, 0xFF), ints(Cbor.encode(4_294_967_295L)))+        // Negative: -24 encodes as 0x37 (major 1, arg 23), -256 as 0x38 0xFF.+        assertEquals(listOf(0x37), ints(Cbor.encode(-24)))+        assertEquals(listOf(0x38, 0xFF), ints(Cbor.encode(-256)))+        assertEquals(listOf(0x39, 0x01, 0x00), ints(Cbor.encode(-257)))+    }++    @Test fun cborEmptyContainersAndNestedSorting() {+        fun ints(b: ByteArray) = b.map { it.toInt() and 0xFF }+        assertEquals(listOf(0x40), ints(Cbor.encode(ByteArray(0))))+        assertEquals(listOf(0x60), ints(Cbor.encode("")))+        assertEquals(listOf(0x80), ints(Cbor.encode(emptyList<Any>())))+        assertEquals(listOf(0xA0), ints(Cbor.encode(emptyMap<Any, Any>())))+        // Map keys sort by encoded length first: key 1 (1 byte) before "ab" (3 bytes).+        val nested = Cbor.encode(mapOf("ab" to listOf(true, -1L), 1L to byteArrayOf(9)))+        assertEquals(0xA2.toByte(), nested[0])+        assertEquals(0x01.toByte(), nested[1])+        // A Double is a Number: it is truncated through toLong like other numbers.+        assertEquals(Cbor.encode(3L).toList(), Cbor.encode(3.9).toList())+        assertFailsWith<IllegalArgumentException> { Cbor.encode('x') }+    }++    // ---- TOTP: decoding tolerance and counter behaviour ----++    @Test fun totpIgnoresInvalidBase32CharactersAndCountsWholeSteps() {+        val secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"+        // Characters outside the base32 alphabet are skipped, not fatal.+        assertEquals(TOTP.generate(secret, 59), TOTP.generate("GEZD GNBV!GY3TQOJQ GEZDGNBVGY3TQOJQ", 59))+        // Epoch 0 and 29 share counter 0; 30 flips to counter 1 (RFC vector value at 59s).+        assertEquals(TOTP.generate(secret, 0), TOTP.generate(secret, 29))+        assertEquals("287082", TOTP.generate(secret, 30))+        // Every code is exactly six digits, including when the value needs leading zeros.+        assertEquals(6, TOTP.generate(secret, 1_111_111_109).length)+        assertEquals("081804", TOTP.generate(secret, 1_111_111_109))+        assertFailsWith<IllegalArgumentException> { TOTP.generate("   ", 0) }+        assertFailsWith<IllegalArgumentException> { TOTP.generate("====", 0) }+    }++    // ---- DomainMatch: normalisation edges ----++    @Test fun normalizeSiteEdges() {+        assertEquals("example.com", DomainMatch.normalizeSite("HTTPS://User:[email protected].:8443/path?q=1"))+        assertEquals("example.com", DomainMatch.normalizeSite("example.com."))+        assertEquals("", DomainMatch.normalizeSite("   "))+        assertEquals("sub.example.com", DomainMatch.normalizeSite("https://sub.example.com"))+        assertEquals("example.com", DomainMatch.normalizeSite("www.example.com"))+        // Only one leading www. label is stripped.+        assertEquals("www.example.com", DomainMatch.normalizeSite("www.www.example.com"))+    }++    @Test fun androidPackageDetectionEdges() {+        assertTrue(DomainMatch.isAndroidPackageSite("android-app://com.example.app"))+        assertTrue(DomainMatch.isAndroidPackageSite("com.example.app"))+        assertFalse(DomainMatch.isAndroidPackageSite("com.example")) // only one dot+        assertFalse(DomainMatch.isAndroidPackageSite("org.example.app")) // does not start with com.+        assertFalse(DomainMatch.isAndroidPackageSite("https://com.example.app/")) // a URL, not a package+        assertFalse(DomainMatch.isAndroidPackageSite("example.com"))+    }++    @Test fun sameSiteEdges() {+        assertTrue(DomainMatch.isSameSiteOrSubdomain("example.com", "example.com"))+        assertTrue(DomainMatch.isSameSiteOrSubdomain("a.b.example.com", "example.com"))+        assertFalse(DomainMatch.isSameSiteOrSubdomain("example.com", "a.example.com"))+        assertFalse(DomainMatch.isSameSiteOrSubdomain("", "example.com"))+        assertFalse(DomainMatch.isSameSiteOrSubdomain("example.com", ""))+        assertFalse(DomainMatch.isSameSiteOrSubdomain("badexample.com", "example.com"))+    }++    // ---- ImportSource: header tables are complete and distinct ----++    @Test fun importSourceHeaderTables() {+        // Every source can find at least a name, username, password and url column in its own table.+        for (source in ImportSource.entries) {+            assertTrue(source.nameHeaders.isNotEmpty(), "$source name")+            assertTrue(source.usernameHeaders.isNotEmpty(), "$source username")+            assertTrue(source.passwordHeaders.isNotEmpty(), "$source password")+            assertTrue(source.urlHeaders.isNotEmpty(), "$source url")+            assertTrue(source.label != 0, "$source label")+        }+        assertEquals(listOf("login_uri", "uri"), ImportSource.BITWARDEN.urlHeaders.toList())+        assertEquals(listOf("username", "username2", "username3"), ImportSource.DASHLANE.usernameHeaders.toList())+        assertTrue(ImportSource.PROTON_PASS.splitUrlsOnComma)+        assertFalse(ImportSource.BITWARDEN.splitUrlsOnComma)+        assertEquals(listOf("email"), ImportSource.PROTON_PASS.emailHeaders.toList())+        assertEquals(listOf("type"), ImportSource.PROTON_PASS.typeHeaders.toList())+        assertTrue(ImportSource.FIREFOX.totpHeaders.isEmpty())+        assertEquals(8, ImportSource.entries.size)+    }++    @Test fun cborMapKeyOrderingByEncodedBytes() {+        fun ints(b: ByteArray) = b.map { it.toInt() and 0xFF }+        // Byte-string keys of equal encoded length order by their bytes.+        val byBytes = Cbor.encode(mapOf(byteArrayOf(2) to "b", byteArrayOf(1) to "a"))+        assertEquals(listOf(0xA2, 0x41, 1, 0x61, 'a'.code, 0x41, 2, 0x61, 'b'.code), ints(byBytes))+        // Shorter encodings sort first even when the byte value is larger:+        // key 24 encodes in 2 bytes, key 1 in 1 byte, so 1 comes first.+        val byLength = Cbor.encode(mapOf(24L to "x", 1L to "y"))+        assertEquals(0x01, ints(byLength)[1])+    }++    @Test fun totpNegativeEpochCounters() {+        val secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"+        // Kotlin Long division truncates toward zero: -29s is still counter 0,+        // while -30s and -31s are both counter -1.+        assertEquals(TOTP.generate(secret, 0), TOTP.generate(secret, -29))+        assertEquals(TOTP.generate(secret, -30), TOTP.generate(secret, -31))+        assertEquals(6, TOTP.generate(secret, -30).length)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.ktnew file mode 100644index 0000000000..40920210d2--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.kt@@ -0,0 +1,43 @@+package com.vayunmathur.passwords.platform++import android.content.pm.Signature+import android.content.pm.SigningInfo+import androidx.credentials.provider.CallingAppInfo+import java.io.File+import java.security.KeyStore++/**+ * Builds a [CallingAppInfo] with a real signing certificate. Neither+ * Robolectric nor the SDK stubs can mint a [SigningInfo] with contents+ * through public APIs, so the framework's `SigningDetails` constructor is+ * reached reflectively — the same objects the system builds for an installed+ * app. The certificate is a real X.509 cert (from the JDK trust store, purely+ * as well-formed DER) because `SigningDetails` validates its signatures.+ */+object CallingAppInfoFactory {++    val certBytes: ByteArray by lazy {+        val store = KeyStore.getInstance(KeyStore.getDefaultType())+        File(System.getProperty("java.home"), "lib/security/cacerts").inputStream().use {+            store.load(it, "changeit".toCharArray())+        }+        val alias = store.aliases().nextElement()+        store.getCertificate(alias).encoded+    }++    fun signingInfo(): SigningInfo {+        val detailsClass = Class.forName("android.content.pm.SigningDetails")+        val detailsCtor = detailsClass.getDeclaredConstructor(+            Array<Signature>::class.java,+            Int::class.javaPrimitiveType,+        )+        detailsCtor.isAccessible = true+        val details = detailsCtor.newInstance(arrayOf(Signature(certBytes)), 3)+        val infoCtor = SigningInfo::class.java.getDeclaredConstructor(detailsClass)+        infoCtor.isAccessible = true+        return infoCtor.newInstance(details) as SigningInfo+    }++    fun callingAppInfo(packageName: String): CallingAppInfo =+        CallingAppInfo(packageName, signingInfo())+}
passwords/src/test/java/com/vayunmathur/passwords/platform/ImportFailureTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/ImportFailureTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/ImportFailureTest.ktnew file mode 100644index 0000000000..39d31ff489--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/ImportFailureTest.kt@@ -0,0 +1,66 @@+package com.vayunmathur.passwords.platform++import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.net.Uri+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.PasswordRepository+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse++/** A provider whose files can never be opened: every stream request returns null. */+class NullStreamProvider : ContentProvider() {+    override fun onCreate(): Boolean = true+    override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? = null+    override fun query(+        uri: Uri, projection: Array<out String>?, selection: String?,+        selectionArgs: Array<out String>?, sortOrder: String?,+    ): Cursor? = null+    override fun getType(uri: Uri): String? = null+    override fun insert(uri: Uri, values: ContentValues?): Uri? = null+    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+    override fun update(+        uri: Uri, values: ContentValues?, selection: String?,+        selectionArgs: Array<out String>?,+    ): Int = 0+}++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class ImportFailureTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() {+        FakeAndroidKeyStore.install()+        Robolectric.buildContentProvider(NullStreamProvider::class.java)+            .create("com.test.nullstream")+    }++    @Test fun importFromUnopenableUriReportsFailure() {+        val viewModel = PasswordsViewModel(app, PasswordRepository.get(app))+        viewModel.importCsv(Uri.parse("content://com.test.nullstream/passwords.csv"))+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline) {+            shadowOf(android.os.Looper.getMainLooper()).idle()+            if (!viewModel.importing.value && viewModel.importMessage.value != null) break+            Thread.sleep(10)+        }+        assertFalse(viewModel.importing.value)+        assertEquals(+            "Import failed: Unable to open selected file",+            viewModel.importMessage.value,+        )+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatExtraTest.ktnew file mode 100644index 0000000000..f6ddaa5d4a--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatExtraTest.kt@@ -0,0 +1,63 @@+package com.vayunmathur.passwords.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.PasswordRepository+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class KdbxBackupFormatExtraTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private fun format() = KdbxBackupFormat(PasswordRepository.get(app))++    @Test fun formatMetadata() {+        val format = format()+        assertEquals("application/octet-stream", format.mimeType)+        assertEquals("passwords.kdbx", format.defaultFileName)+        assertEquals(true, format.needsPassword)+    }++    @Test fun exportAndImportRequireAPassword() {+        val format = format()+        assertFailsWith<IllegalArgumentException> {+            runBlocking { format.export(app, null, ByteArrayOutputStream()) }+        }+        assertFailsWith<IllegalArgumentException> {+            runBlocking { format.import(app, null, ByteArrayInputStream(ByteArray(0))) }+        }+    }++    @Test fun importOfEmptyVaultSucceedsAsNoOp() {+        // A valid KDBX file holding zero entries imports successfully and+        // inserts nothing (the repository is never touched for zero entries).+        val bytes = com.vayunmathur.passwords.sync.NativeKdbxCodec.write("pw", emptyList())!!+        runBlocking { format().import(app, "pw", ByteArrayInputStream(bytes)) }+    }++    @Test fun importRejectsGarbageAndEmptyVaultBytes() {+        val format = format()+        val garbage = assertFailsWith<IllegalStateException> {+            runBlocking { format.import(app, "pw", ByteArrayInputStream(byteArrayOf(1, 2, 3))) }+        }+        assertTrue(garbage.message!!.contains("Failed to open KDBX"))+        assertFailsWith<IllegalStateException> {+            runBlocking { format.import(app, "pw", ByteArrayInputStream(ByteArray(0))) }+        }+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/MainActivityGateTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/MainActivityGateTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/MainActivityGateTest.ktnew file mode 100644index 0000000000..b77521d51b--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/MainActivityGateTest.kt@@ -0,0 +1,30 @@+package com.vayunmathur.passwords.platform++import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.MainActivity+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class MainActivityGateTest {++    @Before fun setUp() = FakeAndroidKeyStore.install()++    @Test fun mainActivityWaitsAtBiometricGate() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        controller.create()+        val activity = controller.get()+        // Composition is deliberately held back (autoSetContent = false) until+        // the biometric gate passes: creating the activity must neither finish+        // it nor render the vault before unlock.+        assertEquals(false, activity.isFinishing)+        assertEquals(false, activity.isDestroyed)+        controller.pause().stop().destroy()+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesRepoOverloadTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesRepoOverloadTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesRepoOverloadTest.ktnew file mode 100644index 0000000000..cbdaf2091c--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesRepoOverloadTest.kt@@ -0,0 +1,43 @@+package com.vayunmathur.passwords.platform++import android.content.Context+import android.os.Bundle+import androidx.credentials.provider.BeginGetPublicKeyCredentialOption+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.PasswordRepository+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * The repository-backed overload of [buildGetCredentialResponse] builds its+ * DAO adapters up front; requests that need no vault rows (no options, or a+ * public-key request without an rpId) complete without opening the vault.+ * Requests that do need rows open SQLCipher, which is on-device only.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasskeyEntriesRepoOverloadTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    @Test fun noOptionsYieldEmptyResponseThroughRepository() = runBlocking {+        val response = buildGetCredentialResponse(ctx, emptyList(), PasswordRepository.get(ctx))+        assertEquals(0, response.credentialEntries.size)+    }++    @Test fun blankRpIdIsSkippedThroughRepository() = runBlocking {+        val option = BeginGetPublicKeyCredentialOption(+            Bundle(), "req-blank", """{"challenge":"Y2hhbGxlbmdl"}""",+        )+        val response = buildGetCredentialResponse(ctx, listOf(option), PasswordRepository.get(ctx))+        assertEquals(0, response.credentialEntries.size)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.ktnew file mode 100644index 0000000000..8c031f2410--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.passwords.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasskeyUtilsExtraTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun authenticatorDataSignCountAndFlagCombinations() {+        val maxed = PasskeyUtils.buildAuthenticatorData(+            "example.com",+            userPresent = true, userVerified = false,+            backupEligible = false, backupState = true,+            attestedCredentialData = true, signCount = -1,+        )+        // UP + BS + AT, sign count written big-endian even for -1 (all FF).+        assertEquals(0x01 or 0x10 or 0x40, maxed[32].toInt() and 0xFF)+        assertEquals(listOf(0xFF, 0xFF, 0xFF, 0xFF), maxed.takeLast(4).map { it.toInt() and 0xFF })+        // Different rpIds hash differently in the first 32 bytes.+        val other = PasskeyUtils.buildAuthenticatorData("other.example")+        assertEquals(32, other.take(32).size)+        assertEquals(false, maxed.take(32) == other.take(32))+        // Zero-state: no flags, zero count.+        val bare = PasskeyUtils.buildAuthenticatorData(+            "example.com", userPresent = false, userVerified = false,+            backupEligible = false, backupState = false,+        )+        assertEquals(0, bare[32].toInt() and 0xFF)+        assertEquals(listOf(0, 0, 0, 0), bare.takeLast(4).map { it.toInt() and 0xFF })+    }++    @Test fun b64UrlEdgeCases() {+        assertEquals("", PasskeyUtils.encodeB64Url(ByteArray(0)))+        assertEquals(0, PasskeyUtils.decodeB64Url("").size)+        // Correct padding on input is tolerated even though output omits it:+        // four bytes encode to six unpadded chars, which take "==" to complete.+        val data = byteArrayOf(1, 2, 3, 4, 5)+        val encoded = PasskeyUtils.encodeB64Url(data)+        assertEquals(data.toList(), PasskeyUtils.decodeB64Url(encoded).toList())+        val four = byteArrayOf(1, 2, 3, 4)+        assertEquals(four.toList(), PasskeyUtils.decodeB64Url(PasskeyUtils.encodeB64Url(four) + "==").toList())+        val ids = (1..8).map { PasskeyUtils.generateCredentialId().toList() }+        assertEquals(8, ids.distinct().size)+    }++    @Test fun privilegedOriginDoesNotMatchOrdinaryApp() {+        // The bundled allow-list only names privileged browsers; an arbitrary+        // package cannot resolve a privileged origin.+        val info = CallingAppInfoFactory.callingAppInfo("com.example.app")+        assertNull(PasskeyUtils.getPrivilegedOrigin(info, ctx))+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelExtraTest.ktnew file mode 100644index 0000000000..37616bac9b--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelExtraTest.kt@@ -0,0 +1,206 @@+package com.vayunmathur.passwords.platform++import android.app.Application+import android.content.ClipDescription+import android.content.ClipboardManager+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.domain.ImportSource+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasswordsViewModelExtraTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private fun vm() = PasswordsViewModel(app, PasswordRepository.get(app))++    @Test fun resolveColumnsMapsEverySourceHeaderFamily() {+        val viewModel = vm()++        val bitwarden = viewModel.resolveColumns(+            listOf("name", "login_username", "login_password", "login_uri", "login_totp"),+            ImportSource.BITWARDEN,+        )+        assertEquals(0, bitwarden.name)+        assertEquals(1, bitwarden.username)+        assertEquals(2, bitwarden.password)+        assertEquals(3, bitwarden.url)+        assertEquals(4, bitwarden.totp)++        // Fallback header spellings are honoured in order.+        val fallback = viewModel.resolveColumns(+            listOf("name", "username", "password", "uri", "totp"),+            ImportSource.BITWARDEN,+        )+        assertEquals(3, fallback.url)++        val proton = viewModel.resolveColumns(+            listOf("name", "username", "password", "url", "totp", "email", "note", "type"),+            ImportSource.PROTON_PASS,+        )+        assertEquals(5, proton.email)+        assertEquals(6, proton.note)+        assertEquals(7, proton.type)++        val onePassword = viewModel.resolveColumns(+            listOf("title", "username", "password", "url", "otpauth"),+            ImportSource.ONE_PASSWORD,+        )+        assertEquals(0, onePassword.name)+        assertEquals(4, onePassword.totp)++        // Dashlane's second username column is used when the first is absent.+        val dashlane = viewModel.resolveColumns(+            listOf("title", "username2", "password", "url", "otpsecret"),+            ImportSource.DASHLANE,+        )+        assertEquals(1, dashlane.username)+    }++    @Test fun resolveColumnsMissingColumnsAreMinusOne() {+        val viewModel = vm()+        val columns = viewModel.resolveColumns(listOf("unrelated", "columns"), ImportSource.CHROME)+        assertEquals(-1, columns.name)+        assertEquals(-1, columns.username)+        assertEquals(-1, columns.password)+        assertEquals(-1, columns.url)+        // Chrome maps its note column onto TOTP.+        val chrome = viewModel.resolveColumns(+            listOf("name", "username", "password", "url", "note"),+            ImportSource.CHROME,+        )+        assertEquals(4, chrome.totp)+        // Firefox has no TOTP header family at all.+        val firefox = viewModel.resolveColumns(+            listOf("url", "username", "password"),+            ImportSource.FIREFOX,+        )+        assertEquals(0, firefox.name) // url doubles as the entry name+        assertEquals(-1, firefox.totp)+        assertEquals(-1, firefox.email)+        assertEquals(-1, firefox.note)+        assertEquals(-1, firefox.type)+    }++    @Test fun copyWithFeedbackEmitsEventAndMarksClipSensitive() = runBlocking {+        val viewModel = vm()+        // Subscribe before copying: the shared flow has no replay, so a late+        // collector would miss the one-shot event.+        var value: String? = null+        val job = launch(Dispatchers.Default) { value = viewModel.copyEvents.first() }+        // Give the collector thread time to actually subscribe (the flow has no+        // replay, so an emission before subscription would be lost by design).+        Thread.sleep(500)+        shadowOf(android.os.Looper.getMainLooper()).idle()+        viewModel.copyToClipboard("totp", "123456", feedback = "TOTP copied")+        val clipboard = app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+        assertEquals("123456", clipboard.primaryClip?.getItemAt(0)?.text)+        assertEquals(+            true,+            clipboard.primaryClip?.description?.extras?.getBoolean(ClipDescription.EXTRA_IS_SENSITIVE),+        )+        // viewModelScope posts on the main looper under Robolectric; idle it while awaiting.+        val deadline = System.currentTimeMillis() + 4_000+        while (value == null && System.currentTimeMillis() < deadline) {+            shadowOf(android.os.Looper.getMainLooper()).idle()+            Thread.sleep(5)+        }+        job.cancel()+        assertEquals("TOTP copied", value)+    }++    @Test fun copyWithoutFeedbackEmitsNoEvent() {+        val viewModel = vm()+        viewModel.copyToClipboard("password", "pw")+        val clipboard = app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+        assertEquals("pw", clipboard.primaryClip?.getItemAt(0)?.text)+        // No subscriber can receive an event that was never emitted: the shared flow has no replay.+        assertEquals(0, viewModel.copyEvents.replayCache.size)+    }++    @Test fun draftTransformsChainAndReseedingRules() {+        val viewModel = vm()+        viewModel.initDraft(Password(id = 9, name = "Base", username = "u", websites = listOf("a.com")))+        viewModel.updateDraft { it.copy(name = it.name + "!", totpSecret = "SEED") }+        viewModel.updateDraft { it.copy(websites = it.websites + "b.com") }+        val draft = viewModel.draft.value+        assertEquals("Base!", draft?.name)+        assertEquals("SEED", draft?.totpSecret)+        assertEquals(listOf("a.com", "b.com"), draft?.websites)++        // Reseeding with the same id preserves edits; clearing allows a fresh seed.+        viewModel.initDraft(Password(id = 9, name = "Replacement"))+        assertEquals("Base!", viewModel.draft.value?.name)+        viewModel.clearDraft()+        assertNull(viewModel.draft.value)+        viewModel.initDraft(Password(id = 9, name = "Replacement"))+        assertEquals("Replacement", viewModel.draft.value?.name)+    }++    @Test fun tickerEmitsRepeatedlyWhileSubscribed() = runBlocking {+        val viewModel = vm()+        val values = mutableListOf<Long>()+        val job = launch(Dispatchers.Default) {+            viewModel.tickerFlow.collect { value ->+                val count = synchronized(values) { values += value; values.size }+                if (count >= 2) throw kotlinx.coroutines.CancellationException("enough ticks")+            }+        }+        // The ticker runs on viewModelScope (main looper): idle it while waiting+        // for the one-second tick to deliver a second value.+        val deadline = System.currentTimeMillis() + 6_000+        while (System.currentTimeMillis() < deadline) {+            shadowOf(android.os.Looper.getMainLooper()).idle()+            val count = synchronized(values) { values.size }+            if (count >= 2) break+            Thread.sleep(10)+        }+        job.cancel()+        val snapshot = synchronized(values) { values.toList() }+        assertTrue(snapshot.size >= 2, "expected at least 2 ticks, got $snapshot")+        assertTrue(snapshot[1] >= snapshot[0])+    }++    @Test fun tickerStartsNearNowAndUiContractsHaveSaneDefaults() {+        val viewModel = vm()+        val before = System.currentTimeMillis()+        val tick = viewModel.tickerFlow.value+        assertTrue(tick in before - 10_000..System.currentTimeMillis() + 10_000)++        val menu = MenuUiState()+        assertTrue(menu.passwords.isEmpty())+        assertTrue(menu.passkeys.isEmpty())+        assertFalse(menu.loading)+        assertEquals(0L, menu.now())+        val edit = PasswordEditUiState()+        assertEquals("", edit.saved.name)+        assertEquals(0L, edit.saved.id)+        assertNull(edit.draft)+        // The Noop actions object accepts every callback without effect.+        PasswordsActions.Noop.copyToClipboard("x", "y")+        PasswordsActions.Noop.delete(Password())+        PasswordsActions.Noop.updateDraft { it }+        PasswordsActions.Noop.saveDraft()+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.ktnew file mode 100644index 0000000000..a8eab47e5c--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.kt@@ -0,0 +1,197 @@+package com.vayunmathur.passwords.platform++import android.app.Service+import android.content.Intent+import android.net.Uri+import android.os.Bundle+import android.os.CancellationSignal+import android.os.OutcomeReceiver+import androidx.credentials.exceptions.CreateCredentialException+import androidx.credentials.exceptions.GetCredentialException+import androidx.credentials.provider.BeginCreateCredentialResponse+import androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest+import androidx.credentials.exceptions.ClearCredentialException+import androidx.credentials.provider.BeginCreateCustomCredentialRequest+import androidx.credentials.provider.BeginGetCredentialRequest+import androidx.credentials.provider.BeginGetPublicKeyCredentialOption+import androidx.credentials.provider.ProviderClearCredentialStateRequest+import androidx.credentials.provider.BeginGetCredentialResponse+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.platform.cable.CableActivity+import com.vayunmathur.passwords.platform.cable.CableService+import com.vayunmathur.passwords.platform.cable.CableTunnel+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class ServicesExtraTest {++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private val app: android.app.Application get() =+        androidx.test.core.app.ApplicationProvider.getApplicationContext()++    // ---- PasskeyCredentialService ----++    @Test fun credentialServiceCreatePublicKeyReturnsEntry() {+        val service = Robolectric.buildService(PasskeyCredentialService::class.java).create().get()+        var response: BeginCreateCredentialResponse? = null+        var error: CreateCredentialException? = null+        service.onBeginCreateCredentialRequest(+            BeginCreatePublicKeyCredentialRequest(+                requestJson = """{"rp":{"id":"example.com"},"user":{"id":"dQ","name":"a"},"challenge":"Yw"}""",+                candidateQueryData = Bundle(),+                callingAppInfo = null,+            ),+            CancellationSignal(),+            object : OutcomeReceiver<BeginCreateCredentialResponse, CreateCredentialException> {+                override fun onResult(r: BeginCreateCredentialResponse) { response = r }+                override fun onError(e: CreateCredentialException) { error = e }+            },+        )+        assertEquals(null, error)+        assertEquals(1, response!!.createEntries.size)+    }++    @Test fun credentialServiceGetWithUnlockedVaultAndNoOptionsReturnsEmpty() {+        DatabaseHelper(app).storePassphrase("db-passphrase")+        val service = Robolectric.buildService(PasskeyCredentialService::class.java).create().get()+        var response: BeginGetCredentialResponse? = null+        service.onBeginGetCredentialRequest(+            BeginGetCredentialRequest(listOf()),+            CancellationSignal(),+            object : OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException> {+                override fun onResult(r: BeginGetCredentialResponse) { response = r }+                override fun onError(e: GetCredentialException) = Unit+            },+        )+        assertNotNull(response)+        assertEquals(0, response!!.credentialEntries.size)+        assertEquals(0, response!!.authenticationActions.size)+    }++    // ---- CableActivity / CableService ----++    @Test fun cableActivityWithValidFidoDataUriStillFinishesWithoutBiometric() {+        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("fido:/12345"))+        val controller = Robolectric.buildActivity(CableActivity::class.java, intent)+        controller.create()+        // The URI passed the gate, so the activity is waiting on the biometric+        // prompt rather than finishing immediately like a rejected URI does.+        assertEquals(false, controller.get().isFinishing)+    }++    @Test fun cableActivityWithUppercaseFidoExtraPassesUriGate() {+        val intent = Intent().putExtra(CableService.EXTRA_FIDO_URI, "FIDO:/12345")+        val controller = Robolectric.buildActivity(CableActivity::class.java, intent)+        controller.create()+        assertEquals(false, controller.get().isFinishing)+    }++    @Test fun cableServiceWithMalformedUriStopsItself() {+        val controller = Robolectric.buildService(CableService::class.java).create()+        val service = controller.get()+        val intent = Intent().putExtra(CableService.EXTRA_FIDO_URI, "FIDO:/not-digits")+        assertEquals(Service.START_NOT_STICKY, service.onStartCommand(intent, 0, 7))+        // The session coroutine runs on IO: wait for it to fail parse and stop the service.+        val deadline = System.currentTimeMillis() + 5_000+        while (System.currentTimeMillis() < deadline && !shadowOf(service).isStoppedBySelf) {+            Thread.sleep(10)+        }+        assertTrue(shadowOf(service).isStoppedBySelf)+        controller.destroy()+    }++    @Test fun cableServiceBindReturnsNull() {+        val service = Robolectric.buildService(CableService::class.java).create().get()+        assertEquals(null, service.onBind(Intent()))+    }++    @Test fun cableTunnelHexEncoding() {+        assertEquals("", CableTunnel.hex(ByteArray(0)))+        assertEquals("00ff10ab", CableTunnel.hex(byteArrayOf(0, 0xFF.toByte(), 0x10, 0xAB.toByte())))+        assertEquals("fido.cable", CableTunnel.SUBPROTOCOL)+        assertEquals("X-caBLE-Routing-ID", CableTunnel.ROUTING_ID_HEADER)+    }++    // ---- AppBackupAgent ----++    @Test fun backupAgentConfig() {+        // dbConfigs decrypts the stored vault passphrase; without one it is+        // expected to fail, so store one first like an unlocked vault would.+        DatabaseHelper(app).storePassphrase("backup-pw")+        val agent = Robolectric.buildBackupAgent(+            com.vayunmathur.passwords.platform.AppBackupAgent::class.java,+        ).create().get()+        assertEquals(listOf("passwords-db" to "backup-pw"), agent.dbConfigs)+        assertTrue(agent.extraFiles.isEmpty())+        assertNotNull(agent.dbCodec)+    }++    @Test fun credentialServiceCreateCustomCredentialReturnsEmptyResponse() {+        val service = Robolectric.buildService(PasskeyCredentialService::class.java).create().get()+        var response: BeginCreateCredentialResponse? = null+        service.onBeginCreateCredentialRequest(+            BeginCreateCustomCredentialRequest(+                "com.example.Custom",+                Bundle(),+                CallingAppInfoFactory.callingAppInfo("com.example.app"),+            ),+            CancellationSignal(),+            object : OutcomeReceiver<BeginCreateCredentialResponse, CreateCredentialException> {+                override fun onResult(r: BeginCreateCredentialResponse) { response = r }+                override fun onError(e: CreateCredentialException) = Unit+            },+        )+        assertNotNull(response)+        assertEquals(0, response!!.createEntries.size)+    }++    @Test fun credentialServiceClearStateCompletesWithNull() {+        val service = Robolectric.buildService(PasskeyCredentialService::class.java).create().get()+        var completed = false+        service.onClearCredentialStateRequest(+            ProviderClearCredentialStateRequest(+                CallingAppInfoFactory.callingAppInfo("com.example.app"),+            ),+            CancellationSignal(),+            object : OutcomeReceiver<Void?, ClearCredentialException> {+                override fun onResult(r: Void?) { completed = true }+                override fun onError(e: ClearCredentialException) = Unit+            },+        )+        assertTrue(completed)+    }++    @Test fun credentialServiceGetWithBlankRpOptionReturnsEmpty() {+        DatabaseHelper(app).storePassphrase("db-passphrase")+        val service = Robolectric.buildService(PasskeyCredentialService::class.java).create().get()+        var response: BeginGetCredentialResponse? = null+        service.onBeginGetCredentialRequest(+            BeginGetCredentialRequest(+                listOf(+                    BeginGetPublicKeyCredentialOption(+                        Bundle(), "req-blank", """{"challenge":"Y2hhbGxlbmdl"}""",+                    ),+                ),+            ),+            CancellationSignal(),+            object : OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException> {+                override fun onResult(r: BeginGetCredentialResponse) { response = r }+                override fun onError(e: GetCredentialException) = Unit+            },+        )+        assertNotNull(response)+        assertEquals(0, response!!.credentialEntries.size)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CablePureExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CablePureExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CablePureExtraTest.ktnew file mode 100644index 0000000000..032fca7c9c--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CablePureExtraTest.kt@@ -0,0 +1,184 @@+package com.vayunmathur.passwords.platform.cable++import com.vayunmathur.passwords.domain.Cbor+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class CablePureExtraTest {++    // ---- CborReader: every major type, widths, and failure modes ----++    @Test fun readerDecodesAllWidthsAndTypes() {+        assertEquals(0L, CborReader.decode(byteArrayOf(0x00)))+        assertEquals(255L, CborReader.decode(byteArrayOf(0x18, 0xFF.toByte())))+        assertEquals(65_536L, CborReader.decode(byteArrayOf(0x1A, 0, 1, 0, 0)))+        assertEquals(-1L, CborReader.decode(byteArrayOf(0x20)))+        assertEquals(-257L, CborReader.decode(byteArrayOf(0x39, 0x01, 0x00)))+        assertEquals("abc", CborReader.decode(byteArrayOf(0x63, 'a'.code.toByte(), 'b'.code.toByte(), 'c'.code.toByte())))+        assertEquals(listOf(1L, "x"), CborReader.decode(Cbor.encode(listOf(1L, "x"))))+        assertEquals(true, CborReader.decode(byteArrayOf(0xF5.toByte())))+        assertEquals(false, CborReader.decode(byteArrayOf(0xF4.toByte())))+        assertEquals(null, CborReader.decode(byteArrayOf(0xF6.toByte())))+        assertEquals(null, CborReader.decode(byteArrayOf(0xF7.toByte())))+        // Round-trip through the canonical encoder for a CTAP-shaped int-keyed map.+        val wire = Cbor.encode(mapOf(1L to byteArrayOf(4, 5), 2L to -3L, 3L to "ctap"))+        val decoded = CborReader(wire).readIntMap()+        assertEquals(listOf(4.toByte(), 5.toByte()), (decoded[1] as ByteArray).toList())+        assertEquals(-3L, decoded[2])+        assertEquals("ctap", decoded[3])+    }++    @Test fun readerTracksRemainingAndTypedGetters() {+        val reader = CborReader(Cbor.encode(listOf(7L, byteArrayOf(1))))+        val list = reader.readValue() as List<*>+        assertEquals(7L, list[0])+        assertEquals(0, reader.remaining)+        assertEquals(42L, CborReader(byteArrayOf(0x18, 42)).readInt())+        assertEquals(listOf(9.toByte()), CborReader(byteArrayOf(0x41, 9)).readByteString().toList())+    }++    @Test fun readerRejectsTruncatedAndUnsupportedInput() {+        assertFailsWith<IllegalStateException> { CborReader.decode(ByteArray(0)) }+        assertFailsWith<IllegalStateException> { CborReader.decode(byteArrayOf(0x18)) } // missing arg byte+        assertFailsWith<IllegalStateException> { CborReader.decode(byteArrayOf(0x43, 1)) } // short byte string+        assertFailsWith<IllegalStateException> { CborReader.decode(byteArrayOf(0x1F)) } // reserved additional info+        assertFailsWith<IllegalStateException> { CborReader.decode(byteArrayOf(0xF8.toByte(), 0)) } // simple next-byte+        assertFailsWith<IllegalStateException> { CborReader(byteArrayOf(0x61, 'a'.code.toByte())).readInt() }+        assertFailsWith<IllegalStateException> { CborReader(byteArrayOf(0x01)).readByteString() }+        assertFailsWith<IllegalStateException> { CborReader(byteArrayOf(0x01)).readIntMap() }+    }++    // ---- CableQrData: parsing validation ----++    private fun qrCbor(extra: Map<Long, Any> = emptyMap()): ByteArray {+        val base = linkedMapOf<Any, Any>(+            0L to ByteArray(CableQrData.PEER_KEY_SIZE) { (it + 1).toByte() },+            1L to ByteArray(CableQrData.QR_SECRET_SIZE) { (it + 40).toByte() },+            2L to 2L,+        )+        for ((k, v) in extra) base[k] = v+        return Cbor.encode(base)+    }++    @Test fun qrFromCborReadsOptionalFields() {+        val data = CableQrData.fromCbor(qrCbor(mapOf(3L to 1_700_000_000L, 4L to true, 5L to "ga")))+        assertEquals(CableQrData.PEER_KEY_SIZE, data.peerPublicKey.size)+        assertEquals(CableQrData.QR_SECRET_SIZE, data.qrSecret.size)+        assertEquals(2, data.numKnownDomains)+        assertEquals(1_700_000_000L, data.timestampSeconds)+        assertEquals(true, data.supportsLinking)+        assertEquals("ga", data.requestTypeHint)+        val minimal = CableQrData.fromCbor(qrCbor())+        assertEquals(null, minimal.timestampSeconds)+        assertEquals(null, minimal.supportsLinking)+        assertEquals(null, minimal.requestTypeHint)+    }++    @Test fun qrRejectsBadShapes() {+        assertFailsWith<IllegalStateException> { CableQrData.parse("https://example.com") }+        assertFailsWith<IllegalArgumentException> { CableQrData.digitDecode("12a45") }+        assertFailsWith<IllegalArgumentException> { CableQrData.digitDecode("1") } // 1 digit is not a valid chunk+        assertFailsWith<IllegalStateException> { CableQrData.fromCbor(Cbor.encode(listOf(1L))) } // not a map+        assertFailsWith<IllegalStateException> {+            CableQrData.fromCbor(Cbor.encode(mapOf(1L to ByteArray(16)))) // missing peer key+        }+        assertFailsWith<IllegalArgumentException> {+            CableQrData.fromCbor(+                Cbor.encode(mapOf(0L to ByteArray(10), 1L to ByteArray(16))),+            )+        }+        assertFailsWith<IllegalArgumentException> {+            CableQrData.fromCbor(+                Cbor.encode(mapOf(0L to ByteArray(33), 1L to ByteArray(3))),+            )+        }+        // Lowercase scheme reaches the same digit decoder as the canonical uppercase one.+        assertFailsWith<IllegalArgumentException> { CableQrData.parse("fido:/12a") }+    }++    @Test fun qrDigitDecodePartialChunks() {+        // 3 digits encode 1 byte, 5 digits 2 bytes, 17 digits a full 7-byte chunk.+        assertEquals(listOf(5.toByte()), CableQrData.digitDecode("005").toList())+        assertEquals(listOf(1.toByte(), 2.toByte()), CableQrData.digitDecode("00513").toList())+        assertEquals(ByteArray(7).toList(), CableQrData.digitDecode("0".repeat(17)).toList())+        assertEquals(0, CableQrData.digitDecode("").size)+    }++    // ---- Crypter padding / nonce ----++    @Test fun crypterNonceLayoutAndPadding() {+        val nonce = Crypter.nonce(0x01020304)+        assertEquals(12, nonce.size)+        assertEquals(listOf(0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4), nonce.map { it.toInt() and 0xFF })++        val empty = Crypter.pad(ByteArray(0))+        assertEquals(32, empty.size)+        assertEquals(31, empty.last().toInt())+        assertEquals(0, Crypter.unpad(empty).size)++        val exact = ByteArray(31) { it.toByte() }+        val padded = Crypter.pad(exact)+        assertEquals(32, padded.size)+        assertEquals(0, padded.last().toInt())+        assertEquals(exact.toList(), Crypter.unpad(padded).toList())++        val over = ByteArray(32) { it.toByte() }+        assertEquals(64, Crypter.pad(over).size)+        assertEquals(over.toList(), Crypter.unpad(Crypter.pad(over)).toList())++        assertFailsWith<IllegalArgumentException> { Crypter.unpad(ByteArray(0)) }+        assertFailsWith<IllegalArgumentException> { Crypter.unpad(byteArrayOf(0x7F)) }+    }++    @Test fun crypterSequencesAreIndependentPerDirection() {+        val keyA = ByteArray(32) { 1 }+        val keyB = ByteArray(32) { 2 }+        val alice = Crypter(keyA, keyB)+        val bob = Crypter(keyB, keyA)+        val first = alice.encrypt("hello cable".toByteArray())+        val second = alice.encrypt("second".toByteArray())+        assertEquals("hello cable", bob.decrypt(first).decodeToString())+        assertEquals("second", bob.decrypt(second).decodeToString())+        // Replaying the first ciphertext as if it were the second message must not decrypt+        // to the first plaintext under the advanced counter (GCM tag or nonce mismatch).+        val bobFresh = Crypter(keyB, keyA)+        bobFresh.decrypt(first)+        assertFailsWith<Exception> { bobFresh.decrypt(first) }+    }++    @Test fun qrDigitRoundTripForEveryLength() {+        // Test-side encoder mirroring the QR digit scheme: 7 bytes -> 17 digits,+        // trailing partial chunks use 3/5/8/10/13/15 digits for 1..6 bytes.+        val partialDigits = intArrayOf(0, 3, 5, 8, 10, 13, 15, 0)+        fun encode(bytes: ByteArray): String {+            val sb = StringBuilder()+            var i = 0+            while (i + 7 <= bytes.size) {+                var v = 0L+                for (j in 6 downTo 0) v = (v shl 8) or (bytes[i + j].toLong() and 0xFF)+                sb.append(v.toString().padStart(17, '0'))+                i += 7+            }+            val rem = bytes.size - i+            if (rem > 0) {+                var v = 0L+                for (j in rem - 1 downTo 0) v = (v shl 8) or (bytes[i + j].toLong() and 0xFF)+                sb.append(v.toString().padStart(partialDigits[rem], '0'))+            }+            return sb.toString()+        }+        for (length in 0..22) {+            val bytes = ByteArray(length) { (it * 37 + length).toByte() }+            assertEquals(bytes.toList(), CableQrData.digitDecode(encode(bytes)).toList(), "length $length")+        }+        // Full URI parse round-trip through the digit encoding.+        val cbor = qrCbor(mapOf(5L to "mc"))+        val parsed = CableQrData.parse("FIDO:/" + encode(cbor))+        assertEquals("mc", parsed.requestTypeHint)+        assertEquals(2, parsed.numKnownDomains)+        val lower = CableQrData.parse("  fido:/" + encode(cbor) + "  ")+        assertEquals("mc", lower.requestTypeHint)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CborReaderAndKeysExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CborReaderAndKeysExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CborReaderAndKeysExtraTest.ktnew file mode 100644index 0000000000..bc219decac--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CborReaderAndKeysExtraTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.passwords.platform.cable++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class CborReaderAndKeysExtraTest {++    @Test fun readerRejectsNullMapKeysAndOversizedLengths() {+        // Map with a null (0xF6) key.+        assertFailsWith<IllegalStateException> {+            CborReader.decode(byteArrayOf(0xA1.toByte(), 0xF6.toByte(), 0x01))+        }+        // Byte string claiming 2^32-1 bytes: length is out of Int range.+        assertFailsWith<IllegalStateException> {+            CborReader.decode(byteArrayOf(0x5A, 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte()))+        }+        // Tag major type (6) is unsupported by this reader.+        assertFailsWith<IllegalStateException> { CborReader.decode(byteArrayOf(0xC0.toByte())) }+        // Multi-byte unsigned via the 8-byte argument form.+        assertEquals(1L, CborReader.decode(byteArrayOf(0x1B, 0, 0, 0, 0, 0, 0, 0, 1)))+        // Nested arrays keep their structure.+        val nested = CborReader.decode(+            com.vayunmathur.passwords.domain.Cbor.encode(listOf(listOf(1L, 2L), emptyList<Any>())),+        )+        assertEquals(listOf(listOf(1L, 2L), emptyList<Any>()), nested)+    }++    @Test fun hkdfLengthAndSaltSemantics() {+        val ikm = ByteArray(16) { it.toByte() }+        val info = byteArrayOf(1, 0, 0, 0)+        assertEquals(0, CableKeys.hkdf(ikm, null, info, 0).size)+        assertFailsWith<IllegalArgumentException> {+            CableKeys.hkdf(ikm, null, info, 255 * 32 + 1)+        }+        // Null and empty salt mean the same RFC 5869 zero salt; a real salt changes the output.+        val unsalted = CableKeys.hkdf(ikm, null, info, 32)+        assertEquals(unsalted.toList(), CableKeys.hkdf(ikm, ByteArray(0), info, 32).toList())+        assertFalse(unsalted.contentEquals(CableKeys.hkdf(ikm, byteArrayOf(9), info, 32)))+        // Longer outputs extend, never alter, the prefix (HKDF expand property).+        val longer = CableKeys.hkdf(ikm, null, info, 64)+        assertEquals(unsalted.toList(), longer.copyOfRange(0, 32).toList())+    }++    @Test fun derivedKeysArePurposeSeparatedAndSized() {+        val secret = ByteArray(16) { (it * 7).toByte() }+        assertEquals(64, CableKeys.eidKey(secret).size)+        assertEquals(16, CableKeys.tunnelId(secret).size)+        val eid = CableEid.buildPlaintext(ByteArray(10), ByteArray(3), 0)+        assertEquals(32, CableKeys.psk(secret, eid).size)+        // Every purpose derives different material from the same secret.+        val outputs = CableKeys.Purpose.entries.map { CableKeys.derive(secret, null, it, 16).toList() }+        assertEquals(outputs.size, outputs.distinct().size)+        assertEquals(listOf(1, 2, 3, 4, 5, 6), CableKeys.Purpose.entries.map { it.value })+        // A different secret changes every derived key.+        assertFalse(CableKeys.eidKey(secret).contentEquals(CableKeys.eidKey(ByteArray(16) { 0x55 })))+        assertEquals(listOf(0x78, 0x56, 0x34, 0x12), CableKeys.leUint32(0x12345678).map { it.toInt() and 0xFF })+        assertTrue(CableKeys.leUint32(-1).all { it == 0xFF.toByte() })+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CryptoEdgesExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CryptoEdgesExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CryptoEdgesExtraTest.ktnew file mode 100644index 0000000000..8fdc793839--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CryptoEdgesExtraTest.kt@@ -0,0 +1,66 @@+package com.vayunmathur.passwords.platform.cable++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class CryptoEdgesExtraTest {++    @Test fun eidValidationAndLayout() {+        assertFailsWith<IllegalArgumentException> {+            CableEid.buildPlaintext(ByteArray(3), ByteArray(3), 0)+        }+        assertFailsWith<IllegalArgumentException> {+            CableEid.buildPlaintext(ByteArray(10), ByteArray(2), 0)+        }+        assertFailsWith<IllegalArgumentException> { CableEid.encrypt(ByteArray(3), ByteArray(64)) }+        assertFailsWith<IllegalArgumentException> { CableEid.encrypt(ByteArray(16), ByteArray(10)) }++        val nonce = ByteArray(10) { (it + 1).toByte() }+        val eid = CableEid.buildPlaintext(nonce, byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte()), 0x1234)+        assertEquals(0.toByte(), eid[0]) // reserved+        assertEquals(nonce.toList(), eid.copyOfRange(1, 11).toList())+        assertEquals(listOf(0xAA, 0xBB, 0xCC), eid.copyOfRange(11, 14).map { it.toInt() and 0xFF })+        // Domain id is little-endian.+        assertEquals(0x34, eid[14].toInt() and 0xFF)+        assertEquals(0x12, eid[15].toInt() and 0xFF)++        assertEquals(10, CableEid.randomNonce().size)+        assertFalse(CableEid.randomNonce().contentEquals(CableEid.randomNonce()))+        assertEquals(20, CableEid.ADVERT_SIZE)+        assertEquals(0xFDE2, CableEid.SERVICE_DATA_UUID16)+    }++    @Test fun eidEncryptIsDeterministicAndKeySensitive() {+        val plaintext = CableEid.buildPlaintext(ByteArray(10) { 1 }, ByteArray(3) { 2 }, 7)+        val key = ByteArray(64) { it.toByte() }+        val a = CableEid.encrypt(plaintext, key)+        val b = CableEid.encrypt(plaintext, key)+        assertEquals(a.toList(), b.toList())+        assertEquals(CableEid.ADVERT_SIZE, a.size)+        val other = CableEid.encrypt(plaintext, ByteArray(64) { (it + 100).toByte() })+        assertFalse(a.contentEquals(other))+    }++    @Test fun p256RejectsBadEncodings() {+        assertFailsWith<IllegalArgumentException> { P256.decodePoint(byteArrayOf(0x05, 1, 2)) }+        assertFailsWith<IllegalArgumentException> { P256.decodePoint(byteArrayOf(0x04, 1, 2)) } // too short+        assertFailsWith<IllegalArgumentException> { P256.decodePoint(byteArrayOf(0x02, 1, 2)) } // too short+        assertFailsWith<IndexOutOfBoundsException> { P256.decodePoint(ByteArray(0)) }+    }++    @Test fun p256UncompressedRoundTripAndSizes() {+        val pair = P256.generateKeyPair()+        val uncompressed = P256.toUncompressed(pair.public)+        assertEquals(P256.UNCOMPRESSED_SIZE, uncompressed.size)+        assertEquals(0x04, uncompressed[0].toInt())+        val decoded = P256.decodePoint(uncompressed)+        assertEquals(P256.toCompressed(pair.public).toList(), P256.toCompressed(decoded).toList())+        // ECDH with itself equals ECDH in the other argument position (same key both sides).+        val secret = P256.ecdh(pair.private, pair.public)+        assertEquals(P256.DH_OUTPUT_SIZE, secret.size)+        assertTrue(secret.any { it != 0.toByte() })+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapParseExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapParseExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapParseExtraTest.ktnew file mode 100644index 0000000000..0b0559b776--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapParseExtraTest.kt@@ -0,0 +1,222 @@+package com.vayunmathur.passwords.platform.cable++import com.vayunmathur.passwords.domain.Cbor+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class CtapParseExtraTest {++    private val hash = ByteArray(32) { 0x11 }++    // ---- getAssertion parsing ----++    @Test fun getAssertionDefaultsAndFiltering() {+        val payload = Cbor.encode(+            linkedMapOf<Any, Any>(+                1L to "example.com",+                2L to hash,+                3L to listOf(+                    linkedMapOf<Any, Any>("id" to byteArrayOf(1, 2), "type" to "public-key"),+                    linkedMapOf<Any, Any>("type" to "public-key"), // no id: skipped+                    "garbage", // not a map: skipped+                    linkedMapOf<Any, Any>("id" to byteArrayOf(3)), // type defaults+                ),+                5L to linkedMapOf<Any, Any>("up" to false, "junk" to "not-bool", 9L to true),+            ),+        )+        val req = CtapGetAssertionRequest.parse(payload)+        assertEquals("example.com", req.rpId)+        assertEquals(32, req.clientDataHash.size)+        assertEquals(2, req.allowList.size)+        assertEquals(listOf(1.toByte(), 2.toByte()), req.allowList[0].id.toList())+        assertEquals("public-key", req.allowList[1].type)+        // Non-boolean and non-string-keyed options are dropped.+        assertEquals(mapOf("up" to false), req.options)+        assertEquals(false, req.userPresenceRequired)+        assertEquals(false, req.userVerificationRequired)+        assertEquals(null, req.extensions)+    }++    @Test fun getAssertionOptionDefaultsFollowCtap() {+        val payload = Cbor.encode(linkedMapOf<Any, Any>(1L to "a.com", 2L to hash))+        val req = CtapGetAssertionRequest.parse(payload)+        assertTrue(req.allowList.isEmpty())+        assertTrue(req.userPresenceRequired) // up defaults true+        assertEquals(false, req.userVerificationRequired) // uv defaults false+    }++    @Test fun getAssertionMissingRequiredFieldsThrows() {+        assertFailsWith<IllegalStateException> {+            CtapGetAssertionRequest.parse(Cbor.encode(linkedMapOf<Any, Any>(2L to hash)))+        }+        assertFailsWith<IllegalStateException> {+            CtapGetAssertionRequest.parse(Cbor.encode(linkedMapOf<Any, Any>(1L to "a.com")))+        }+    }++    @Test fun getAssertionResponseEncodeIncludesOptionalUserFields() {+        val response = CtapGetAssertionResponse(+            credentialId = byteArrayOf(9),+            authData = byteArrayOf(1, 2),+            signature = byteArrayOf(3, 4),+            userId = byteArrayOf(7, 8),+            userName = "alice",+            userDisplayName = "Alice A",+            numberOfCredentials = 3,+        )+        val map = CborReader.decode(response.encode()) as Map<*, *>+        val user = map[4L] as Map<*, *>+        assertEquals("alice", user["name"])+        assertEquals("Alice A", user["displayName"])+        assertEquals(3L, map[5L])+        val minimal = CtapGetAssertionResponse(byteArrayOf(9), byteArrayOf(1), byteArrayOf(2), byteArrayOf(7))+        val minMap = CborReader.decode(minimal.encode()) as Map<*, *>+        assertEquals(null, minMap[5L])+        assertEquals(setOf("id"), (minMap[4L] as Map<*, *>).keys)+    }++    // ---- makeCredential parsing ----++    private fun makePayload(+        rp: Any? = linkedMapOf<Any, Any>("id" to "example.com"),+        user: Any? = linkedMapOf<Any, Any>("id" to byteArrayOf(5, 6)),+        hashValue: Any? = hash,+        algorithms: Any? = listOf(linkedMapOf<Any, Any>("alg" to -7L, "type" to "public-key")),+    ): ByteArray {+        val map = linkedMapOf<Any, Any>()+        hashValue?.let { map[1L] = it }+        rp?.let { map[2L] = it }+        user?.let { map[3L] = it }+        algorithms?.let { map[4L] = it }+        return Cbor.encode(map)+    }++    @Test fun makeCredentialFallbacksAndDerivedFlags() {+        val req = CtapMakeCredentialRequest.parse(makePayload())+        assertEquals("example.com", req.rpId)+        assertEquals("example.com", req.rpName) // falls back to rpId+        assertEquals("", req.userName)+        assertEquals("", req.userDisplayName) // falls back to userName+        assertEquals(listOf(-7L), req.algorithms)+        assertTrue(req.supportsEs256)+        assertEquals(false, req.residentKey)+        assertEquals(false, req.userVerificationRequired)+        assertEquals(null, req.userPresenceOption)+        assertTrue(req.excludeList.isEmpty())+    }++    @Test fun makeCredentialAlgorithmAndExcludeFiltering() {+        val payload = run {+            val map = linkedMapOf<Any, Any>(+                1L to hash,+                2L to linkedMapOf<Any, Any>("id" to "example.com", "name" to "Example"),+                3L to linkedMapOf<Any, Any>(+                    "id" to byteArrayOf(5), "name" to "alice", "displayName" to "Alice",+                ),+                4L to listOf(+                    linkedMapOf<Any, Any>("alg" to -7L, "type" to "public-key"),+                    linkedMapOf<Any, Any>("alg" to -257L, "type" to "public-key"),+                    linkedMapOf<Any, Any>("alg" to -8L, "type" to "token"), // wrong type: skipped+                    linkedMapOf<Any, Any>("type" to "public-key"), // no alg: skipped+                ),+                5L to listOf(+                    linkedMapOf<Any, Any>("id" to byteArrayOf(1), "type" to "public-key"),+                    linkedMapOf<Any, Any>("type" to "public-key"), // no id: skipped+                ),+                7L to linkedMapOf<Any, Any>("rk" to true, "uv" to true, "up" to false),+            )+            Cbor.encode(map)+        }+        val req = CtapMakeCredentialRequest.parse(payload)+        assertEquals("Example", req.rpName)+        assertEquals("Alice", req.userDisplayName)+        assertEquals(listOf(-7L, -257L), req.algorithms)+        assertEquals(1, req.excludeList.size)+        assertTrue(req.residentKey)+        assertTrue(req.userVerificationRequired)+        assertEquals(false, req.userPresenceOption)+    }++    @Test fun makeCredentialMissingRequiredFieldsThrows() {+        assertFailsWith<IllegalStateException> { CtapMakeCredentialRequest.parse(makePayload(rp = null)) }+        assertFailsWith<IllegalStateException> { CtapMakeCredentialRequest.parse(makePayload(user = null)) }+        assertFailsWith<IllegalStateException> {+            CtapMakeCredentialRequest.parse(makePayload(rp = linkedMapOf<Any, Any>("name" to "x")))+        }+        assertFailsWith<IllegalStateException> {+            CtapMakeCredentialRequest.parse(makePayload(user = linkedMapOf<Any, Any>("name" to "x")))+        }+        assertFailsWith<IllegalStateException> { CtapMakeCredentialRequest.parse(makePayload(hashValue = null)) }+    }++    @Test fun ctapResponseAndDescriptorDefaults() {+        assertEquals(listOf(0.toByte()), Ctap.response(Ctap.OK).toList())+        val withPayload = Ctap.response(Ctap.ERR_OTHER, byteArrayOf(1, 2))+        assertEquals(Ctap.ERR_OTHER.toByte(), withPayload[0])+        assertEquals(3, withPayload.size)+        val descriptor = Ctap.CredentialDescriptor(byteArrayOf(4))+        assertEquals("public-key", descriptor.type)+        assertEquals(16, Ctap.ZERO_AAGUID.size)+        assertTrue(Ctap.ZERO_AAGUID.all { it == 0.toByte() })+    }++    @Test fun getInfoEncodeRoundTripsCustomValues() {+        val info = CtapGetInfoResponse(+            versions = listOf("FIDO_2_0"),+            extensions = emptyList(),+            options = linkedMapOf("uv" to false),+            transports = listOf("internal"),+        )+        val map = CborReader.decode(info.encode()) as Map<*, *>+        assertEquals(listOf("FIDO_2_0"), map[1L])+        assertEquals(emptyList<String>(), map[2L])+        assertEquals(mapOf("uv" to false), map[4L])+        assertEquals(listOf("internal"), map[9L])+        // MakeCredential response encode: fmt/authData/attStmt at keys 1/2/3.+        val mc = CtapMakeCredentialResponse(authData = byteArrayOf(8), fmt = "packed")+        val mcMap = CborReader.decode(mc.encode()) as Map<*, *>+        assertEquals("packed", mcMap[1L])+        assertEquals(listOf(8.toByte()), (mcMap[2L] as ByteArray).toList())+    }++    @Test fun makeCredentialSkipsMalformedAlgorithmExcludeAndOptionEntries() {+        val payload = run {+            val map = linkedMapOf<Any, Any>(+                1L to hash,+                2L to linkedMapOf<Any, Any>("id" to "example.com"),+                3L to linkedMapOf<Any, Any>("id" to byteArrayOf(5)),+                4L to listOf(+                    "not-a-map",+                    linkedMapOf<Any, Any>("alg" to "not-a-long", "type" to "public-key"),+                    linkedMapOf<Any, Any>("alg" to -7L, "type" to "public-key"),+                ),+                5L to listOf(+                    "not-a-map",+                    linkedMapOf<Any, Any>("id" to "not-bytes"),+                    linkedMapOf<Any, Any>("id" to byteArrayOf(1)),+                ),+                7L to linkedMapOf<Any, Any>("rk" to "not-a-bool", 4L to true, "uv" to true),+            )+            com.vayunmathur.passwords.domain.Cbor.encode(map)+        }+        val req = CtapMakeCredentialRequest.parse(payload)+        assertEquals(listOf(-7L), req.algorithms)+        assertEquals(1, req.excludeList.size)+        assertEquals(mapOf("uv" to true), req.options)+    }++    @Test fun getAssertionSkipsMalformedOptionEntries() {+        val payload = com.vayunmathur.passwords.domain.Cbor.encode(+            linkedMapOf<Any, Any>(+                1L to "example.com",+                2L to hash,+                5L to linkedMapOf<Any, Any>(9L to true, "up" to "not-a-bool", "uv" to true),+            ),+        )+        val req = CtapGetAssertionRequest.parse(payload)+        assertEquals(mapOf("uv" to true), req.options)+        assertTrue(req.userVerificationRequired)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapProcessorExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapProcessorExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapProcessorExtraTest.ktnew file mode 100644index 0000000000..b0ff9f56c2--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapProcessorExtraTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.passwords.platform.cable++import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.domain.Cbor+import kotlinx.coroutines.runBlocking+import java.security.KeyPairGenerator+import java.security.MessageDigest+import java.security.spec.ECGenParameterSpec+import kotlin.io.encoding.Base64+import kotlin.io.encoding.ExperimentalEncodingApi+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@OptIn(ExperimentalEncodingApi::class)+class CtapProcessorExtraTest {++    private val urlEncoder = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT)+    private val hash = MessageDigest.getInstance("SHA-256").digest("h".toByteArray())++    private fun storedPasskey(+        id: Long,+        rpId: String,+        credBytes: ByteArray,+        lastUsed: Long = 0,+        userId: String = "dXNlcg", // "user"+    ): Passkey {+        val kp = KeyPairGenerator.getInstance("EC").apply {+            initialize(ECGenParameterSpec("secp256r1"))+        }.generateKeyPair()+        return Passkey(+            id = id, rpId = rpId, credentialId = urlEncoder.encode(credBytes),+            userId = userId, userName = "user-$id", privateKeyBytes = kp.private.encoded,+            signCount = 0, lastUsedTime = lastUsed, syncId = "pk-$id",+        )+    }++    private fun assertionRequest(+        rpId: String,+        allow: List<ByteArray> = emptyList(),+        uv: Boolean = false,+    ): ByteArray {+        val map = linkedMapOf<Any, Any>(1L to rpId, 2L to hash)+        if (allow.isNotEmpty()) {+            map[3L] = allow.map { linkedMapOf<Any, Any>("id" to it, "type" to "public-key") }+        }+        map[5L] = linkedMapOf<Any, Any>("up" to true, "uv" to uv)+        return byteArrayOf(Ctap.CMD_GET_ASSERTION.toByte()) + Cbor.encode(map)+    }++    @Test fun emptyAndUnknownCommandsReturnStatusBytes() = runBlocking {+        val processor = CtapProcessor(FakePasskeyStore(), userVerified = true)+        assertEquals(Ctap.ERR_INVALID_CBOR.toByte(), processor.process(ByteArray(0))[0])+        assertEquals(Ctap.ERR_NOT_ALLOWED.toByte(), processor.process(byteArrayOf(0x7F))[0])+        assertEquals(Ctap.ERR_NOT_ALLOWED.toByte(), processor.process(byteArrayOf(Ctap.CMD_GET_NEXT_ASSERTION.toByte()))[0])+        // A getInfo command with trailing garbage payload still answers getInfo.+        assertEquals(Ctap.OK.toByte(), processor.process(byteArrayOf(Ctap.CMD_GET_INFO.toByte(), 0xFF.toByte()))[0])+    }++    @Test fun getAssertionUvRequiredButUnverifiedIsDeniedBeforeLookup() = runBlocking {+        val cred = ByteArray(16) { 1 }+        val store = FakePasskeyStore(listOf(storedPasskey(1, "example.com", cred)))+        val processor = CtapProcessor(store, userVerified = false)+        val response = processor.process(assertionRequest("example.com", uv = true))+        assertEquals(Ctap.ERR_OPERATION_DENIED.toByte(), response[0])+        // Denial happens before signing: the counter must not move.+        assertEquals(0, store.store.single().signCount)+    }++    @Test fun allowListSelectsMatchingCredentialAndIgnoresOthers() = runBlocking {+        val credA = ByteArray(16) { 0x0A }+        val credB = ByteArray(16) { 0x0B }+        val a = storedPasskey(1, "example.com", credA, lastUsed = 9_999)+        val b = storedPasskey(2, "example.com", credB, lastUsed = 1)+        val store = FakePasskeyStore(listOf(a, b))+        val processor = CtapProcessor(store, userVerified = true)++        // allowList wins over recency: B is older but explicitly allowed.+        val response = processor.process(assertionRequest("example.com", allow = listOf(credB)))+        assertEquals(Ctap.OK.toByte(), response[0])+        assertEquals(1, store.store.first { it.id == 2L }.signCount)+        assertEquals(0, store.store.first { it.id == 1L }.signCount)++        // An allowList naming only a credential for another RP matches nothing here.+        val foreign = processor.process(assertionRequest("other.com", allow = listOf(credA)))+        assertEquals(Ctap.ERR_NO_CREDENTIALS.toByte(), foreign[0])+        // Unknown allowList ids are skipped, not fatal, when nothing else matches.+        val unknown = processor.process(assertionRequest("example.com", allow = listOf(ByteArray(16) { 0x7E })))+        assertEquals(Ctap.ERR_NO_CREDENTIALS.toByte(), unknown[0])+    }++    @Test fun emptyAllowListPicksMostRecentlyUsed() = runBlocking {+        val older = storedPasskey(1, "example.com", ByteArray(16) { 0x0A }, lastUsed = 10)+        val newer = storedPasskey(2, "example.com", ByteArray(16) { 0x0B }, lastUsed = 20)+        val store = FakePasskeyStore(listOf(older, newer))+        val response = CtapProcessor(store, true).process(assertionRequest("example.com"))+        assertEquals(Ctap.OK.toByte(), response[0])+        assertEquals(1, store.store.first { it.id == 2L }.signCount)+        assertEquals(0, store.store.first { it.id == 1L }.signCount)+    }++    @Test fun assertionWithRawUtf8UserIdFallsBackGracefully() = runBlocking {+        // A stored user handle that is not valid base64url is echoed as raw UTF-8 bytes.+        val cred = ByteArray(16) { 0x0C }+        val pk = storedPasskey(1, "example.com", cred, userId = "raw user!")+        val store = FakePasskeyStore(listOf(pk))+        val response = CtapProcessor(store, true).process(assertionRequest("example.com"))+        assertEquals(Ctap.OK.toByte(), response[0])+        assertTrue(response.size > 1)+    }++    @Test fun malformedAssertionPayloadMapsToErrorStatus() = runBlocking {+        val processor = CtapProcessor(FakePasskeyStore(), userVerified = true)+        // Command byte + truncated CBOR map: parse failure must surface as a CTAP+        // status byte (ERR_OTHER via the processor's catch), never as a throw.+        val response = processor.process(byteArrayOf(Ctap.CMD_GET_ASSERTION.toByte(), 0xA1.toByte()))+        assertTrue(response.isNotEmpty())+        assertTrue(response[0] != Ctap.OK.toByte())+    }++    @Test fun makeCredentialMissingParametersMapsToMissingParameter() = runBlocking {+        val processor = CtapProcessor(FakePasskeyStore(), userVerified = true)+        val emptyMap = byteArrayOf(Ctap.CMD_MAKE_CREDENTIAL.toByte()) + Cbor.encode(emptyMap<Any, Any>())+        assertEquals(Ctap.ERR_MISSING_PARAMETER.toByte(), processor.process(emptyMap)[0])+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/NoiseEdgesExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/NoiseEdgesExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/NoiseEdgesExtraTest.ktnew file mode 100644index 0000000000..0ed5254405--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/NoiseEdgesExtraTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.passwords.platform.cable++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class NoiseEdgesExtraTest {++    @Test fun responderRejectsBadPskAndOutOfOrderCalls() {+        val staticPair = P256.generateKeyPair()+        assertFailsWith<IllegalArgumentException> {+            NoiseResponder(staticPair.public, ByteArray(31))+        }+        assertFailsWith<IllegalArgumentException> {+            NoiseResponder(staticPair.public, ByteArray(33))+        }+        val responder = NoiseResponder(staticPair.public, ByteArray(32) { 0x42 })+        // msg2 cannot be written before msg1 has been read.+        assertFailsWith<IllegalStateException> { responder.writeMessage2() }+        // A truncated first message is rejected before any state is mixed.+        assertFailsWith<IllegalArgumentException> { responder.readMessage1(ByteArray(10)) }+        assertEquals("Noise_KNpsk0_P256_AESGCM_SHA256", NoiseResponder.PROTOCOL_NAME)+    }++    @Test fun responderRejectsForgedMessage1Ciphertext() {+        val staticPair = P256.generateKeyPair()+        val responder = NoiseResponder(staticPair.public, ByteArray(32) { 1 })+        val ephemeral = P256.generateKeyPair()+        // 65-byte ephemeral + 16 zero bytes as the (invalid) AEAD tag for the empty payload.+        val forged = P256.toUncompressed(ephemeral.public) + ByteArray(16)+        assertFailsWith<Exception> { responder.readMessage1(forged) }+        assertTrue(forged.size == 65 + 16)+    }++    @Test fun responderRejectsNonEmptyMessage1Payload() {+        // Build a protocol-valid msg1 whose encrypted payload is one byte instead+        // of empty: decryption must succeed and the payload check must reject it.+        val staticPair = P256.generateKeyPair()+        val psk = ByteArray(32) { 0x2A }+        val responder = NoiseResponder(staticPair.public, psk)+        val msg1 = Initiator(staticPair, psk).buildMessage(byteArrayOf(0x99.toByte()))+        val error = assertFailsWith<IllegalArgumentException> { responder.readMessage1(msg1) }+        assertEquals("Noise msg1 payload must be empty", error.message)+    }++    /** Minimal KNpsk0 initiator, sufficient to produce a valid first handshake message. */+    private class Initiator(staticPair: java.security.KeyPair, psk: ByteArray) {+        private var ck: ByteArray+        private var h: ByteArray+        private var key: ByteArray? = null+        private var nonce = 0+        private val ephemeral = P256.generateKeyPair()++        init {+            val name = NoiseResponder.PROTOCOL_NAME.toByteArray(Charsets.US_ASCII)+            h = name + ByteArray(32 - name.size)+            ck = h.copyOf()+            mixHash(byteArrayOf(1))+            mixHash(P256.toUncompressed(staticPair.public))+            val (c, hh, k) = hkdf3(ck, psk)+            ck = c+            mixHash(hh)+            key = k+            nonce = 0+        }++        fun buildMessage(payload: ByteArray): ByteArray {+            val ePub = P256.toUncompressed(ephemeral.public)+            mixHash(ePub)+            val (c, k) = hkdf2(ck, ePub)+            ck = c+            key = k+            nonce = 0+            return ePub + encryptAndHash(payload)+        }++        private fun mixHash(data: ByteArray) {+            h = java.security.MessageDigest.getInstance("SHA-256").digest(h + data)+        }++        private fun encryptAndHash(plaintext: ByteArray): ByteArray {+            val k = key ?: return plaintext.also { mixHash(it) }+            val n = ByteArray(12)+            n[0] = ((nonce ushr 24) and 0xFF).toByte()+            n[1] = ((nonce ushr 16) and 0xFF).toByte()+            n[2] = ((nonce ushr 8) and 0xFF).toByte()+            n[3] = (nonce and 0xFF).toByte()+            nonce+++            val ct = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding").run {+                init(+                    javax.crypto.Cipher.ENCRYPT_MODE,+                    javax.crypto.spec.SecretKeySpec(k, "AES"),+                    javax.crypto.spec.GCMParameterSpec(128, n),+                )+                updateAAD(h)+                doFinal(plaintext)+            }+            mixHash(ct)+            return ct+        }++        private fun hmac(keyBytes: ByteArray, data: ByteArray): ByteArray =+            javax.crypto.Mac.getInstance("HmacSHA256").run {+                init(javax.crypto.spec.SecretKeySpec(keyBytes, "HmacSHA256"))+                doFinal(data)+            }++        private fun hkdf2(ckIn: ByteArray, ikm: ByteArray): Pair<ByteArray, ByteArray> {+            val tk = hmac(ckIn, ikm)+            val o1 = hmac(tk, byteArrayOf(1))+            val o2 = hmac(tk, o1 + 2)+            return o1 to o2+        }++        private fun hkdf3(ckIn: ByteArray, ikm: ByteArray): Triple<ByteArray, ByteArray, ByteArray> {+            val tk = hmac(ckIn, ikm)+            val o1 = hmac(tk, byteArrayOf(1))+            val o2 = hmac(tk, o1 + 2)+            val o3 = hmac(tk, o2 + 3)+            return Triple(o1, o2, o3)+        }+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/WebAuthnAndBluetoothExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/WebAuthnAndBluetoothExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/WebAuthnAndBluetoothExtraTest.ktnew file mode 100644index 0000000000..059c016c14--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/WebAuthnAndBluetoothExtraTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.passwords.platform.cable++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.data.Passkey+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class WebAuthnAndBluetoothExtraTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun bluetoothHelpersWithShadowAdapter() {+        // Robolectric provides a shadow Bluetooth adapter.+        assertTrue(CableBluetooth.adapter(ctx) != null)+        assertTrue(CableBluetooth.isSupported(ctx))+    }++    @Test fun advertiserStartsWithShadowBluetooth() {+        val advertiser = CableAdvertiser(ctx)+        assertTrue(advertiser.isAvailable)+        // Robolectric's shadow LE advertiser accepts the advert without+        // invoking the callback synchronously; starting must not throw.+        advertiser.start(byteArrayOf(1, 2, 3)) { }+        advertiser.stop()+        // uuid16 masks to 16 bits and expands into the Bluetooth base UUID.+        assertEquals(+            "0000fde2-0000-1000-8000-00805f9b34fb",+            CableAdvertiser.uuid16(0x1FDE2).toString(),+        )+        assertEquals(+            "00000000-0000-1000-8000-00805f9b34fb",+            CableAdvertiser.uuid16(0).toString(),+        )+    }++    @Test fun createCredentialWithPresenceAndVerificationOff() = runBlocking {+        val store = FakePasskeyStore()+        val created = WebAuthnAuthenticator.createCredential(+            rpId = "example.com",+            rpName = "Example",+            userId = byteArrayOf(1, 2),+            userName = "alice",+            userDisplayName = "Alice",+            aaguid = ByteArray(16) { 0x0A },+            store = store,+            userPresent = false,+            userVerified = false,+        )+        // AT plus the default backup flags, with UP/UV cleared (offset 32).+        assertEquals(0x40 or 0x08 or 0x10, created.authenticatorData[32].toInt() and 0xFF)+        assertEquals(listOf(0x0A.toByte()), created.authenticatorData.copyOfRange(37, 38).toList())+        assertEquals(1, store.store.size)++        // Signing with userPresent = false clears UP but still bumps the counter.+        val assertion = WebAuthnAuthenticator.signAssertion(+            passkey = store.store.single(),+            clientDataHash = ByteArray(32) { 0x11 },+            store = store,+            userPresent = false,+            userVerified = true,+        )+        assertEquals(0x04 or 0x08 or 0x10, assertion.authenticatorData[32].toInt() and 0xFF)+        assertEquals(1, assertion.newSignCount)+        assertEquals(1, store.store.single().signCount)+    }++    @Test fun assertionForPasskeyWithNonBase64CredentialIdStillSigns() = runBlocking {+        // Through the CTAP processor: a stored credential id that is not valid+        // base64url is echoed back as an empty credential descriptor, not a crash.+        val kp = java.security.KeyPairGenerator.getInstance("EC").apply {+            initialize(java.security.spec.ECGenParameterSpec("secp256r1"))+        }.generateKeyPair()+        val pk = Passkey(+            id = 1, rpId = "example.com", credentialId = "!!!not-b64!!!",+            userId = "dXNlcg", userName = "alice", privateKeyBytes = kp.private.encoded,+            signCount = 0, syncId = "pk-bad",+        )+        val store = FakePasskeyStore(listOf(pk))+        val request = com.vayunmathur.passwords.domain.Cbor.encode(+            linkedMapOf<Any, Any>(1L to "example.com", 2L to ByteArray(32) { 0x22 }),+        )+        val response = CtapProcessor(store, userVerified = true)+            .process(byteArrayOf(Ctap.CMD_GET_ASSERTION.toByte()) + request)+        assertEquals(Ctap.OK.toByte(), response[0])+        val map = CborReader.decode(response.copyOfRange(1, response.size)) as Map<*, *>+        val cred = map[1L] as Map<*, *>+        assertEquals(0, (cred["id"] as ByteArray).size)+        assertEquals(1, store.store.single().signCount)+        assertTrue(response.size > 40)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/EntryMapperExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/EntryMapperExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/EntryMapperExtraTest.ktnew file mode 100644index 0000000000..32255730f1Binary files /dev/null and b/passwords/src/test/java/com/vayunmathur/passwords/sync/EntryMapperExtraTest.kt differ
passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineExtraTest.ktnew file mode 100644index 0000000000..979cb0ae73--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineExtraTest.kt@@ -0,0 +1,267 @@+package com.vayunmathur.passwords.sync++import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.PasskeyDao+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordDao+import com.vayunmathur.passwords.data.SyncSnapshot+import com.vayunmathur.passwords.data.SyncSnapshotDao+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import java.io.FileNotFoundException+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++private const val PW = "vault-pw"++class KdbxSyncEngineExtraTest {++    @Test fun emptyRemoteFileIsTreatedAsEmptyVaultAndPushed() = runBlocking {+        val h = Harness(passwords = listOf(pw(1, "A", updatedAt = 100)))+        h.document.bytes = ByteArray(0)+        val result = h.engine.sync(h.document, PW)+        assertEquals(KdbxSyncResult.Success(1, 0, 0, 0), result)+        assertEquals(1, h.document.writes)+        assertEquals("A", h.remoteEntries().single()["Title"])+    }++    @Test fun encodeFailureReturnsErrorWithoutWritingOrMutating() = runBlocking {+        val h = Harness(passwords = listOf(pw(1, "A", updatedAt = 100)))+        h.codec.failWrite = true+        val result = h.engine.sync(h.document, PW)+        assertEquals(KdbxSyncResult.Error("Failed to encode KDBX"), result)+        assertEquals(0, h.document.writes)+        assertEquals(1, h.pwDao.store.size)+        assertTrue(h.snapshotDao.store.isEmpty())+    }++    @Test fun verifyMismatchReturnsVerifyFailedWithoutWriting() = runBlocking {+        val h = Harness(passwords = listOf(pw(1, "A", updatedAt = 100)))+        h.codec.corruptVerify = true+        val result = h.engine.sync(h.document, PW)+        assertEquals(KdbxSyncResult.VerifyFailed, result)+        assertEquals(0, h.document.writes)+        assertTrue(h.snapshotDao.store.isEmpty())+    }++    @Test fun documentWriteIOExceptionReturnsError() = runBlocking {+        val h = Harness(passwords = listOf(pw(1, "A", updatedAt = 100)))+        h.document.writeFailsWith = IOException("disk full")+        val result = h.engine.sync(h.document, PW)+        assertEquals(KdbxSyncResult.Error("disk full"), result)+        assertTrue(h.snapshotDao.store.isEmpty())+    }++    @Test fun documentReadIOExceptionReturnsErrorWithMessage() = runBlocking {+        val h = Harness(passwords = listOf(pw(1, "A", updatedAt = 100)))+        h.document.readFailsWith = IOException("cloud unavailable")+        val result = h.engine.sync(h.document, PW)+        assertEquals(KdbxSyncResult.Error("cloud unavailable"), result)+        assertEquals(1, h.pwDao.store.size)+    }++    @Test fun backupCallbackReceivesPreviousBytesOnlyWhenRewriting() = runBlocking {+        val h = Harness(passwords = listOf(pw(1, "A", updatedAt = 100)))+        h.sync()+        val previous = assertNotNull(h.document.bytes)+        var backedUp: ByteArray? = null+        h.pwDao.store[0] = h.pwDao.store[0].copy(password = "changed", updatedAt = 5000)+        val result = h.engine.sync(h.document, PW, onBackup = { backedUp = it })+        assertTrue(result is KdbxSyncResult.Success)+        assertEquals(previous.toList(), backedUp!!.toList())+    }++    @Test fun blankSyncIdLocalRowGetsFreshIdentityAndIsPersisted() = runBlocking {+        val blank = Password(id = 5, name = "Legacy", username = "u", password = "p", syncId = "", updatedAt = 42)+        val h = Harness(passwords = listOf(blank))+        val result = h.engine.sync(h.document, PW)+        assertEquals(KdbxSyncResult.Success(1, 0, 0, 0), result)+        val stored = h.pwDao.store.single()+        assertTrue(stored.syncId.isNotBlank())+        assertEquals(32, stored.syncId.length)+        assertEquals(stored.syncId, h.remoteEntries().single()[EntryMapper.FIELD_SYNC_ID])+        assertEquals(stored.syncId, h.snapshotDao.store.keys.single())+    }++    @Test fun duplicateRemoteSyncIdsAreNotDropped() = runBlocking {+        val entry = EntryMapper.toFields(pw(0, "First", syncId = "dup", updatedAt = 100))+        val dupe = entry + ("Password" to "second-copy")+        val h = Harness(remote = listOf(entry, dupe))+        val result = h.engine.sync(h.document, PW)+        assertTrue(result is KdbxSyncResult.Success, "got $result")+        // Both rows survive locally: the duplicate is adopted under a fresh identity.+        assertEquals(2, h.pwDao.store.size)+        assertEquals(setOf("First"), h.pwDao.store.map { it.name }.toSet())+        assertEquals(2, h.pwDao.store.map { it.syncId }.distinct().size)+    }++    @Test fun foreignExtraFieldsSurviveALocalWin() = runBlocking {+        val h = Harness(passwords = listOf(pw(1, "A", updatedAt = 100)))+        h.sync()+        h.editRemote { it + mapOf("Tags" to "work,important", "Custom" to "keep-me") }+        h.pwDao.store[0] = h.pwDao.store[0].copy(password = "newer", updatedAt = 9000)+        val result = h.engine.sync(h.document, PW)+        assertEquals(1, (result as KdbxSyncResult.Success).pushed)+        val remote = h.remoteEntries().single()+        assertEquals("newer", remote["Password"])+        assertEquals("work,important", remote["Tags"])+        assertEquals("keep-me", remote["Custom"])+    }++    @Test fun passkeyPulledFromRemoteAndDeletedByTombstone() = runBlocking {+        val pk = Passkey(+            id = 0, rpId = "example.com", rpName = "Example", credentialId = "cred-x",+            userId = "uid", userName = "alice", privateKeyBytes = byteArrayOf(9, 8),+            creationTime = 11, lastUsedTime = 22, signCount = 3, syncId = "pk-r", updatedAt = 700,+        )+        val h = Harness(remote = listOf(EntryMapper.toFields(pk)))+        assertEquals(KdbxSyncResult.Success(0, 1, 0, 0), h.engine.sync(h.document, PW))+        val stored = h.pkDao.store.single()+        assertEquals("cred-x", stored.credentialId)+        assertEquals(listOf(9.toByte(), 8.toByte()), stored.privateKeyBytes.toList())+        assertEquals(700L, stored.updatedAt)++        h.setRemote(+            listOf(+                mapOf(+                    EntryMapper.FIELD_SYNC_ID to "pk-r",+                    EntryMapper.FIELD_TYPE to "tombstone",+                    EntryMapper.FIELD_TOMBSTONE to EntryMapper.TOMBSTONE_VALUE,+                    EntryMapper.FIELD_MODIFIED to "800",+                ),+            ),+        )+        val deleted = h.engine.sync(h.document, PW)+        assertEquals(1, (deleted as KdbxSyncResult.Success).deletedLocal)+        assertTrue(h.pkDao.store.isEmpty())+    }++    @Test fun localOnlyPasskeyIsPushedWithAllKpexFields() = runBlocking {+        val pk = Passkey(+            id = 3, rpId = "acme.example", rpName = "Acme", credentialId = "c1",+            userId = "u1", userName = "bob", userDisplayName = "Bob B",+            privateKeyBytes = byteArrayOf(1), creationTime = 5, lastUsedTime = 6,+            signCount = 7, linkedPasswordSyncId = "sync-1", syncId = "pk-l", updatedAt = 123,+        )+        val h = Harness(passkeys = listOf(pk))+        assertEquals(KdbxSyncResult.Success(1, 0, 0, 0), h.engine.sync(h.document, PW))+        val remote = h.remoteEntries().single()+        assertEquals("c1", remote["KPEX_PASSKEY_CREDENTIAL_ID"])+        assertEquals("acme.example", remote["KPEX_PASSKEY_RELYING_PARTY"])+        assertEquals("7", remote["_SignCount"])+        assertEquals("sync-1", remote["_LinkedPassword"])+    }++    // -- harness (mirrors KdbxSyncEngineTest's fakes, plus failure knobs) --++    private fun pw(id: Long, name: String, syncId: String = "sync-$id", updatedAt: Long) =+        Password(id = id, name = name, username = "u-$name", password = "p", syncId = syncId, updatedAt = updatedAt)++    private class Harness(+        passwords: List<Password> = emptyList(),+        passkeys: List<Passkey> = emptyList(),+        remote: List<Map<String, String>> = emptyList(),+    ) {+        val codec = FakeCodec()+        val pwDao = FakePwDao(passwords)+        val pkDao = FakePkDao(passkeys)+        val snapshotDao = FakeSnapshotDao()+        val document = FakeDocument(codec.write(PW, remote))+        val engine get() = KdbxSyncEngine(pwDao, pkDao, snapshotDao, codec)+        suspend fun sync() = engine.sync(document, PW)+        fun remoteEntries(): List<Map<String, String>> = codec.read(PW, assertNotNull(document.bytes))!!+        fun setRemote(entries: List<Map<String, String>>) { document.bytes = codec.write(PW, entries) }+        fun editRemote(transform: (Map<String, String>) -> Map<String, String>) =+            setRemote(remoteEntries().map(transform))+    }++    private class FakeCodec : KdbxCodec {+        private val vaults = mutableMapOf<String, List<Map<String, String>>>()+        private var counter = 0+        var failWrite = false+        var corruptVerify = false+        override fun read(password: String, bytes: ByteArray): List<Map<String, String>>? {+            if (password != PW) return null+            val found = vaults[String(bytes)] ?: return null+            return if (corruptVerify) found + mapOf("Title" to "phantom") else found+        }+        override fun write(password: String, entries: List<Map<String, String>>): ByteArray? {+            if (failWrite) return null+            val handle = "vault-${counter++}"+            vaults[handle] = entries.map { it.toMap() }+            return handle.toByteArray()+        }+    }++    private class FakeDocument(var bytes: ByteArray?) : KdbxDocument {+        var writes = 0+        var readFailsWith: IOException? = null+        var writeFailsWith: IOException? = null+        override fun read(): ByteArray {+            readFailsWith?.let { throw it }+            return bytes ?: throw FileNotFoundException("no document")+        }+        override fun write(bytes: ByteArray) {+            writeFailsWith?.let { throw it }+            this.bytes = bytes+            writes+++        }+    }++    private class FakePwDao(initial: List<Password>) : PasswordDao() {+        val store = initial.toMutableList()+        private var nextId = (initial.maxOfOrNull { it.id } ?: 0L) + 1+        override fun getAllFlow(): Flow<List<Password>> = flowOf(store.toList())+        override suspend fun getAll(): List<Password> = store.toList()+        override fun getByIdFlow(id: Long): Flow<Password?> = flowOf(store.firstOrNull { it.id == id })+        override suspend fun getById(id: Long): Password? = store.firstOrNull { it.id == id }+        override suspend fun getBySyncId(syncId: String): Password? = store.firstOrNull { it.syncId == syncId }+        override suspend fun getUpdatedSince(since: Long): List<Password> = store.filter { it.updatedAt > since }+        override suspend fun upsertRaw(value: Password): Long {+            val row = if (value.id == 0L) value.copy(id = nextId++) else value+            val i = store.indexOfFirst { it.id == row.id }+            if (i >= 0) store[i] = row else store.add(row)+            return row.id+        }+        override suspend fun delete(value: Password): Int = if (store.removeAll { it.id == value.id }) 1 else 0+        override suspend fun deleteBySyncId(syncId: String): Int =+            if (store.removeAll { it.syncId == syncId }) 1 else 0+        override suspend fun deleteAll() = store.clear()+    }++    private class FakePkDao(initial: List<Passkey>) : PasskeyDao() {+        val store = initial.toMutableList()+        private var nextId = (initial.maxOfOrNull { it.id } ?: 0L) + 1+        override fun getAllFlow(): Flow<List<Passkey>> = flowOf(store.toList())+        override suspend fun getAll(): List<Passkey> = store.toList()+        override suspend fun getByRpId(rpId: String): List<Passkey> = store.filter { it.rpId == rpId }+        override suspend fun getByCredentialId(credentialId: String): Passkey? =+            store.firstOrNull { it.credentialId == credentialId }+        override suspend fun getBySyncId(syncId: String): Passkey? = store.firstOrNull { it.syncId == syncId }+        override suspend fun getUpdatedSince(since: Long): List<Passkey> = store.filter { it.updatedAt > since }+        override suspend fun upsertRaw(passkey: Passkey): Long {+            val row = if (passkey.id == 0L) passkey.copy(id = nextId++) else passkey+            val i = store.indexOfFirst { it.id == row.id }+            if (i >= 0) store[i] = row else store.add(row)+            return row.id+        }+        override suspend fun delete(passkey: Passkey): Int =+            if (store.removeAll { it.id == passkey.id }) 1 else 0+        override suspend fun deleteBySyncId(syncId: String): Int =+            if (store.removeAll { it.syncId == syncId }) 1 else 0+        override suspend fun deleteAll() = store.clear()+    }++    private class FakeSnapshotDao : SyncSnapshotDao {+        val store = mutableMapOf<String, SyncSnapshot>()+        override suspend fun getAll(): List<SyncSnapshot> = store.values.toList()+        override suspend fun upsert(snapshot: SyncSnapshot) { store[snapshot.syncId] = snapshot }+        override suspend fun deleteBySyncId(syncId: String) { store.remove(syncId) }+        override suspend fun deleteByKind(kind: String) { store.entries.removeAll { it.value.kind == kind } }+        override suspend fun deleteAll() = store.clear()+    }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/NativeKdbxCodecExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/NativeKdbxCodecExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/NativeKdbxCodecExtraTest.ktnew file mode 100644index 0000000000..0824c52611--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/NativeKdbxCodecExtraTest.kt@@ -0,0 +1,42 @@+package com.vayunmathur.passwords.sync++import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class NativeKdbxCodecExtraTest {++    @Test fun specialCharacterEntriesRoundTrip() {+        val entries = listOf(+            mapOf("Title" to "Git Hub (work) #1", "Password" to "p@ss:w0rd!"),+            mapOf("Title" to "Café", "UserName" to "rené", "Password" to "päss"),+        )+        val bytes = NativeKdbxCodec.write("vault-pw", entries)+        assertNotNull(bytes)+        val restored = NativeKdbxCodec.read("vault-pw", bytes)+        assertNotNull(restored)+        assertEquals(2, restored.size)+        assertEquals("p@ss:w0rd!", restored.first { it["Title"] == "Git Hub (work) #1" }["Password"])+        assertEquals("päss", restored.first { it["Title"] == "Café" }["Password"])+    }++    @Test fun emptyVaultRoundTrips() {+        val bytes = NativeKdbxCodec.write("vault-pw", emptyList())+        assertNotNull(bytes)+        assertEquals(0, NativeKdbxCodec.read("vault-pw", bytes)!!.size)+    }++    @Test fun manyEntriesRoundTripWithSyncFields() {+        val entries = (1..25).map { i ->+            mapOf("Title" to "Entry $i", "UserName" to "user$i", "Password" to "pw$i", "_SyncId" to "sync-$i")+        }+        val restored = NativeKdbxCodec.read("vault-pw", NativeKdbxCodec.write("vault-pw", entries)!!)!!+        assertEquals(25, restored.size)+        assertEquals("user25", restored.first { it["_SyncId"] == "sync-25" }["UserName"])+    }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderExtraTest.ktnew file mode 100644index 0000000000..fb492be288--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderExtraTest.kt@@ -0,0 +1,185 @@+package com.vayunmathur.passwords.sync++import android.content.ContentValues+import android.net.Uri+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class RelayProviderExtraTest {++    private val provider: RelayPasswordProvider by lazy {+        Robolectric.buildContentProvider(RelayPasswordProvider::class.java)+            .create(RelayPasswordProvider.AUTHORITY).get()+    }++    private fun uri(path: String) = Uri.parse("content://${RelayPasswordProvider.AUTHORITY}/$path")++    @Test fun onCreateAndGetTypeForEveryRoute() {+        assertTrue(provider.onCreate())+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.password",+            provider.getType(uri("vault/v/passwords")),+        )+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.password",+            provider.getType(uri("vault/v/passwords/querySince")),+        )+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.passkey",+            provider.getType(uri("vault/v/passkeys")),+        )+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.passkey",+            provider.getType(uri("vault/v/passkeys/querySince")),+        )+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.snapshot",+            provider.getType(uri("vault/v/snapshots")),+        )+        assertNull(provider.getType(uri("vault/v/unknown")))+        assertNull(provider.getType(uri("elsewhere/passwords")))+    }++    @Test fun unknownRoutesAreInert() {+        val values = ContentValues().apply { put(RelayPasswordProvider.COL_PAYLOAD_JSON, "{}") }+        assertNull(provider.query(uri("vault/v/unknown"), null, null, null, null))+        assertNull(provider.insert(uri("vault/v/unknown"), values))+        assertEquals(0, provider.update(uri("vault/v/unknown"), values, null, null))+        assertEquals(0, provider.delete(uri("vault/v/unknown"), null, null))+    }++    @Test fun nullAndMalformedPayloadsAreRejectedWithoutTouchingVault() {+        val passwords = uri("vault/v/passwords")+        assertNull(provider.insert(passwords, null))+        assertEquals(0, provider.update(passwords, null, null, null))+        // No payloadJson column at all.+        assertNull(provider.insert(passwords, ContentValues()))+        // Malformed JSON is not an envelope.+        val malformed = ContentValues().apply {+            put(RelayPasswordProvider.COL_PAYLOAD_JSON, "{not json")+        }+        assertNull(provider.insert(passwords, malformed))+        assertEquals(0, provider.update(passwords, malformed, null, null))+        assertNull(provider.insert(uri("vault/v/passkeys"), malformed))+        // Well-formed JSON whose uid is blank is rejected as foreign/corrupt.+        val blankUid = ContentValues().apply {+            put(RelayPasswordProvider.COL_PAYLOAD_JSON, """{"uid":"","name":"Ghost"}""")+        }+        assertNull(provider.insert(passwords, blankUid))+        // Snapshot insert without a syncId is rejected.+        assertNull(provider.insert(uri("vault/v/snapshots"), ContentValues()))+        assertEquals(+            0,+            provider.update(+                uri("vault/v/snapshots"),+                ContentValues().apply { put("kind", "password") },+                null, null,+            ),+        )+    }++    @Test fun envelopeDefaultsAndFullFieldMapping() {+        val defaults = RelayPasswordJson()+        assertEquals("", defaults.uid)+        assertEquals(false, defaults.isPasskey)+        assertEquals(false, defaults.deleted)+        assertEquals(emptyList(), defaults.websites)+        assertNull(defaults.totpSecret)+        assertNull(defaults.linkedPasswordSyncId)++        val full = RelayPasswordJson(+            uid = "u-9", name = "Mail", username = "alice", email = "[email protected]",+            password = "pw", note = "note", totpSecret = "SEED",+            websites = listOf("mail.example", "webmail.example"),+            deleted = true, updatedAt = 4242,+        )+        val asPassword = full.toPassword(id = 77)+        assertEquals(77L, asPassword.id)+        assertEquals("u-9", asPassword.syncId)+        assertEquals(4242L, asPassword.updatedAt)+        assertEquals(listOf("mail.example", "webmail.example"), asPassword.websites)+        assertEquals("SEED", asPassword.totpSecret)+        // toRelayJson of a Password never marks passkey/deleted: those are transport-only.+        val back = asPassword.toRelayJson()+        assertEquals(false, back.isPasskey)+        assertEquals(false, back.deleted)+        assertEquals(full.name, back.name)+        assertNotEquals(full.hashCode(), RelayPasswordJson(uid = "other").hashCode())+    }++    @Test fun passkeyEnvelopeAndPayloadCarriersPreserveEveryField() {+        val pk = Passkey(+            id = 12, rpId = "login.example", rpName = "Login", credentialId = "cred-9",+            userId = "uid-1", userName = "carol", userDisplayName = "Carol C",+            privateKeyBytes = byteArrayOf(3, 1, 4), creationTime = 100, lastUsedTime = 200,+            signCount = 9, linkedPasswordSyncId = "sync-pw", syncId = "pk-9", updatedAt = 300,+        )+        val payload = PasswordPasskeyPayload.fromPasskey(pk)+        val restoredPayload = payload.toPasskey()+        assertEquals(pk.rpId, restoredPayload.rpId)+        assertEquals(pk.credentialId, restoredPayload.credentialId)+        assertEquals(listOf(3.toByte(), 1.toByte(), 4.toByte()), restoredPayload.privateKeyBytes.toList())+        assertEquals("sync-pw", restoredPayload.linkedPasswordSyncId)+        assertEquals(9, restoredPayload.signCount)++        val relay = pk.toRelayJson()+        assertEquals(payload.privateKeyBase64, relay.privateKeyB64)+        val restored = relay.toPasskey(id = 99)+        assertEquals(99L, restored.id)+        assertEquals(100L, restored.creationTime)+        assertEquals(200L, restored.lastUsedTime)+        assertEquals("Carol C", restored.userDisplayName)++        // A payload with garbage base64 decodes to an empty key rather than throwing.+        val garbage = PasswordPasskeyPayload(privateKeyBase64 = "%%%")+        assertEquals(0, garbage.toPasskey().privateKeyBytes.size)+        // Serialised envelope round-trips through the provider's JSON shape.+        val json = Json { ignoreUnknownKeys = true }+        val text = json.encodeToString(relay)+        assertEquals(relay, json.decodeFromString(RelayPasswordJson.serializer(), text))+        assertTrue(text.contains("\"uid\"

Diff truncated.