Modern Apps git

← Modern-Apps.git

securemail: trust, claim, migration and intent tests

Commit
745ccd9724bbe61a0b749159062a61e6a4bfd4c5
Author
Vayun Mathur <[email protected]>
When
2026-11-17 02:10 UTC (19 days ago)
Parents
27fb2e9
Coverage top-up for :securemail (CI 428a82e90: 78.1%
INSTRUCTION). Local merged report before: 78.1% (21626/27698);
after: 80.3% (22251/27698).

- MailViewModelTrustClaimTest (5 tests): resolveTrust answers
  from the vault cache (addresses trimmed/lowercased, cached
  fingerprint carried), reports no-key for an address that
  cannot be looked up at all, and handles no recipients;
  claimAddress rejects malformed addresses and short
  passphrases synchronously, and a well-formed claim runs until
  the absent relay refuses it with the offline error.
- IdentitiesMigrationContextTest (2 tests): the context-level
  ensureMigrated/active, previously only exercised through the
  DAO-level core. With MailRepository seeded to an in-memory
  database (singleton reset and restored, the :clock pattern)
  and an in-memory AndroidKeyStore fake: migration is a no-op
  until an identity is configured AND a secret is stored, then
  backfills the primary exactly once and stays idempotent.
- MainActivityIntentTest (2 tests): SENDTO/SEND intents become
  the documented composer route (recipient, subject, body) and
  a plain intent leaves no pending route. MainActivity itself
  was at 0% before this.

Note: IdentitiesTest's detached-signature comparison is a
pre-existing second-boundary flake (two signatures compared
byte-for-byte); it passes in isolation and on re-run.

Verified: ./gradlew :securemail:testDevUnitTest
:securemail:createMergedCoverageReport green, 80.3%.

Diff

securemail/src/test/java/com/vayunmathur/securemail/FakeAndroidKeyStore.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/FakeAndroidKeyStore.kt b/securemail/src/test/java/com/vayunmathur/securemail/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..0bad97e138--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/FakeAndroidKeyStore.kt@@ -0,0 +1,97 @@+package com.vayunmathur.securemail++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStore+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Collections+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGenerator+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * Robolectric has no AndroidKeyStore provider, which otherwise blocks every+ * code path that opens the SQLCipher vault (PasswordRepository,+ * DatabaseHelper, KdbxPasswordHelper). Installing this JCA provider gives+ * tests a plain in-memory AES keystore with the same alias semantics; keys+ * never leave the test process.+ */+object FakeAndroidKeyStore {+    private val keys = mutableMapOf<String, SecretKey>()++    fun install() {+        if (Security.getProvider("AndroidKeyStore") == null) {+            Security.addProvider(FakeProvider())+        }+    }++    fun put(alias: String, key: SecretKey) {+        keys[alias] = key+    }++    fun get(alias: String): SecretKey? = keys[alias]++    fun remove(alias: String) {+        keys.remove(alias)+    }++    fun contains(alias: String): Boolean = keys.containsKey(alias)++    fun aliases(): List<String> = keys.keys.toList()++    class FakeProvider : Provider("AndroidKeyStore", 1.0, "in-memory test keystore") {+        init {+            put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+            put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+        }+    }++    class FakeKeyStoreSpi : KeyStoreSpi() {+        override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+        override fun engineContainsAlias(alias: String) = contains(alias)+        override fun engineDeleteEntry(alias: String) = remove(alias)+        override fun engineGetKey(alias: String, password: CharArray?): Key? = get(alias)+        override fun engineIsKeyEntry(alias: String) = contains(alias)+        override fun engineAliases(): Enumeration<String> = Collections.enumeration(aliases())+        override fun engineSize() = aliases().size+        override fun engineGetCertificate(alias: String): Certificate? = null+        override fun engineGetCertificateAlias(cert: Certificate) = null+        override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+        override fun engineGetCreationDate(alias: String) = Date()+        override fun engineIsCertificateEntry(alias: String) = false+        override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+        override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+        override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+            if (key is SecretKey) put(alias, key)+        }+        override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) = Unit+    }++    class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+        private var alias: String = "test-key"++        override fun engineInit(random: SecureRandom) = Unit+        override fun engineInit(keysize: Int, random: SecureRandom) = Unit+        override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom) {+            if (params is KeyGenParameterSpec) alias = params.keystoreAlias+        }++        override fun engineGenerateKey(): SecretKey {+            val bytes = ByteArray(32)+            SecureRandom().nextBytes(bytes)+            return SecretKeySpec(bytes, "AES").also { put(alias, it) }+        }+    }++    /** Convenience for tests that obtain a generator through JCA. */+    fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
securemail/src/test/java/com/vayunmathur/securemail/MainActivityIntentTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/MainActivityIntentTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/MainActivityIntentTest.ktnew file mode 100644index 0000000000..43f68c5d75--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/MainActivityIntentTest.kt@@ -0,0 +1,60 @@+package com.vayunmathur.securemail++import android.content.Intent+import android.net.Uri+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * MainActivity's intent-to-route mapping, which had never run in a test:+ * SENDTO/SEND intents from other apps must land as a seeded composer+ * route, and plain launches must not invent one.+ */+@RunWith(RobolectricTestRunner::class)+class MainActivityIntentTest {++    @BeforeTest fun setUp() = FakeAndroidKeyStore.install()++    @AfterTest fun tearDown() {+        IntentState.navigationRoute = null+    }++    @Test fun `sendto intent becomes a composer route addressed to the recipient`() {+        IntentState.navigationRoute = null+        val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:[email protected]")).apply {+            putExtra(Intent.EXTRA_SUBJECT, "Hello Ada")+            putExtra(Intent.EXTRA_TEXT, "Body text")+        }+        Robolectric.buildActivity(MainActivity::class.java, intent).create()+        assertEquals(+            Route.Composer(to = "[email protected]", subject = "Hello Ada", body = "Body text"),+            IntentState.navigationRoute,+        )+    }++    @Test fun `send intent and plain launch map as documented`() {+        IntentState.navigationRoute = null+        val share = Intent(Intent.ACTION_SEND).apply {+            putExtra(Intent.EXTRA_TEXT, "shared words")+            type = "text/plain"+        }+        val controller = Robolectric.buildActivity(MainActivity::class.java, share)+        controller.create()+        assertEquals(+            Route.Composer(to = "", subject = "", body = "shared words"),+            IntentState.navigationRoute,+        )++        // A later plain intent replaces the pending route with nothing to do.+        IntentState.navigationRoute = null+        controller.newIntent(Intent(Intent.ACTION_MAIN))+        assertNull(IntentState.navigationRoute)+        controller.destroy()+    }+}
securemail/src/test/java/com/vayunmathur/securemail/data/IdentitiesMigrationContextTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/data/IdentitiesMigrationContextTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/data/IdentitiesMigrationContextTest.ktnew file mode 100644index 0000000000..ed61b8fa8b--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/data/IdentitiesMigrationContextTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.securemail.data++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.databases+import com.vayunmathur.securemail.FakeAndroidKeyStore+import com.vayunmathur.securemail.platform.crypto.KeyManager+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The context-level [Identities.ensureMigrated] / [Identities.active],+ * which earlier suites only exercised through the DAO-level core: the+ * production overloads read MailConfig, the KeyManager secret and the+ * process-wide MailRepository. Seeding the shared database cache with+ * an in-memory database and resetting the repository singleton (both+ * restored afterwards) plus the in-memory keystore fake makes the full+ * migration run on the host.+ */+@RunWith(RobolectricTestRunner::class)+class IdentitiesMigrationContextTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val repo: MailRepository get() = MailRepository.get(app)++    @BeforeTest fun setUp() {+        FakeAndroidKeyStore.install()+        resetRepositorySingleton()+        synchronized(databases) {+            runCatching { databases[MailDatabase::class]?.close() }+            databases[MailDatabase::class] =+                Room.inMemoryDatabaseBuilder(app, MailDatabase::class.java)+                    .allowMainThreadQueries().build()+        }+        runBlocking {+            repo.identityDao().deleteAll()+            MailConfig(app).setIdentity("", "", "")+        }+        KeyManager(app).clear()+    }++    @AfterTest fun tearDown() {+        resetRepositorySingleton()+        synchronized(databases) {+            runCatching { databases[MailDatabase::class]?.close() }+            databases.remove(MailDatabase::class)+        }+    }++    private fun resetRepositorySingleton() {+        runCatching {+            val field = MailRepository::class.java.getDeclaredField("instance")+            field.isAccessible = true+            field.set(null, null)+        }+    }++    @Test fun `migration is a no-op until configured with a stored secret`() = runBlocking {+        // Nothing configured at all.+        Identities.ensureMigrated(app)+        assertEquals(0, repo.identityDao().count())++        // Configured identity, but the keystore holds no secret yet.+        MailConfig(app).setIdentity("[email protected]", "pub-armor", "AABBCC")+        Identities.ensureMigrated(app)+        assertEquals(0, repo.identityDao().count())+        assertTrue(Identities.active(app).isEmpty())+    }++    @Test fun `migration backfills the primary identity once and stays idempotent`() = runBlocking {+        MailConfig(app).setIdentity("[email protected]", "pub-armor", "AABBCC")+        KeyManager(app).storeSecretArmor("secret-armor")++        Identities.ensureMigrated(app)+        assertEquals(1, repo.identityDao().count())+        val active = Identities.active(app)+        assertEquals(1, active.size)+        val primary = active.single()+        assertEquals("[email protected]", primary.address)+        assertEquals("pub-armor", primary.publicArmor)+        assertEquals("AABBCC", primary.fingerprintHex)+        assertEquals("secret-armor", primary.secretArmor)+        assertTrue(primary.isPrimary)++        // A second migration with changed config must not duplicate or+        // overwrite the backfilled row.+        MailConfig(app).setIdentity("[email protected]", "x", "y")+        Identities.ensureMigrated(app)+        assertEquals(1, repo.identityDao().count())+        assertEquals("[email protected]", Identities.active(app).single().address)+        assertEquals("[email protected]", MailConfig(app).settings.first().address)+    }+}
securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTrustClaimTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTrustClaimTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTrustClaimTest.ktnew file mode 100644index 0000000000..df837c30f2--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTrustClaimTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.securemail.platform++import android.app.Application+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.securemail.data.CachedKey+import com.vayunmathur.securemail.domain.mail.KeyLookupPolicy+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Trust resolution and address claiming in [MailViewModel], which the+ * report named and earlier suites only reached up to their early+ * returns: the cached-key trust path, the no-key outcome, and a+ * well-formed claim that runs until the (absent) relay refuses it.+ */+@RunWith(RobolectricTestRunner::class)+class MailViewModelTrustClaimTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private fun vm(store: FakeMailStore = FakeMailStore()) = MailViewModel(app, store)++    private fun await(description: String, timeoutMs: Long = 40_000, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            shadowOf(Looper.getMainLooper()).idle()+            if (condition()) return+            Thread.sleep(20)+        }+        assertTrue(condition(), "timed out waiting for: $description")+    }++    @Test fun `resolveTrust answers from the vault cache without any lookup`() = runBlocking {+        val store = FakeMailStore()+        store.keys.upsert(+            CachedKey(+                address = "[email protected]", armoredPublic = "armor",+                fingerprintHex = "AABBCCDD", source = "Cached", updatedMillis = 1L,+            ),+        )+        val trust = vm(store).resolveTrust(listOf("  [email protected] ", "[email protected]"))+        assertEquals(2, trust.size)+        for (entry in trust) {+            assertEquals("[email protected]", entry.address, "addresses are trimmed and lowercased")+            assertTrue(entry.hasKey)+            assertEquals(KeyLookupPolicy.KeySource.Cached, entry.source)+            assertEquals("AABBCCDD", entry.fingerprintHex)+        }+    }++    @Test fun `resolveTrust reports no key for an address that cannot be looked up`() = runBlocking {+        // No '@' at all: no directory or WKD lookup is even possible, and no+        // network is touched - the answer is a plain no-key.+        val trust = vm().resolveTrust(listOf("not-an-address"))+        assertEquals(1, trust.size)+        assertFalse(trust.single().hasKey)+        assertEquals(KeyLookupPolicy.KeySource.None, trust.single().source)+        assertEquals("not-an-address", trust.single().address)+    }++    @Test fun `resolveTrust handles an empty recipient list`() = runBlocking {+        assertTrue(vm().resolveTrust(emptyList()).isEmpty())+    }++    @Test fun `claimAddress rejects malformed addresses and short passphrases synchronously`() {+        val viewModel = vm()+        viewModel.claimAddress("ab", "long-enough-passphrase")+        assertEquals(+            "Use 3–64 lowercase letters, digits, dots or dashes.",+            viewModel.state.error,+        )+        viewModel.claimAddress("good.name", "short")+        assertEquals("Use a passphrase of at least 8 characters.", viewModel.state.error)+        assertFalse(viewModel.state.busy, "a rejected claim must not start work")+    }++    @Test fun `claimAddress with a well-formed request fails at the offline relay`() {+        val viewModel = vm()+        viewModel.claimAddress("new.user", "long-enough-passphrase")+        assertTrue(viewModel.state.busy, "a well-formed claim starts work")+        // The relay never connects in a host test: after the relay wait the+        // claim surfaces the offline error instead of claiming anything.+        await("relay offline claim error") {+            viewModel.state.error?.contains("Relay offline") == true+        }+        assertFalse(viewModel.state.busy)+    }+}