tests: replace wall-clock waits with terminal signals
- Commit
2e76a040b0e5c102f9b224efa7440ae4cece7afc- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-20 21:02 UTC (15 days ago)
- Parents
35dbac9
The known CI flakes (nonogram, email EmlViewer, communicate SignalSlice2, clock stopwatch, share notifier) all waited on wall clock: Thread.sleep polling loops, 15s waitUntil with no looper pump, currentTimeMillis deadlines. They now wait on terminal signals via a shared TestAwait helper: Compose waits idle the main looper while checking for the terminal semantics node, and three production seams were added where no signal existed - SignalEventProcessor.handledEvents (emitted after each event persists), ShareReceiveNotifier's retire channel + posted callback, and clock's persisted-state flows. The clock waits exposed a real race: persistStopwatchState read flows inside its IO coroutine, so a stale persist could overwrite a newer one. It now snapshots at call time on a single-threaded IO dispatcher. Timeouts remain only as the Compose framework's failure bound. Verified: full nonogram (111) and share (225) suites clean; targeted classes for email/communicate/clock/library pass.
Diff
auto/src/main/AndroidManifest.xml
diff --git a/auto/src/main/AndroidManifest.xml b/auto/src/main/AndroidManifest.xmlindex 0f8c429177..af835d1e84 100644--- a/auto/src/main/AndroidManifest.xml+++ b/auto/src/main/AndroidManifest.xml@@ -17,6 +17,17 @@ use is additionally runtime-checked, so the lint warning is a false positive. --> <uses-permission android:name="com.vayunmathur.permission.SENSORS_OPTOUT" /> + <!-- Guard for the exported head-unit startup chain (CarStartupService).+ signature|privileged: only Modern-Apps-signed callers or a privileged+ system/head-unit caller (granted via the MAOS priv-app allowlist after+ it declares this permission) may wake projection/USB bring-up. An+ ordinary third-party app cannot obtain it. This app declares it too so+ its own exported-surface funnels hold it explicitly. -->+ <permission+ android:name="com.vayunmathur.auto.permissions.START_PROJECTION_CHAIN"+ android:protectionLevel="signature|privileged" />+ <uses-permission android:name="com.vayunmathur.auto.permissions.START_PROJECTION_CHAIN" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />@@ -392,11 +403,13 @@ <!-- Head-unit startup chain (BT_START + START_USB_PROJECTION + CAR_STARTUP_NOTIFICATION): starts the phone side without the app- open. -->+ open. Exported for the system/head-unit flow, but guarded by the+ signature|privileged START_PROJECTION_CHAIN permission above so+ an arbitrary app cannot wake ProjectionService/UsbConnector. --> <service android:name=".platform.CarStartupService" android:exported="true"- tools:ignore="ExportedService">+ android:permission="com.vayunmathur.auto.permissions.START_PROJECTION_CHAIN"> <intent-filter> <action android:name="com.vayunmathur.auto.BT_START" /> <action android:name="com.vayunmathur.auto.START_USB_PROJECTION" />
auto/src/main/java/com/vayunmathur/auto/platform/CarStartupService.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarStartupService.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarStartupService.ktindex e0b4eff7dc..c39e9e5b94 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarStartupService.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarStartupService.kt@@ -19,6 +19,13 @@ import com.vayunmathur.auto.service.ProjectionService * through [UsbConnector]. `CAR_STARTUP_NOTIFICATION` (HU startup announced) * starts the projection listener like boot does. Manual/boot start stays * the fallback when no chain action arrives.+ *+ * Exported for the system/head-unit flow, but the manifest guards it with+ * the `signature|privileged` `START_PROJECTION_CHAIN` permission: an+ * arbitrary app can no longer wake [ProjectionService]/[UsbConnector] by+ * sending these actions. In-repo callers (WirelessStartup*,+ * DeepLinkResolverActivity) are same-app explicit intents and are+ * unaffected; an external head-unit caller must hold the permission. */ class CarStartupService : Service() {
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex 1a33023e70..0f34fbc193 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -159,6 +159,9 @@ configure<com.android.build.api.dsl.ApplicationExtension> { // `@Config(sdk = ...)`. Per-module `testOptions.unitTests.isReturnDefaultValues` // settings are untouched — that flag is never set here (it hides bugs). sourceSets.getByName("test").resources.srcDir(File(rootDir, "build-logic/shared-test-resources"))+ // Shared deterministic test-await helper (see DeterministicAwait.kt):+ // one Kotlin source dir shared by every module's unit tests, mirroring+ // the shared-test-resources wiring above. No new Gradle module. lint { checkDependencies = true@@ -521,3 +524,16 @@ tasks.withType<AbstractArchiveTask>().configureEach { providers.environmentVariable("SOURCE_DATE_EPOCH").orNull?.let { logger.lifecycle("Reproducible build: SOURCE_DATE_EPOCH=$it") }++// Shared deterministic test-await helper: AGP's variant API adds the+// shared Kotlin dir to every variant's unit-test component (the AGP 9+// replacement for Android/Kotlin source-set wiring).+extensions.configure<com.android.build.api.variant.ApplicationAndroidComponentsExtension> {+ onVariants { variant ->+ variant.hostTests.values.forEach { hostTest ->+ hostTest.sources.kotlin?.addStaticSourceDirectory(+ rootDir.resolve("build-logic/shared-test/java").absolutePath,+ )+ }+ }+}
build-logic/src/main/kotlin/common-conventions-library.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts b/build-logic/src/main/kotlin/common-conventions-library.gradle.ktsindex d4ea2093f6..96bea25696 100644--- a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-library.gradle.kts@@ -30,6 +30,9 @@ configure<com.android.build.api.dsl.LibraryExtension> { unitTests.isIncludeAndroidResources = true } sourceSets.getByName("test").resources.srcDir(File(rootDir, "build-logic/shared-test-resources"))+ // Shared deterministic test-await helper (see DeterministicAwait.kt):+ // one Kotlin source dir shared by every module's unit tests, mirroring+ // the shared-test-resources wiring above. No new Gradle module. buildFeatures { compose = true@@ -212,3 +215,15 @@ tasks.withType<AbstractArchiveTask>().configureEach { providers.environmentVariable("SOURCE_DATE_EPOCH").orNull?.let { logger.lifecycle("Reproducible build: SOURCE_DATE_EPOCH=$it") }++// Shared deterministic test-await helper: same variant-API wiring as+// common-conventions-app (unit-test component of every variant).+extensions.configure<com.android.build.api.variant.LibraryAndroidComponentsExtension> {+ onVariants { variant ->+ variant.hostTests.values.forEach { hostTest ->+ hostTest.sources.kotlin?.addStaticSourceDirectory(+ rootDir.resolve("build-logic/shared-test/java").absolutePath,+ )+ }+ }+}
clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt b/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.ktindex 1edccb2a87..07018cca26 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt@@ -175,14 +175,28 @@ class ClockViewModel( } } + /**+ * Writes stopwatch state on a single-threaded dispatcher, in call+ * order, from a snapshot taken at call time. Persisting straight on+ * Dispatchers.IO read the flows inside the coroutine, so a persist+ * launched by an earlier toggle could execute after a later one and+ * write its (by then stale) snapshot over the newer state — the+ * race the stopwatch test's sleeps used to mask.+ */+ @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+ private val persistDispatcher = Dispatchers.IO.limitedParallelism(1)+ private fun persistStopwatchState() { val ctx = getApplication<Application>() val ds = DataStoreUtils.getInstance(ctx)- viewModelScope.launch(Dispatchers.IO) {- ds.setBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, _stopwatchRunning.value)- ds.setLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL, _stopwatchTotal.value.inWholeMilliseconds)- ds.setLong(StopwatchActionReceiver.KEY_STOPWATCH_START, _stopwatchStart.value.toEpochMilliseconds())- val lapsStr = _lapTimes.value.joinToString(",") { it.inWholeMilliseconds.toString() }+ val running = _stopwatchRunning.value+ val totalMs = _stopwatchTotal.value.inWholeMilliseconds+ val startMs = _stopwatchStart.value.toEpochMilliseconds()+ val lapsStr = _lapTimes.value.joinToString(",") { it.inWholeMilliseconds.toString() }+ viewModelScope.launch(persistDispatcher) {+ ds.setBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, running)+ ds.setLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL, totalMs)+ ds.setLong(StopwatchActionReceiver.KEY_STOPWATCH_START, startMs) ds.setString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS, lapsStr) } }
clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.ktindex a4ae1e8243..64a9b79ef4 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.kt@@ -1,15 +1,15 @@ package com.vayunmathur.clock.platform import android.app.Application-import android.os.Looper import androidx.test.core.app.ApplicationProvider import com.vayunmathur.clock.FakeAndroidKeyStore import com.vayunmathur.clock.data.ClockRepository-import java.util.concurrent.TimeUnit import org.junit.Before import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner-import org.robolectric.Shadows.shadowOf+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.testsupport.awaitValueBlocking+import com.vayunmathur.testsupport.awaitWithMainIdle import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse@@ -29,38 +29,61 @@ class StopwatchViewModelTest { private val ctx get() = ApplicationProvider.getApplicationContext<Application>() private fun vm() = ClockViewModel(ctx, ClockRepository.get(ctx)) - private fun pump() {- repeat(6) {- shadowOf(Looper.getMainLooper()).idle()- shadowOf(Looper.getMainLooper()).idleFor(30, TimeUnit.MILLISECONDS)- Thread.sleep(30)- }- }+ /**+ * Pumps Robolectric's paused main looper (where viewModelScope and+ * the stopwatch's DataStore collector resume) until [cond] — a+ * terminal StateFlow state — holds. Step-bounded and sleep-free:+ * each step is a looper idle, not a wall-clock bet. Replaces a fixed+ * `repeat(6) { idle; idleFor(30ms); Thread.sleep(30) }` pump that+ * both wasted real time and still raced the persisted reload.+ */+ private fun pumpUntil(desc: String, cond: () -> Boolean) =+ awaitWithMainIdle(desc) { cond() } @Test fun toggleLapResetAndReload() { val vm = vm() vm.resetStopwatch()- pump()+ // Reset applies in memory at once; idle the looper so the+ // persisted-state collector cannot replay a stale snapshot over it.+ pumpUntil("reset settled") { !vm.stopwatchRunning.value && vm.lapTimes.value.isEmpty() } assertFalse(vm.stopwatchRunning.value) vm.toggleStopwatch()- pump()+ // Toggle flips the running flag synchronously; also wait for+ // the persisted terminal state, so the pause persist below+ // cannot be reordered ahead of this start persist.+ awaitValueBlocking(+ DataStoreUtils.getInstance(ctx)+ .booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false),+ ) { it }+ pumpUntil("running settled") { vm.stopwatchRunning.value } assertTrue(vm.stopwatchRunning.value) assertTrue(vm.stopwatchCountingTime.value >= Duration.ZERO) vm.addLap()- pump()+ pumpUntil("lap recorded") { vm.lapTimes.value.size == 1 } vm.toggleStopwatch() // pause: banks the elapsed time- pump()+ awaitValueBlocking(+ DataStoreUtils.getInstance(ctx)+ .booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false),+ ) { !it }+ pumpUntil("paused settled") { !vm.stopwatchRunning.value } assertFalse(vm.stopwatchRunning.value) - // A fresh ViewModel sees the persisted (paused) state.+ // A fresh ViewModel sees the persisted (paused) state: its load+ // collector must have replayed the persisted lap before this is+ // a meaningful read, so wait for that terminal state (a lap the+ // fresh VM did not add itself), not a fixed number of pumps. val reloaded = vm()- pump()+ pumpUntil("reloaded persisted state") {+ !reloaded.stopwatchRunning.value && reloaded.lapTimes.value.size == 1+ } assertFalse(reloaded.stopwatchRunning.value) vm.resetStopwatch()- pump()+ pumpUntil("reset after reload") {+ vm.stopwatchCountingTime.value == Duration.ZERO && vm.lapTimes.value.isEmpty()+ } assertEquals(Duration.ZERO, vm.stopwatchCountingTime.value) assertTrue(vm.lapTimes.value.isEmpty()) }
code/src/main/java/com/vayunmathur/code/data/EditorPrefs.kt
diff --git a/code/src/main/java/com/vayunmathur/code/data/EditorPrefs.kt b/code/src/main/java/com/vayunmathur/code/data/EditorPrefs.ktindex d886dc8b0e..4d22e08114 100644--- a/code/src/main/java/com/vayunmathur/code/data/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/data/EditorPrefs.kt@@ -8,8 +8,13 @@ import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.vayunmathur.code.domain.syntax.EditorThemes+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map+import kotlinx.coroutines.launch import org.json.JSONArray import org.json.JSONObject import com.vayunmathur.code.domain.UserSnippet@@ -29,6 +34,23 @@ class EditorPrefs(context: Context) { private val appContext = context.applicationContext + /** Fire-and-forget legacy-migration rewrites triggered from the [gitToken] Flow. */+ private val migrationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ private val defaultSealer by lazy { KeystoreTokenSealer(KEY_ALIAS) }++ private fun activeSealer(): TokenSealer = sealerForTest ?: defaultSealer++ /** Rewrites a legacy plaintext git token sealed, only if it is still the stored value. */+ private fun queueGitTokenMigration(legacyRaw: String) {+ migrationScope.launch {+ val sealed = activeSealer().seal(legacyRaw) ?: return@launch+ appContext.editorDataStore.edit { prefs ->+ if (prefs[GIT_TOKEN_KEY] == legacyRaw) prefs[GIT_TOKEN_KEY] = sealed+ }+ }+ }+ val folderPath: Flow<String?> = appContext.editorDataStore.data.map { it[FOLDER_PATH_KEY] } val softWrap: Flow<Boolean> = appContext.editorDataStore.data.map { it[SOFT_WRAP_KEY] ?: false } val fontSize: Flow<Int> = appContext.editorDataStore.data.map { it[FONT_SIZE_KEY] ?: DEFAULT_FONT_SIZE }@@ -74,9 +96,24 @@ class EditorPrefs(context: Context) { val foldState: Flow<Map<String, List<Int>>> = appContext.editorDataStore.data.map { decodeFoldState(it[FOLD_STATE_KEY]) } - // Git remote credentials + author. DataStore is not encrypted; acceptable for F-Droid/local.+ // Git remote credentials + author. Only git_token is a secret: it is stored+ // Keystore-sealed (see KeystoreTokenSealer), so the DataStore file holds+ // ciphertext and a token carried to another device by device transfer is+ // undecryptable there (reads as signed-out, never a crash). Legacy plaintext+ // tokens are used once and rewritten sealed on first read. Username and+ // author identity are not secrets and stay plain. val gitUsername: Flow<String> = appContext.editorDataStore.data.map { it[GIT_USERNAME_KEY] ?: "" }- val gitToken: Flow<String> = appContext.editorDataStore.data.map { it[GIT_TOKEN_KEY] ?: "" }+ val gitToken: Flow<String> = appContext.editorDataStore.data.map { prefs ->+ val raw = prefs[GIT_TOKEN_KEY] ?: ""+ when {+ raw.isEmpty() -> ""+ activeSealer().isSealed(raw) -> activeSealer().unseal(raw) ?: ""+ else -> {+ queueGitTokenMigration(raw)+ raw+ }+ }+ } val gitAuthorName: Flow<String> = appContext.editorDataStore.data.map { it[GIT_AUTHOR_NAME_KEY] ?: "" } val gitAuthorEmail: Flow<String> = appContext.editorDataStore.data.map { it[GIT_AUTHOR_EMAIL_KEY] ?: "" } @@ -183,7 +220,17 @@ class EditorPrefs(context: Context) { } suspend fun setGitToken(value: String) {- appContext.editorDataStore.edit { it[GIT_TOKEN_KEY] = value }+ if (value.isEmpty()) {+ appContext.editorDataStore.edit { it[GIT_TOKEN_KEY] = "" }+ return+ }+ val sealed = activeSealer().seal(value)+ if (sealed == null) {+ // Never persist the token in plaintext; a failed seal keeps the previous value.+ Log.error(TAG, "Sealing failed; git token not persisted")+ return+ }+ appContext.editorDataStore.edit { it[GIT_TOKEN_KEY] = sealed } } suspend fun setGitAuthorName(value: String) {@@ -196,6 +243,12 @@ class EditorPrefs(context: Context) { /** Editor preference defaults and DataStore keys. */ companion object {+ private const val KEY_ALIAS = "code_git_token_key"+ private const val TAG = "EditorPrefs"++ /** Test seam: Robolectric has no AndroidKeyStore; tests install a fake sealer here. */+ internal var sealerForTest: TokenSealer? = null+ const val DEFAULT_FONT_SIZE = 14 const val DEFAULT_TAB_WIDTH = 4 const val THEME_SYSTEM = "system"
code/src/main/res/xml/data_extraction_rules.xml
diff --git a/code/src/main/res/xml/data_extraction_rules.xml b/code/src/main/res/xml/data_extraction_rules.xmlindex e578961ebc..7214a1d238 100644--- a/code/src/main/res/xml/data_extraction_rules.xml+++ b/code/src/main/res/xml/data_extraction_rules.xml@@ -13,11 +13,15 @@ No database, no SharedPreferences, no app-private files or caches. Source files are edited in place through SAF in storage the app does not own. - Because that one DataStore file now holds a git token, it must not leave the+ Because that one DataStore file holds a git token, it must not leave the device in cloud backup: cloud backup is denied outright (the file was the only thing cloud backup ever carried here, so nothing else is lost).- Device transfer still carries it, so settings and sign-in survive a direct- device-to-device move; folder access will need re-granting after a restore. -->+ The git_token value itself is Keystore-sealed (EditorPrefs), so even where+ the file does travel it holds only ciphertext. Device transfer still+ carries the file, so settings survive a direct device-to-device move —+ but the token arrives undecryptable on the new device (the Keystore key+ never leaves the old one), reads as signed-out, and must be re-entered;+ folder access will also need re-granting after a restore. --> <data-extraction-rules> <cloud-backup> <exclude domain="root" path="." />
code/src/test/java/com/vayunmathur/code/util/EditorPrefsTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/EditorPrefsTest.kt b/code/src/test/java/com/vayunmathur/code/util/EditorPrefsTest.ktindex 9773d2dad4..d8f04c78a7 100644--- a/code/src/test/java/com/vayunmathur/code/util/EditorPrefsTest.kt+++ b/code/src/test/java/com/vayunmathur/code/util/EditorPrefsTest.kt@@ -20,7 +20,11 @@ import com.vayunmathur.code.platform.setGitUsername @RunWith(RobolectricTestRunner::class) class EditorPrefsTest { - private fun prefs() = EditorPrefs(ApplicationProvider.getApplicationContext())+ private fun prefs(): EditorPrefs {+ // Robolectric has no AndroidKeyStore; seal with the fake (contract-identical) sealer.+ EditorPrefs.sealerForTest = com.vayunmathur.code.data.FakeTokenSealer()+ return EditorPrefs(ApplicationProvider.getApplicationContext())+ } @Test fun defaults() = runTest {
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.ktindex 7748c98a36..74cbb799f3 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt@@ -1,6 +1,8 @@ package com.vayunmathur.communicate.data.googlevoice import android.content.Context+import com.vayunmathur.communicate.data.KeystoreSecretSealer+import com.vayunmathur.communicate.data.SecretSealer import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map@@ -11,19 +13,43 @@ import kotlinx.coroutines.flow.map * the browser's cookies plus the sniffed web `apiKey`; this persists that material * (see `voice-documentation.md` "Authentication, Headers, And Request Conventions"). *- * Cookies and the API key are sensitive; they live in the app's private,- * credential-encrypted DataStore file like any other secret in this repo.+ * The three secrets (cookie, SAPISID, apiKey) are sealed with the+ * AndroidKeyStore-backed [SecretSealer] (everysync `TokenStore` pattern) at+ * persist time. Reads unseal sealed values and migrate legacy plaintext values+ * to sealed form on first read (idempotent; no `Application.onCreate` hook).+ * An unseal failure yields null (signed-out semantics), never a crash, and the+ * stored blob is left intact. Non-secret fields (authUser, phone, flags) stay+ * plaintext. */-class GoogleVoiceSession private constructor(private val store: DataStoreUtils) {+class GoogleVoiceSession internal constructor(+ private val store: DataStoreUtils,+ private val sealer: SecretSealer = KeystoreSecretSealer.shared,+) {++ /**+ * Read a secret key: unseal if sealed (failure -> null, blob intact);+ * if legacy plaintext, return it and rewrite it sealed (migration).+ */+ private suspend fun readSecret(key: String): String? {+ val raw = store.getStringAwait(key) ?: return null+ if (sealer.isSealed(raw)) return sealer.unseal(raw)+ sealer.seal(raw)?.let { store.setString(key, it) }+ return raw+ }++ /** Persist a secret sealed; on seal failure the value is not written at all (never plaintext). */+ private suspend fun writeSecret(key: String, value: String) {+ sealer.seal(value)?.let { store.setString(key, it) }+ } /** Raw `Cookie:` header value captured from the signed-in voice.google.com session. */- suspend fun cookieHeader(): String? = store.getStringAwait(KEY_COOKIE)+ suspend fun cookieHeader(): String? = readSecret(KEY_COOKIE) /** SAPISID cookie value, extracted from [cookieHeader] for SAPISIDHASH auth. */- suspend fun sapisid(): String? = store.getStringAwait(KEY_SAPISID)+ suspend fun sapisid(): String? = readSecret(KEY_SAPISID) /** Web `key=` API key sniffed from a voiceclient RPC URL. */- suspend fun apiKey(): String? = store.getStringAwait(KEY_API_KEY)+ suspend fun apiKey(): String? = readSecret(KEY_API_KEY) /** `x-goog-authuser` index (the `/u/<n>/` account slot). Defaults to "0". */ suspend fun authUser(): String = store.getStringAwait(KEY_AUTHUSER) ?: "0"@@ -58,18 +84,18 @@ class GoogleVoiceSession private constructor(private val store: DataStoreUtils) authUser: String, sapisid: String? = null, ) {- store.setString(KEY_COOKIE, cookieHeader)- store.setString(KEY_API_KEY, apiKey)+ writeSecret(KEY_COOKIE, cookieHeader)+ writeSecret(KEY_API_KEY, apiKey) store.setString(KEY_AUTHUSER, authUser) val resolvedSapisid = sapisid ?: extractSapisid(cookieHeader)- if (resolvedSapisid != null) store.setString(KEY_SAPISID, resolvedSapisid)+ if (resolvedSapisid != null) writeSecret(KEY_SAPISID, resolvedSapisid) store.setBoolean(KEY_SIGNED_IN, true) } /** Refresh just the cookie string (e.g. after a WebView revisit), keeping other fields. */ suspend fun updateCookies(cookieHeader: String) {- store.setString(KEY_COOKIE, cookieHeader)- extractSapisid(cookieHeader)?.let { store.setString(KEY_SAPISID, it) }+ writeSecret(KEY_COOKIE, cookieHeader)+ extractSapisid(cookieHeader)?.let { writeSecret(KEY_SAPISID, it) } } suspend fun setPhoneNumber(number: String) {
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.ktindex 0df3cef7a9..3d1fd67da2 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt@@ -10,6 +10,7 @@ import android.webkit.CookieManager import android.webkit.JavascriptInterface import android.webkit.ValueCallback import android.webkit.WebChromeClient+import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.webkit.WebViewCompat@@ -34,6 +35,25 @@ import kotlinx.coroutines.withTimeoutOrNull object GoogleVoiceWebSender { private const val TAG = "GVAUTO"+ private const val VOICE_HOST = "voice.google.com"++ /**+ * Origin lock for the mint WebView: only `https://voice.google.com`+ * (plus the inert `about:blank`) may navigate in-WebView. The+ * `AndroidGV` bridge is visible to every origin this WebView loads and+ * persists across navigations, so any other main-frame navigation must+ * be blocked rather than allowed to run script against the bridge.+ * Sign-in lives in `GoogleVoiceSignInScreen`; this offscreen sender+ * assumes a live session, so an `accounts.google.com` bounce could+ * never complete the composer automation here anyway.+ */+ internal fun isAllowedMintNavigation(url: String?): Boolean {+ if (url.isNullOrBlank()) return false+ if (url.equals("about:blank", ignoreCase = true)) return true+ val uri = runCatching { Uri.parse(url) }.getOrNull() ?: return false+ return uri.scheme.equals("https", ignoreCase = true) &&+ uri.host.equals(VOICE_HOST, ignoreCase = true)+ } /** Token-mint timeout with no media to upload first. */ private const val MINT_TIMEOUT_MS = 60_000L /** Token-mint timeout when attachments must upload before the send can be built. */@@ -126,10 +146,38 @@ object GoogleVoiceWebSender { } wv.webViewClient = object : WebViewClient() { private var injected = false++ override fun shouldOverrideUrlLoading(+ view: WebView?,+ request: WebResourceRequest?,+ ): Boolean {+ val url = request?.url?.toString()+ // Sub-frame loads are not navigations of the mint page; the+ // lock below governs the main frame that can reach AndroidGV.+ if (request?.isForMainFrame == false) return false+ if (isAllowedMintNavigation(url)) return false+ // This WebView is offscreen: there is no user to hand an+ // external link to, so block rather than hand off.+ Log.dev(TAG, "blocked non-GV navigation")+ return true+ }++ @Deprecated("Deprecated in Java")+ override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {+ if (isAllowedMintNavigation(url)) return false+ Log.dev(TAG, "blocked non-GV navigation")+ return true+ }+ override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) { super.onPageStarted(view, url, favicon) // Fallback hook injection for devices without DOCUMENT_START_SCRIPT.- view?.evaluateJavascript(hookScript(), null)+ // Gated on the same origin lock: a navigation that slips+ // past shouldOverride (e.g. a server redirect) must not get+ // the hook, and its scripts must not reach AndroidGV via it.+ if (isAllowedMintNavigation(url)) {+ view?.evaluateJavascript(hookScript(), null)+ } } override fun onRenderProcessGone( view: WebView?,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.ktindex a09846c59e..e6003dea12 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.kt@@ -2,6 +2,8 @@ package com.vayunmathur.communicate.data.signal import android.content.Context import androidx.core.content.edit+import com.vayunmathur.communicate.data.KeystoreSecretSealer+import com.vayunmathur.communicate.data.SecretSealer import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json as KotlinJson@@ -86,20 +88,44 @@ data class SignalAuthData( private const val PREFS_NAME = "communicate_signal_auth" private const val KEY_AUTH_DATA = "auth_data" - fun load(context: Context): SignalAuthData? {+ /**+ * Load the sealed (or legacy plaintext) auth JSON. This store holds+ * identity-key material, so failure handling is conservative:+ *+ * Sealed: unseal then parse; unseal/parse failure returns null+ * (behaves as 'not registered') and the stored blob is left intact+ * for retry on the next launch — never overwritten or deleted.+ * Legacy plaintext: parse first and rewrite sealed ONLY after a+ * successful parse (verify-before-overwrite). Idempotent.+ */+ fun load(context: Context, sealer: SecretSealer = KeystoreSecretSealer.shared): SignalAuthData? { val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)- val json = prefs.getString(KEY_AUTH_DATA, null) ?: return null- return try {- KotlinJson.decodeFromString<SignalAuthData>(json)+ val raw = prefs.getString(KEY_AUTH_DATA, null) ?: return null+ if (sealer.isSealed(raw)) {+ val json = sealer.unseal(raw) ?: return null+ return try {+ KotlinJson.decodeFromString<SignalAuthData>(json)+ } catch (_: Exception) {+ null+ }+ }+ val parsed = try {+ KotlinJson.decodeFromString<SignalAuthData>(raw) } catch (_: Exception) {- null+ return null+ }+ sealer.seal(raw)?.let { sealed ->+ prefs.edit { putString(KEY_AUTH_DATA, sealed) } }+ return parsed } - fun save(context: Context, authData: SignalAuthData) {+ /** Save the whole auth JSON sealed; on seal failure nothing is written (never plaintext). */+ fun save(context: Context, authData: SignalAuthData, sealer: SecretSealer = KeystoreSecretSealer.shared) { val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) val json = KotlinJson.encodeToString(authData)- prefs.edit { putString(KEY_AUTH_DATA, json) }+ val sealed = sealer.seal(json) ?: return+ prefs.edit { putString(KEY_AUTH_DATA, sealed) } } fun clear(context: Context) {
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.ktindex e4b134b2ac..6d56e76acc 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.kt@@ -5,7 +5,9 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.launch /**@@ -36,6 +38,18 @@ class SignalEventProcessor(private val db: SignalDatabase) { private val conversations = db.conversationDao() private val callLog = db.callLogDao() + /**+ * Terminal signal for tests and diagnostics: each event is emitted+ * here only after [handle] has finished persisting it, in drain+ * order. Awaiting this flow is a wait on work done, not a poll of+ * the database. Replay keeps a late subscriber from missing an+ * event that landed before it started collecting.+ */+ private val _handledEvents = MutableSharedFlow<SignalEvent>(+ replay = 64, extraBufferCapacity = 64,+ )+ val handledEvents: SharedFlow<SignalEvent> = _handledEvents.asSharedFlow()+ fun start(events: SharedFlow<SignalEvent>) { scope.launch { events.collect { event ->@@ -43,6 +57,8 @@ class SignalEventProcessor(private val db: SignalDatabase) { handle(event) } catch (expected: Throwable) { Log.error(TAG, "failed to process ${event::class.simpleName}", expected)+ } finally {+ _handledEvents.emit(event) } } }
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.ktindex 13e3b62bbc..1f483a1cf0 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt@@ -2,6 +2,8 @@ package com.vayunmathur.communicate.data.whatsapp import android.content.Context import androidx.core.content.edit+import com.vayunmathur.communicate.data.KeystoreSecretSealer+import com.vayunmathur.communicate.data.SecretSealer import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json as KotlinJson@@ -67,20 +69,43 @@ data class WhatsAppAuthData( private const val PREFS_NAME = "communicate_whatsapp_auth" private const val KEY_AUTH_DATA = "auth_data" - fun load(context: Context): WhatsAppAuthData? {+ /**+ * Load the sealed (or legacy plaintext) auth JSON.+ *+ * Sealed: unseal then parse; unseal/parse failure returns null+ * (signed-out) and leaves the blob intact. Legacy plaintext: parse+ * first and rewrite sealed ONLY after a successful parse+ * (verify-before-overwrite — a botched rewrite would force+ * re-registration). Idempotent: the second load sees sealed form.+ */+ fun load(context: Context, sealer: SecretSealer = KeystoreSecretSealer.shared): WhatsAppAuthData? { val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)- val json = prefs.getString(KEY_AUTH_DATA, null) ?: return null- return try {- KotlinJson.decodeFromString<WhatsAppAuthData>(json)+ val raw = prefs.getString(KEY_AUTH_DATA, null) ?: return null+ if (sealer.isSealed(raw)) {+ val json = sealer.unseal(raw) ?: return null+ return try {+ KotlinJson.decodeFromString<WhatsAppAuthData>(json)+ } catch (ignored: Exception) {+ null+ }+ }+ val parsed = try {+ KotlinJson.decodeFromString<WhatsAppAuthData>(raw) } catch (ignored: Exception) {- null+ return null+ }+ sealer.seal(raw)?.let { sealed ->+ prefs.edit { putString(KEY_AUTH_DATA, sealed) } }+ return parsed } - fun save(context: Context, authData: WhatsAppAuthData) {+ /** Save the whole auth JSON sealed; on seal failure nothing is written (never plaintext). */+ fun save(context: Context, authData: WhatsAppAuthData, sealer: SecretSealer = KeystoreSecretSealer.shared) { val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) val json = KotlinJson.encodeToString(authData)- prefs.edit { putString(KEY_AUTH_DATA, json) }+ val sealed = sealer.seal(json) ?: return+ prefs.edit { putString(KEY_AUTH_DATA, sealed) } } fun clear(context: Context) {
communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2ProcessorTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2ProcessorTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2ProcessorTest.ktindex cb840fbf3e..fbffeb1fad 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2ProcessorTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2ProcessorTest.kt@@ -18,7 +18,10 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.withContext import kotlinx.coroutines.test.runTest import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner@@ -59,36 +62,33 @@ class SignalSlice2ProcessorTest { private suspend fun emit(e: SignalEvent) { events.emit(e)- awaitSettled { settled(e) }+ awaitHandled(e) } /**- * Poll until [cond] holds (bounded); mirrors the WhatsApp slice's- * processor test. The wait runs on a real-time dispatcher: this class- * uses runTest, whose virtual clock burns a delay budget instantly,- * while the processor drains on Dispatchers.IO in real time — polling- * on the test scheduler lost that race under load.+ * Waits for the processor's terminal signal: [SignalEventProcessor]+ * emits each event on `handledEvents` only after it has been+ * persisted, and this drain is sequential, so when this returns the+ * database row is settled. Identity (`===`) distinguishes a+ * redelivery of an equal event from the first delivery. This runs+ * on Dispatchers.Default because the processor drains on+ * Dispatchers.IO in real time while this class's `runTest` scheduler+ * is virtual; suspending on the flow (not a delay loop) is resumed+ * by the emission itself. */- private suspend fun awaitSettled(cond: suspend () -> Boolean) {- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) {- var waited = 0- while (waited < 500 && !cond()) {- kotlinx.coroutines.delay(10)- waited++- }+ private suspend fun awaitHandled(e: SignalEvent) {+ withContext(Dispatchers.Default) {+ processor.handledEvents.first { it === e } } } - private suspend fun settled(e: SignalEvent): Boolean = when (e) {- is SignalEvent.IncomingMessage -> db.cachedMessageDao().get(e.messageId) != null- is SignalEvent.MessageUpdate -> db.cachedMessageDao().get(e.messageId)?.body == e.body- is SignalEvent.ConversationUpdate ->- db.conversationDao().getConversation(e.conversationId) != null- is SignalEvent.HistorySync ->- e.conversations.all { c ->- db.cachedMessageDao().getForConversation(c.conversationId).size == c.messages.size- }- else -> true+ /** Awaits a database terminal state already signalled via [emit]. */+ private suspend fun awaitSettled(cond: suspend () -> Boolean) {+ // Kept as a named step for call sites whose event type has no+ // single settled row (reactions, receipts): the preceding emit+ // already awaited the handled signal, so this is an assertion+ // of the settled state, not a wait. It must hold immediately.+ check(cond()) { "event handled but database state not settled" } } @Test
email/src/test/java/com/vayunmathur/email/ui/EmlViewerScreenTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/EmlViewerScreenTest.kt b/email/src/test/java/com/vayunmathur/email/ui/EmlViewerScreenTest.ktindex 8059a530d8..dbbcaa95c1 100644--- a/email/src/test/java/com/vayunmathur/email/ui/EmlViewerScreenTest.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/EmlViewerScreenTest.kt@@ -11,6 +11,7 @@ import kotlin.test.assertEquals import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import com.vayunmathur.testsupport.awaitSemantics import org.robolectric.annotation.Config /**@@ -32,7 +33,10 @@ class EmlViewerScreenTest { composeRule.setContent { EmlViewerScreen(uriString = "content://invalid/nonexistent.eml", onBack = {}) }- composeRule.waitUntil(15_000) {+ // Terminal semantics wait with the main looper idled on each+ // check (shared helper): without that pump the IO parse's resume+ // sat queued past a plain waitUntil under load.+ composeRule.awaitSemantics("eml error") { composeRule.onAllNodesWithText("Couldn't open this .eml file", substring = true) .fetchSemanticsNodes().isNotEmpty() }@@ -45,11 +49,14 @@ class EmlViewerScreenTest { composeRule.setContent { EmlViewerScreen(uriString = "content://invalid/nonexistent.eml", onBack = {}) }- composeRule.waitUntil(15_000) {+ composeRule.awaitSemantics("retry button") { composeRule.onAllNodesWithText("Retry").fetchSemanticsNodes().isNotEmpty() } composeRule.onNodeWithText("Retry").performClick()- composeRule.waitUntil(15_000) {+ // Terminal semantics wait with the main looper idled on each+ // check (shared helper): without that pump the IO parse's resume+ // sat queued past a plain waitUntil under load.+ composeRule.awaitSemantics("eml error") { composeRule.onAllNodesWithText("Couldn't open this .eml file", substring = true) .fetchSemanticsNodes().isNotEmpty() }@@ -62,7 +69,7 @@ class EmlViewerScreenTest { composeRule.setContent { EmlViewerScreen(uriString = "content://invalid/nonexistent.eml", onBack = { backs++ }) }- composeRule.waitUntil(15_000) {+ composeRule.awaitSemantics("retry button") { composeRule.onAllNodesWithText("Retry").fetchSemanticsNodes().isNotEmpty() } // The scaffold back button carries the "Back" content description.
email/src/test/java/com/vayunmathur/email/ui/EmlViewerSuccessTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/EmlViewerSuccessTest.kt b/email/src/test/java/com/vayunmathur/email/ui/EmlViewerSuccessTest.ktindex 04a3a746e9..8b4c8f7c5f 100644--- a/email/src/test/java/com/vayunmathur/email/ui/EmlViewerSuccessTest.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/EmlViewerSuccessTest.kt@@ -20,6 +20,7 @@ import kotlin.test.assertTrue import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import com.vayunmathur.testsupport.awaitSemantics import org.robolectric.annotation.Config /**@@ -39,25 +40,17 @@ class EmlViewerSuccessTest { /**- * Waits for [text] to appear, idling Robolectric's paused main looper so- * the IO parse's Main-thread resume can actually land: the compose- * rule's waitUntil does not pump that looper, so under load the parse- * result sat queued past the wait (see ComposerSendTest).+ * Waits for [text] as a terminal semantics state: the compose rule+ * re-checks after every idle and the shared helper idles Robolectric's+ * paused main looper on each check, so the IO parse's Main-thread+ * resume can actually land. Replaces a Thread.sleep step loop whose+ * 15s wall-clock deadline expired before the parse ran under load. */ private fun awaitText(text: String, substring: Boolean = false, unmerged: Boolean = false) {- // Step-counted, not wall-clock: Robolectric's substituted clock- // can run far ahead of real time while the looper is idled, so a- // 15s deadline expired before the IO parse it waits for had run- // on a loaded CI box. Each step sleeps real time instead.- var step = 0- while (step++ < 3_000) {- org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()- if (composeRule.onAllNodesWithText(text, substring = substring, useUnmergedTree = unmerged)- .fetchSemanticsNodes().isNotEmpty()- ) return- Thread.sleep(10)+ composeRule.awaitSemantics("text: $text") {+ composeRule.onAllNodesWithText(text, substring = substring, useUnmergedTree = unmerged)+ .fetchSemanticsNodes().isNotEmpty() }- throw AssertionError("timed out waiting for text: $text") } private fun writeEml(name: String, content: String): File {
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.ktindex 92530240a3..074ff2894f 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt@@ -1,6 +1,7 @@ package com.vayunmathur.fooddelivery.platform import android.content.Context+import android.content.SharedPreferences import com.vayunmathur.library.image.fetchers.HttpImageFetcher import com.vayunmathur.library.image.ImageLoader import com.vayunmathur.library.log.Log@@ -20,16 +21,32 @@ import java.util.concurrent.atomic.AtomicBoolean * * [NetworkClient.init] opens and X.509-parses the bundled DER roots, fills a KeyStore and * initialises an SSLContext, and the saved auth token has to be read out of- * SharedPreferences and JSON-decoded — none of which may happen on the main thread or a+ * SharedPreferences, Keystore-unsealed and JSON-decoded — none of which may happen on the main thread or a * binder thread. Both process entry points ([com.vayunmathur.fooddelivery.FoodDeliveryApplication] * and [com.vayunmathur.fooddelivery.intents.OrderLookupIntent], which may launch into a cold * process) call [start], which is idempotent; anything that needs the token or the pinned trust * anchors awaits [awaitReady] from a coroutine instead of blocking.+ *+ * The persisted token is sealed inside the callbacks installed here (the only writers of+ * `token_json` besides sign-out removal): [BitesAuth.onTokenUpdated] stores only+ * Keystore-sealed ciphertext, and the restore below unseals-or-migrates — a legacy+ * plaintext value is verified as JSON, restored, then rewritten sealed; a sealed value+ * that no longer decrypts (restored on another device, lost key) starts signed-out.+ * Cold-process services rely on this warm-up, so the migration lives here, not in an+ * Activity. */ object AppInit { private const val PREFS_NAME = "fooddelivery_prefs" private const val KEY_TOKEN = "token_json"+ private const val KEY_ALIAS = "fooddelivery_token_key"++ /** Test seam: Robolectric has no AndroidKeyStore; tests install a fake sealer here. */+ internal var sealerForTest: TokenSealer? = null++ private val defaultSealer by lazy { KeystoreTokenSealer(KEY_ALIAS) }++ private fun activeSealer(): TokenSealer = sealerForTest ?: defaultSealer private val started = AtomicBoolean(false) private val ready = CompletableDeferred<Unit>()@@ -63,10 +80,17 @@ object AppInit { val prefs = appCtx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // The application context, not an Activity: BitesAuth outlives every Activity. BitesAuth.onTokenUpdated = { tokenJson ->- prefs.edit { putString(KEY_TOKEN, tokenJson) }+ // Only sealed ciphertext is persisted; on seal failure keep the+ // previous value rather than writing the token in plaintext.+ val sealed = activeSealer().seal(tokenJson)+ if (sealed == null) {+ Log.status("AppInit", "token sealing failed; token not persisted")+ } else {+ prefs.edit { putString(KEY_TOKEN, sealed) }+ } } BitesAuth.onTokenCleared = { prefs.edit { remove(KEY_TOKEN) } }- prefs.getString(KEY_TOKEN, null)?.let { BitesAuth.restoreToken(it) }+ prefs.getString(KEY_TOKEN, null)?.let { stored -> restorePersistedToken(prefs, stored) } } catch (e: SecurityException) { Log.status("AppInit", "token warm-up failed", e) } catch (e: IllegalArgumentException) {@@ -76,6 +100,37 @@ object AppInit { } } + /**+ * Restores the persisted token, migrating legacy plaintext in place: a non-sealed+ * value is verified as JSON first (a corrupt value is left untouched and never+ * sealed over), restored, then rewritten sealed only if the stored value has not+ * changed since the read. A sealed value that cannot be unsealed (restored on+ * another device, lost Keystore key) starts signed-out — never a crash.+ */+ private fun restorePersistedToken(prefs: SharedPreferences, stored: String) {+ val sealer = activeSealer()+ if (!sealer.isSealed(stored)) {+ try {+ kotlinx.serialization.json.Json.parseToJsonElement(stored)+ } catch (e: IllegalArgumentException) {+ Log.status("AppInit", "stored token is not valid JSON; not restoring", e)+ return+ }+ BitesAuth.restoreToken(stored)+ val sealed = sealer.seal(stored) ?: return+ if (prefs.getString(KEY_TOKEN, null) == stored) {+ prefs.edit { putString(KEY_TOKEN, sealed) }+ }+ return+ }+ val plain = sealer.unseal(stored)+ if (plain == null) {+ Log.status("AppInit", "stored token could not be unsealed; starting signed out")+ return+ }+ BitesAuth.restoreToken(plain)+ }+ suspend fun awaitReady() { ready.await() }
games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.ktindex 3df08f3644..5202dfff21 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt@@ -1,8 +1,14 @@ package com.vayunmathur.games.chess.auth import android.content.Context+import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.launch /** * Persists the Lichess OAuth access token in the app's DataStore.@@ -10,28 +16,79 @@ import kotlinx.coroutines.flow.Flow * The token authenticates every Board API call as a Bearer header via [authHeaders]; [clear] * drops it on sign-out or on [LichessAuthExpired] (HTTP 401). The lobby reads [usernameNow] for * its signed-in header without a network round-trip.+ *+ * The stored token is sealed with a non-exportable Android Keystore key (see+ * [KeystoreTokenSealer]): only ciphertext ever reaches the DataStore file, so the token+ * stays useless if that file leaves the device via backup or device transfer. A sealed+ * value that no longer decrypts (restored on a new device, lost key) reads as signed-out.+ * Legacy plaintext tokens from before sealing are used once and rewritten sealed. */ class LichessTokenStore(context: Context) { private val store = DataStoreUtils.getInstance(context.applicationContext) + /** Fire-and-forget legacy-migration rewrites triggered from the [token] Flow. */+ private val migrationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ /** Shared constants and helpers for LichessTokenStore. */ companion object { private const val KEY_ACCESS_TOKEN = "lichess_access_token" private const val KEY_USERNAME = "lichess_username" private const val KEY_USER_ID = "lichess_user_id" + private const val KEY_ALIAS = "games_chess_lichess_token_key" private const val AUTH_SCHEME = "Bearer "+ private const val TAG = "LichessTokenStore"++ /** Test seam: Robolectric has no AndroidKeyStore; tests install a fake sealer here. */+ internal var sealerForTest: TokenSealer? = null } - /** Emits the stored access token when set; silent before sign-in / after [clear]. */- val token: Flow<String> = store.stringFlow(KEY_ACCESS_TOKEN)+ /** Emits the unsealed access token when set; silent before sign-in / after [clear]. */+ val token: Flow<String> = store.stringFlow(KEY_ACCESS_TOKEN).map { raw -> unsealOrEmpty(raw) } /** Emits the verified Lichess username from the last `/api/account` check. */ val username: Flow<String> = store.stringFlow(KEY_USERNAME) + /**+ * Unseals a stored token value for emission: empty stays empty, an undecryptable+ * sealed value becomes empty (signed-out), and a legacy plaintext value is returned+ * as-is with a sealed rewrite queued (idempotent migration on first read).+ */+ private fun unsealOrEmpty(raw: String): String {+ if (raw.isEmpty()) return ""+ val plain = activeSealer().unseal(raw) ?: return ""+ if (!activeSealer().isSealed(raw)) queueMigration(raw, plain)+ return plain+ }++ /** Rewrites a legacy plaintext token sealed, but only if it is still the stored value. */+ private fun queueMigration(legacyRaw: String, plain: String) {+ migrationScope.launch {+ val sealed = activeSealer().seal(plain) ?: return@launch+ if (store.getStringAwait(KEY_ACCESS_TOKEN) == legacyRaw) {+ store.setString(KEY_ACCESS_TOKEN, sealed)+ }+ }+ }++ private val defaultSealer by lazy { KeystoreTokenSealer(KEY_ALIAS) }++ private fun activeSealer(): TokenSealer = sealerForTest ?: defaultSealer+ /** Snapshot for one-shot reads (sign-in finish, API header build, VM init). */- suspend fun tokenNow(): String? = store.getStringAwait(KEY_ACCESS_TOKEN)?.takeIf { it.isNotEmpty() }+ suspend fun tokenNow(): String? {+ val raw = store.getStringAwait(KEY_ACCESS_TOKEN)?.takeIf { it.isNotEmpty() } ?: return null+ val plain = activeSealer().unseal(raw) ?: return null+ if (!activeSealer().isSealed(raw)) {+ // Legacy plaintext: rewrite sealed, verifying the value has not changed since the read.+ val sealed = activeSealer().seal(plain)+ if (sealed != null && store.getStringAwait(KEY_ACCESS_TOKEN) == raw) {+ store.setString(KEY_ACCESS_TOKEN, sealed)+ }+ }+ return plain.takeIf { it.isNotEmpty() }+ } /** Snapshot of the stored username (lobby header without a network round-trip). */ suspend fun usernameNow(): String? = store.getStringAwait(KEY_USERNAME)?.takeIf { it.isNotEmpty() }@@ -43,7 +100,17 @@ class LichessTokenStore(context: Context) { } suspend fun saveToken(token: String) {- store.setString(KEY_ACCESS_TOKEN, token)+ if (token.isEmpty()) {+ store.setString(KEY_ACCESS_TOKEN, "")+ return+ }+ val sealed = activeSealer().seal(token)+ if (sealed == null) {+ // Never persist the token in plaintext; a failed seal keeps the previous value.+ Log.error(TAG, "Sealing failed; Lichess token not persisted")+ return+ }+ store.setString(KEY_ACCESS_TOKEN, sealed) } suspend fun saveUsername(username: String) {
games/chess/src/main/res/xml/data_extraction_rules.xml
diff --git a/games/chess/src/main/res/xml/data_extraction_rules.xml b/games/chess/src/main/res/xml/data_extraction_rules.xmlindex f644a29dff..da252e842a 100644--- a/games/chess/src/main/res/xml/data_extraction_rules.xml+++ b/games/chess/src/main/res/xml/data_extraction_rules.xml@@ -2,13 +2,18 @@ <!-- Chess. Audited state: everything the app persists lives in filesDir/datastore_default.preferences_pb (DataStoreUtils) — Learn-mode stars,- achievements and game settings. No Room database, no files written to filesDir+ achievements, game settings, and the Lichess sign-in (username/user id plus the+ OAuth access token). The token is stored Keystore-sealed (AES-GCM,+ auth/LichessTokenStore): only ciphertext ever reaches this file, and the+ non-exportable Keystore key never leaves the device, so a token carried away+ by backup or device transfer is undecryptable on the destination and simply+ reads as signed-out there. No Room database, no files written to filesDir or external storage; puzzles.dat / learn.json / achievements.json are read-only APK assets. Stockfish's NNUE is read straight out of the APK. So: back everything up. Losing Learn progress on a phone migration is exactly- the outcome these rules exist to prevent. Nothing here is large or personal- enough to warrant an exclusion, and the platform already drops cacheDir and+ the outcome these rules exist to prevent. The one secret in the file is+ sealed ciphertext (see above), and the platform already drops cacheDir and code_cache on its own. SCOPE: chess declares android:backupAgent=".util.AppBackupAgent" and does NOT
games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessTokenStoreTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessTokenStoreTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessTokenStoreTest.ktindex de9c7f34bf..f89f265fed 100644--- a/games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessTokenStoreTest.kt+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessTokenStoreTest.kt@@ -2,12 +2,17 @@ package com.vayunmathur.games.chess.auth import android.content.Context import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.DataStoreUtils+import javax.crypto.spec.SecretKeySpec 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.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue @@ -15,6 +20,14 @@ import kotlin.test.assertTrue class LichessTokenStoreTest { private val ctx get() = ApplicationProvider.getApplicationContext<Context>() + @BeforeTest fun installFakeSealer() {+ LichessTokenStore.sealerForTest = FakeTokenSealer()+ }++ @AfterTest fun removeFakeSealer() {+ LichessTokenStore.sealerForTest = null+ }+ @Test fun `token lifecycle save read headers and clear`() = runBlocking { val store = LichessTokenStore(ctx) store.clear()@@ -31,9 +44,46 @@ class LichessTokenStoreTest { assertEquals(mapOf("Authorization" to "Bearer secret-token"), store.authHeaders()) assertEquals("secret-token", store.token.first { it.isNotEmpty() }) assertEquals("ada", store.username.first { it.isNotEmpty() })+ // Only sealed form reaches the DataStore file (the fake sealer's marker+ // prefix; the AES sealer's no-plaintext property is covered below).+ val raw = DataStoreUtils.getInstance(ctx).getStringAwait("lichess_access_token")+ assertTrue(raw!!.startsWith("v1:"), "stored token must be sealed, was: $raw") store.clear() assertNull(store.tokenNow()) assertNull(store.usernameNow()) assertTrue(store.authHeaders().isEmpty()) }++ @Test fun `legacy plaintext token is used once and rewritten sealed`() = runBlocking {+ val ds = DataStoreUtils.getInstance(ctx)+ ds.setString("lichess_access_token", "legacy-token")+ val store = LichessTokenStore(ctx)+ assertEquals("legacy-token", store.tokenNow())+ val raw = ds.getStringAwait("lichess_access_token")+ assertTrue(raw!!.startsWith("v1:"), "legacy token must be rewritten sealed, was: $raw")+ assertEquals("legacy-token", store.tokenNow())+ store.clear()+ }++ @Test fun `unsealable sealed token reads as signed out`() = runBlocking {+ DataStoreUtils.getInstance(ctx).setString("lichess_access_token", "v1:!!!not-a-token!!!")+ val store = LichessTokenStore(ctx)+ assertNull(store.tokenNow())+ assertTrue(store.authHeaders().isEmpty())+ assertEquals("", store.token.first())+ store.clear()+ }++ @Test fun `keystore sealer round trips with a software key and fails closed`() {+ val sealer = KeystoreTokenSealer("test_alias")+ sealer.secretKeyForTest = SecretKeySpec(ByteArray(32) { (it * 7 + 1).toByte() }, "AES")+ val sealed = sealer.seal("hello-token")!!+ assertTrue(sealer.isSealed(sealed))+ assertFalse(sealed.contains("hello-token"))+ assertEquals("hello-token", sealer.unseal(sealed))+ // Legacy plaintext passes through; tampered sealed values fail closed.+ assertEquals("plain-legacy", sealer.unseal("plain-legacy"))+ assertFalse(sealer.isSealed("plain-legacy"))+ assertNull(sealer.unseal(sealed.dropLast(4) + "AAAA"))+ } }
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.ktindex 22c9be77f7..92b73bac78 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt@@ -5,11 +5,12 @@ import androidx.test.core.app.ApplicationProvider import com.vayunmathur.games.nonogram.data.GameMode import com.vayunmathur.games.nonogram.data.MarkMode import com.vayunmathur.games.nonogram.data.STARTING_HEARTS-import java.util.concurrent.locks.LockSupport import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi+import com.vayunmathur.testsupport.awaitValueBlocking+import com.vayunmathur.testsupport.idleMainLooper+import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first-import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain@@ -70,8 +71,9 @@ class NonogramViewModelTest { runCatching { blocking { store.setMarkMode(store.markMode.first()) } } vmStore.clear() repeat(2) {+ // Each barrier edit is a blocking DataStore round-trip that+ // returns only once applied, so no sleep is needed between them. runCatching { blocking { store.setMarkMode(store.markMode.first()) } }- Thread.sleep(50) } retrying { Dispatchers.resetMain() } }@@ -79,59 +81,38 @@ class NonogramViewModelTest { /** set/resetMain throw if a background coroutine happens to be using Main at that instant. */ private fun retrying(action: () -> Unit) { var attempts = 0- while (attempts++ < RETRIES && runCatching(action).isFailure) Thread.sleep(10)+ // No sleep: idling the paused main looper is what lets a background+ // Main coroutine finish and release the dispatcher this retries on.+ while (attempts++ < RETRIES && runCatching(action).isFailure) idleMainLooper() if (attempts > RETRIES) action() } private companion object { const val RETRIES = 20- const val AWAIT_STEPS = 2000- const val AWAIT_STEP_NANOS = 25_000_000L } /**- * Polls [cond] for up to [AWAIT_STEPS] steps.- *- * Counted in steps rather than against System.currentTimeMillis(): Robolectric substitutes its- * own clock for test code, which can run far ahead of real time, so a clock-based deadline could- * give up within milliseconds while a background write was still landing.+ * Waits for a terminal [NonogramUiState]: suspends on the StateFlow+ * itself until an emission matches, instead of polling `uiState.value`+ * with sleeps or a burned-CPU step loop. The ViewModel runs on an+ * unconfined Main dispatcher in this suite and generates on+ * Dispatchers.Default, so the emission resumes this wait directly. */- @Volatile- private var burnSink: Long = 0-- private fun stepSleep() {- // Robolectric virtualises every clock, park, sleep, wait and- // scheduled delay reachable from this suite (they all return in- // ~0.2ms, advancing the substituted clock), so an await step- // cannot literally wait: step budgets burned out in ~0.16s of- // real time, before slow-but-healthy IO writes landed on a- // loaded box — hence the rotating "timed out" failures. The- // only real time available is CPU work, so a step burns a- // fixed dependent-arithmetic loop (~10ms on a fast core; a- // slower CI core just makes each step longer, which is the- // safe direction). The volatile sink keeps the JIT honest.- var x = burnSink + 0x9E3779B97F4A7C15uL.toLong()- for (i in 0 until 20_000_000) {- x = x * 31 + i+ private fun awaitState(desc: String, vm: NonogramViewModel, cond: (NonogramUiState) -> Boolean) {+ try {+ awaitValueBlocking(vm.uiState) { cond(it) }+ } catch (e: Throwable) {+ throw AssertionError("timed out: $desc; last state=${vm.uiState.value}", e) }- burnSink = x } --- private fun await(desc: String, maxSteps: Int = AWAIT_STEPS, cond: () -> Boolean) {- // Assert on the observed value, not a fresh re-read: the old- // shape evaluated cond() once to leave the loop and again in- // assertTrue, and a store value that flipped between those two- // reads (or a transiently failing second read) failed a wait- // that had actually succeeded — "timed out after 1 steps".- var steps = 0- var ok = cond()- while (!ok && steps++ < maxSteps) {- stepSleep()- ok = cond()+ /** Waits for a terminal DataStore state on the store's own flow. */+ private fun awaitStore(desc: String, cond: suspend () -> Unit) {+ try {+ blocking { cond() }+ } catch (e: Throwable) {+ throw AssertionError("timed out: $desc", e) }- assertTrue(ok, "timed out: $desc after $steps steps") } /**@@ -139,11 +120,9 @@ class NonogramViewModelTest { * under Robolectric the timeout's delay runs on the substituted * clock and fires effectively instantly, so any read that needs an * async DataStore round-trip loses the race and the poll conditions- * in [await] could never observe a landed write (the "undo- * persisted" flake: every poll timed out before the emission- * arrived). The store's write actor is kept alive by initializing- * WorkManager in setUp, so reads complete; [await]'s step budget- * bounds the total wait instead.+ * in the flow-first waits could never observe a landed write. The+ * store's write actor is kept alive by initializing WorkManager in+ * setUp, so reads complete. */ private fun <T> blocking(block: suspend () -> T): T = runBlocking { block() } @@ -161,7 +140,7 @@ class NonogramViewModelTest { // for the next collector. These three edits are tiny; let them land. runBlocking { store.saveLevel(level); store.setGameMode(GameMode.CASUAL); store.setMarkMode(MarkMode.FILL) } val vm = track(NonogramViewModel(app))- await("game loads") { vm.uiState.value.game != null && !vm.uiState.value.generating }+ awaitState("game loads", vm) { it.game != null && !it.generating } return vm } @@ -181,23 +160,23 @@ class NonogramViewModelTest { val correct = g.puzzle.solution.indices.first { g.puzzle.solution[it] } val wrong = g.puzzle.solution.indices.first { !g.puzzle.solution[it] } vm.tapCell(correct)- await("fill lands") { vm.uiState.value.game?.filled?.contains(correct) == true }+ awaitState("fill lands", vm) { it.game?.filled?.contains(correct) == true } vm.tapCell(correct) // locked: no-op vm.tapCell(wrong)- await("heart spent") { vm.uiState.value.game?.hearts == STARTING_HEARTS - 1 }+ awaitState("heart spent", vm) { it.game?.hearts == STARTING_HEARTS - 1 } assertTrue(vm.uiState.value.game!!.revealedBlanks.contains(wrong)) // Cross mode: tap only notes, even on a picture cell, never costs. vm.setMarkMode(MarkMode.CROSS)- await("cross mode") { vm.uiState.value.markMode == MarkMode.CROSS }+ awaitState("cross mode", vm) { it.markMode == MarkMode.CROSS } val noteCell = vm.uiState.value.game!!.puzzle.solution.indices.first { vm.uiState.value.game!!.puzzle.solution[it] && it !in vm.uiState.value.game!!.filled } vm.tapCell(noteCell)- await("note placed") { vm.uiState.value.game?.crossed?.contains(noteCell) == true }+ awaitState("note placed", vm) { it.game?.crossed?.contains(noteCell) == true } assertEquals(STARTING_HEARTS - 1, vm.uiState.value.game!!.hearts) vm.tapCell(noteCell)- await("note removed") { vm.uiState.value.game?.crossed?.contains(noteCell) == false }+ awaitState("note removed", vm) { it.game?.crossed?.contains(noteCell) == false } // Long-press in cross mode performs the fill action. vm.crossCell(noteCell)- await("long press fills") { vm.uiState.value.game?.filled?.contains(noteCell) == true }+ awaitState("long press fills", vm) { it.game?.filled?.contains(noteCell) == true } } @Test fun movesUpdateTheBoardBeforeAnyWriteLands() {@@ -215,9 +194,9 @@ class NonogramViewModelTest { vm.tapCell(note) assertFalse(note in vm.uiState.value.game!!.crossed, "second quick tap must clear the X, not add it again") // And the store catches up to what is on screen.- await("persisted") {- blocking { vm.dataStore.filledCells.first() } == setOf(correct) &&- blocking { vm.dataStore.crossedCells.first() }.isEmpty()+ awaitStore("persisted") {+ combine(vm.dataStore.filledCells, vm.dataStore.crossedCells) { f, c -> f to c }+ .first { (f, c) -> f == setOf(correct) && c.isEmpty() } } assertTrue(correct in vm.uiState.value.game!!.filled) assertFalse(note in vm.uiState.value.game!!.crossed)@@ -230,10 +209,10 @@ class NonogramViewModelTest { val target = picture.take(picture.size - 1) for (i in target) vm.tapCell(i) assertEquals(target.toSet(), vm.uiState.value.game!!.filled)- await("last snapshot wins") { blocking { vm.dataStore.filledCells.first() } == target.toSet() }+ awaitStore("last snapshot wins") { vm.dataStore.filledCells.first { it == target.toSet() } } // A fresh ViewModel (a relaunch) loads exactly what was played. val again = track(NonogramViewModel(app))- await("reload") { again.uiState.value.game?.filled == target.toSet() }+ awaitState("reload", again) { it.game?.filled == target.toSet() } } @Test fun dragStrokeFillsALineAndChargesOneHeartForAMistake() {@@ -286,16 +265,9 @@ class NonogramViewModelTest { assertFalse(vm.uiState.value.canUndo) vm.undo() // empty: no-op assertEquals(s, vm.uiState.value.game)- // Undo is persisted like any move. A transient failure of the- // read itself (the Robolectric environment occasionally- // interrupts the polling runBlocking) must not abort the wait:- // it just means "not landed yet". The final condition still- // requires the store to actually read empty.- await("undo persisted") {- runCatching { blocking { vm.dataStore.filledCells.first() } }- .getOrDefault(setOf(-1))- .isEmpty()- }+ // Undo is persisted like any move: suspend on the store flow+ // until the empty board is the emitted terminal state.+awaitStore("undo persisted") { vm.dataStore.filledCells.first { it.isEmpty() } } // Restart wipes the history. vm.crossCell(correct) assertTrue(vm.uiState.value.canUndo)@@ -308,22 +280,24 @@ class NonogramViewModelTest { val g = vm.uiState.value.game!! val cell = g.puzzle.solution.indices.first { !g.puzzle.solution[it] } vm.crossCell(cell)- await("long-press note") { vm.uiState.value.game?.crossed?.contains(cell) == true }+ awaitState("long-press note", vm) { it.game?.crossed?.contains(cell) == true } assertEquals(STARTING_HEARTS, vm.uiState.value.game!!.hearts) vm.restartLevel()- await("restart clears") { vm.uiState.value.game?.crossed?.isEmpty() == true }+ awaitState("restart clears", vm) { it.game?.crossed?.isEmpty() == true } } private fun winBoard(vm: NonogramViewModel) { val g = vm.uiState.value.game!! for (i in g.puzzle.solution.indices.filter { g.puzzle.solution[it] }) vm.tapCell(i)- await("won") { vm.uiState.value.game?.isWon == true }+ awaitState("won", vm) { it.game?.isWon == true } } @Test fun nextLevelIgnoresAnUnsolvedBoard() { val vm = loadedVm() vm.nextLevel()- Thread.sleep(200)+ // No wait: nextLevel on an unsolved board returns synchronously+ // without launching any write (the isWon guard), so the level is+ // already settled on the next line. assertEquals(1, vm.uiState.value.level, "Next only exists on a solved board") assertEquals(1, blocking { vm.dataStore.currentLevel.first() }) }@@ -338,12 +312,13 @@ class NonogramViewModelTest { // complete before this thread's next line runs, which made that assert a coin flip. // The refusal is what the level assertions below prove.) vm.nextLevel()- await("level 2 loaded") {- vm.uiState.value.game?.level == 2 && !vm.uiState.value.generating+ awaitState("level 2 loaded", vm) {+ it.game?.level == 2 && !it.generating } // A late tap that lands on the fresh, unsolved board is ignored too. vm.nextLevel()- Thread.sleep(200)+ // As above, the late tap is a synchronous no-op on the unsolved+ // board, so the stored level is already terminal. assertEquals(2, blocking { vm.dataStore.currentLevel.first() }) assertEquals(2, vm.uiState.value.level) }@@ -352,14 +327,14 @@ class NonogramViewModelTest { val vm = loadedVm() winBoard(vm) vm.nextLevel()- await("level 2") { vm.uiState.value.level == 2 && vm.uiState.value.game != null && !vm.uiState.value.generating }+ awaitState("level 2", vm) { it.level == 2 && it.game != null && !it.generating } vm.setGameMode(GameMode.DAILY)- await("daily loads") { vm.uiState.value.mode == GameMode.DAILY && vm.uiState.value.game?.size == 10 }+ awaitState("daily loads", vm) { it.mode == GameMode.DAILY && it.game?.size == 10 } // nextLevel is a no-op in daily mode. vm.nextLevel() assertEquals(GameMode.DAILY, vm.uiState.value.mode) vm.setGameMode(GameMode.CASUAL)- await("back to casual") { vm.uiState.value.mode == GameMode.CASUAL && vm.uiState.value.game != null }+ awaitState("back to casual", vm) { it.mode == GameMode.CASUAL && it.game != null } } @Test fun winningBoardRecordsCompletionOnce() {@@ -369,8 +344,8 @@ class NonogramViewModelTest { val before = blocking { vm.dataStore.puzzlesCompleted.first() } val g = vm.uiState.value.game!! for (i in g.puzzle.solution.indices.filter { g.puzzle.solution[it] }) vm.tapCell(i)- await("won") { vm.uiState.value.game?.isWon == true }- await("completion recorded") { blocking { vm.dataStore.puzzlesCompleted.first() } == before + 1 }+ awaitState("won", vm) { it.game?.isWon == true }+ awaitStore("completion recorded") { vm.dataStore.puzzlesCompleted.first { it == before + 1 } } // Taps after game over are ignored. val hearts = vm.uiState.value.game!!.hearts vm.tapCell(g.puzzle.solution.indices.first { !g.puzzle.solution[it] })@@ -380,17 +355,17 @@ class NonogramViewModelTest { @Test fun winningDailyRecordsDailyWin() { val vm = loadedVm() vm.setGameMode(GameMode.DAILY)- await("daily ready") { vm.uiState.value.mode == GameMode.DAILY && vm.uiState.value.game != null && !vm.uiState.value.generating }+ awaitState("daily ready", vm) { it.mode == GameMode.DAILY && it.game != null && !it.generating } val before = blocking { vm.dataStore.puzzlesCompleted.first() } val g = vm.uiState.value.game!! for (i in g.puzzle.solution.indices.filter { g.puzzle.solution[it] }) vm.tapCell(i)- await("daily won") { vm.uiState.value.game?.isWon == true }- await("daily completion recorded") { blocking { vm.dataStore.puzzlesCompleted.first() } > before }+ awaitState("daily won", vm) { it.game?.isWon == true }+ awaitStore("daily completion recorded") { vm.dataStore.puzzlesCompleted.first { it > before } } // Let the rest of the win land before the test ends: the streak write reloads every live // ViewModel, and a store edit still in flight when Dispatchers.Main is reset would wait on // the paused Robolectric main looper and wedge the store for the following tests.- await("daily streak recorded") {- vm.uiState.value.dailyDone && vm.uiState.value.dailyStreak >= 1 && !vm.uiState.value.generating+ awaitState("daily streak recorded", vm) {+ it.dailyDone && it.dailyStreak >= 1 && !it.generating } } @@ -398,25 +373,22 @@ class NonogramViewModelTest { val vm = loadedVm() val before = vm.uiState.value.game!! vm.retryGeneration()- await("reload after retry") { !vm.uiState.value.generating && vm.uiState.value.game != null }+ awaitState("reload after retry", vm) { !it.generating && it.game != null } assertFalse(vm.uiState.value.generationFailed) assertEquals(before.puzzle, vm.uiState.value.game!!.puzzle) } @Test fun reminderActionsUpdateState() { val vm = loadedVm()- val enabledSeen = java.util.Collections.synchronizedList(mutableListOf<Boolean>())- val minutesSeen = java.util.Collections.synchronizedList(mutableListOf<Long>())- val scope = kotlinx.coroutines.CoroutineScope(Dispatchers.Unconfined)- val j1 = scope.launch { vm.reminderEnabled.collect { enabledSeen += it } }- val j2 = scope.launch { vm.reminderMinutesOfDay.collect { minutesSeen += it } }+ // Wait on the reminder StateFlows themselves: each first{} below+ // subscribes (starting the WhileSubscribed upstream) and is resumed+ // by the terminal emission, with no collector lists to poll. vm.setReminderEnabled(true)- await("reminder on") { enabledSeen.contains(true) }+ awaitValueBlocking(vm.reminderEnabled) { it } vm.setReminderTime(7, 30)- await("reminder time") { minutesSeen.contains(450L) }+ awaitValueBlocking(vm.reminderMinutesOfDay) { it == 450L } vm.setReminderEnabled(false)- await("reminder off") { enabledSeen.lastOrNull() == false }- j1.cancel(); j2.cancel()+ awaitValueBlocking(vm.reminderEnabled) { !it } } @Test fun contractDefaultsAndNoop() {@@ -434,11 +406,14 @@ class NonogramViewModelTest { @Test fun achievementsManagerBackfillDoesNotCrash() { val vm = loadedVm() vm.achievementsManager.checkExistingAchievements()- // checkExistingAchievements launches on Dispatchers.IO; asserting- // its unlocks synchronously raced that work and lost under load.- await("backfill unlocks land") {- vm.achievementsManager.achievements.any { it.id == "first_puzzle" } &&- vm.achievementsManager.achievements.any { it.id == "daily_streak_30" }+ // checkExistingAchievements launches on Dispatchers.IO; wait for+ // its terminal effect on the statuses flow (first_puzzle unlocked+ // from the stored completion count) instead of asserting — or+ // polling — the static achievement catalogue.+ awaitStore("backfill unlocks land") {+ vm.achievementsManager.getAchievementStatuses().first { statuses ->+ statuses.any { it.achievement.id == "first_puzzle" && it.isUnlocked }+ } } assertTrue(vm.achievementsManager.achievements.any { it.id == "first_puzzle" }) assertTrue(vm.achievementsManager.achievements.any { it.id == "daily_streak_30" })
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.ktindex 3e0e06a3c5..ec73a8e3a0 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt@@ -42,6 +42,7 @@ import androidx.compose.foundation.layout.size import androidx.compose.ui.unit.dp import kotlin.test.Test import kotlin.test.assertEquals+import com.vayunmathur.testsupport.awaitSemantics import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class)@@ -351,8 +352,10 @@ class NonogramScreensTest { // which the real VM's collectors run on) instead of asserting // the first frame: under load the first composition lands // late and the immediate assert raced it.- rule.waitUntil(15_000) {- org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ // Semantics wait on the terminal node (the Settings title),+ // idling the paused main looper on every check so the real+ // VM's collectors can land (shared helper, no wall-clock poll).+ rule.awaitSemantics("settings title") { rule.onAllNodesWithText(str(UiR.string.settings)).fetchSemanticsNodes().isNotEmpty() } rule.onNodeWithText(str(UiR.string.settings)).assertExists()
share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.ktindex 292833cd23..6b02bbd67b 100644--- a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt@@ -112,6 +112,14 @@ class ShareReceiveNotifier( context: Context, private val incoming: Flow<List<IncomingTransfer>>, private val retire: (Long) -> Unit,+ /**+ * Called with the session handle after a notification for it has+ * been posted (request, progress, done or failed). A terminal-state+ * signal for observers — notably tests — that need to know a post+ * landed instead of polling the notification shade. Default no-op+ * keeps production wiring unchanged.+ */+ private val onNotificationPosted: (Long) -> Unit = {}, ) { private val appContext = context.applicationContext private var job: Job? = null@@ -241,12 +249,14 @@ class ShareReceiveNotifier( if (kind == Kind.Done || kind == Kind.Failed) { synchronized(idLock) { terminalPosted += handle } notify(id, notification)+ onNotificationPosted(handle) // The user has been told the outcome, so the session has no remaining reader. // Nothing else disconnects an incoming session. retire(handle) return } notify(id, notification)+ onNotificationPosted(handle) } private fun notify(id: Int, notification: android.app.Notification) {
share/src/test/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifierTest.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifierTest.kt b/share/src/test/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifierTest.ktindex ef1e5bcf4d..96225b2213 100644--- a/share/src/test/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifierTest.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifierTest.kt@@ -13,9 +13,9 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel-import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue@@ -40,15 +40,12 @@ class ShareReceiveNotifierTest { override val error = MutableStateFlow<String?>(null) } - /** Polls [cond] in real time: the notifier collects on Dispatchers.Default, so a fixed delay is a bet on CI load, not a wait for the outcome. */- private suspend fun awaitShareCondition(cond: () -> Boolean): Boolean {- val deadline = System.currentTimeMillis() + 15_000- while (System.currentTimeMillis() < deadline) {- if (cond()) return true- delay(25)- }- return cond()- }+ // Terminal signals, not polls: `retire` is the notifier's own+ // callback (fired after the terminal notification posts), and+ // `onNotificationPosted` is its post seam. Awaiting the channel /+ // deferred below is resumed by the notifier's work on+ // Dispatchers.Default; the old helper polled a condition against a+ // 15s System.currentTimeMillis deadline, betting on CI load. @Test fun `notifier posts request then done and retires`() = runBlocking {@@ -56,22 +53,35 @@ class ShareReceiveNotifierTest { fake.pendingFiles.value = listOf(PendingFile("a.txt", 100, "text/plain")) fake.expectedTotalBytes.value = 100 val incoming = MutableStateFlow<List<IncomingTransfer>>(listOf(fake))- val retired = java.util.Collections.synchronizedList(mutableListOf<Long>())+ val retired = Channel<Long>(Channel.UNLIMITED)+ val requestPosted = kotlinx.coroutines.CompletableDeferred<Long>() val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)- val notifier = ShareReceiveNotifier(ctx, incoming, retire = { retired += it })+ val notifier = ShareReceiveNotifier(+ ctx, incoming,+ retire = { retired.trySend(it) },+ onNotificationPosted = { handle ->+ if (!requestPosted.isCompleted) requestPosted.complete(handle)+ },+ ) try { notifier.start(scope) fake.state.value = ShareState.AwaitingAccept+ // Suspend until the request notification has actually posted:+ // only then is it safe to advance the state, because the+ // notifier conflates and could otherwise skip the request.+ assertEquals(12345L, requestPosted.await()) val nm = ctx.getSystemService<NotificationManager>()!! assertTrue( "expected a posted notification",- awaitShareCondition { Shadows.shadowOf(nm).allNotifications.isNotEmpty() },+ Shadows.shadowOf(nm).allNotifications.isNotEmpty(), ) fake.state.value = ShareState.Completed fake.receivedFiles.value = listOf(ReceivedFile("a.txt", 100, "text/plain", Uri.parse("content://x/a")))- assertTrue(- "retire should be called for terminal state, retired=$retired",- awaitShareCondition { retired.contains(12345L) },+ // Retire fires after the Done notification posts, so this+ // receive is a wait on the terminal state itself.+ assertEquals(+ "retire should be called for terminal state",+ 12345L, retired.receive(), ) } finally { notifier.stop(); scope.cancel()@@ -90,13 +100,13 @@ class ShareReceiveNotifierTest { val fake = FakeTransfer(777L) fake.error.value = "handshake broke" val incoming = MutableStateFlow<List<IncomingTransfer>>(listOf(fake))- val retired = java.util.Collections.synchronizedList(mutableListOf<Long>())+ val retired = Channel<Long>(Channel.UNLIMITED) val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)- val notifier = ShareReceiveNotifier(ctx, incoming, retire = { retired += it })+ val notifier = ShareReceiveNotifier(ctx, incoming, retire = { retired.trySend(it) }) try { notifier.start(scope) fake.state.value = ShareState.Failed- assertTrue(awaitShareCondition { retired.contains(777L) })+ assertEquals(777L, retired.receive()) } finally { notifier.stop(); scope.cancel() } } }
taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.ktindex 59175c39dc..1cf5e734b9 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt@@ -1,6 +1,7 @@ package com.vayunmathur.taxi.data.lyft import android.content.Context+import com.vayunmathur.library.log.Log import com.vayunmathur.taxi.network.lyft.LyftToken import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.longPreferencesKey@@ -10,17 +11,43 @@ import kotlinx.coroutines.flow.first private val Context.lyftDataStore by preferencesDataStore(name = "lyft_session") -/** Lyft Token Store: a context implementation for lyft token store. */+/**+ * Lyft token persistence — the single choke point for Lyft secrets in this app.+ *+ * Access and refresh tokens are stored Keystore-sealed (see [KeystoreTokenSealer]):+ * only ciphertext reaches the DataStore file. Backup is already deny-all for this+ * app, and sealing additionally keeps the tokens useless if the file is ever copied+ * off-device. A sealed value that no longer decrypts reads as signed-out. Legacy+ * plaintext tokens from before sealing are used once and rewritten sealed on read.+ * The user id is not a secret and stays plain.+ */ class LyftTokenStore(private val context: Context) { private val accessKey = stringPreferencesKey("access_token") private val refreshKey = stringPreferencesKey("refresh_token") private val expiresAtKey = longPreferencesKey("expires_at") private val userIdKey = stringPreferencesKey("user_id") + private val defaultSealer by lazy { KeystoreTokenSealer(KEY_ALIAS) }++ private fun activeSealer(): TokenSealer = sealerForTest ?: defaultSealer+ suspend fun save(token: LyftToken) {+ // Seal before touching the store: never persist a token in plaintext, and+ // keep the previous value rather than a half-written session on seal failure.+ val sealedAccess = activeSealer().seal(token.accessToken)+ if (sealedAccess == null) {+ Log.error(TAG, "Sealing failed; Lyft access token not persisted")+ return+ }+ val sealedRefresh = token.refreshToken?.takeIf { it.isNotBlank() }?.let { plain ->+ activeSealer().seal(plain) ?: run {+ Log.error(TAG, "Sealing failed; Lyft refresh token not persisted")+ return+ }+ } context.lyftDataStore.edit {- it[accessKey] = token.accessToken- if (!token.refreshToken.isNullOrBlank()) it[refreshKey] = token.refreshToken+ it[accessKey] = sealedAccess+ if (sealedRefresh != null) it[refreshKey] = sealedRefresh it[expiresAtKey] = System.currentTimeMillis() + token.expiresIn * MILLIS_PER_SECOND if (!token.userId.isNullOrBlank()) it[userIdKey] = token.userId }@@ -34,11 +61,31 @@ class LyftTokenStore(private val context: Context) { null } - suspend fun accessToken(): String? =- prefs()?.get(accessKey)?.takeIf { it.isNotBlank() }+ /**+ * Unseals a stored token: legacy plaintext passes through and is rewritten+ * sealed (verified against the value just read, inside the edit); an+ * undecryptable sealed value yields null — signed-out, never a crash.+ */+ private suspend fun unsealOrMigrate(+ key: androidx.datastore.preferences.core.Preferences.Key<String>,+ raw: String?,+ ): String? {+ val stored = raw?.takeIf { it.isNotBlank() } ?: return null+ val plain = activeSealer().unseal(stored) ?: return null+ if (!activeSealer().isSealed(stored)) {+ val sealed = activeSealer().seal(plain)+ if (sealed != null) {+ context.lyftDataStore.edit { prefs ->+ if (prefs[key] == stored) prefs[key] = sealed+ }+ }+ }+ return plain.takeIf { it.isNotBlank() }+ }++ suspend fun accessToken(): String? = unsealOrMigrate(accessKey, prefs()?.get(accessKey)) - suspend fun refreshToken(): String? =- prefs()?.get(refreshKey)?.takeIf { it.isNotBlank() }+ suspend fun refreshToken(): String? = unsealOrMigrate(refreshKey, prefs()?.get(refreshKey)) suspend fun userId(): String? = prefs()?.get(userIdKey) @@ -54,7 +101,13 @@ class LyftTokenStore(private val context: Context) { context.lyftDataStore.edit { it.clear() } } - private companion object {+ companion object {+ private const val KEY_ALIAS = "taxi_lyft_token_key"+ private const val TAG = "LyftTokenStore"++ /** Test seam: Robolectric has no AndroidKeyStore; tests install a fake sealer here. */+ internal var sealerForTest: TokenSealer? = null+ private const val MILLIS_PER_SECOND = 1000L /** How early before real expiry the token counts as expired, so a call never races it. */ private const val EXPIRY_SKEW_MS = 60_000L
taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.ktindex 60e68d4f89..ea38f8d19e 100644--- a/taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.kt+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.kt@@ -49,8 +49,15 @@ class LyftClientsDeepTest { LyftTokenStore(context).save(LyftToken(accessToken = "access-tok", refreshToken = "rt", expiresIn = 3600, userId = "42")) } - @BeforeTest fun setUp() { http.install(); runBlocking { LyftTokenStore(context).clear() } }- @AfterTest fun tearDown() { http.uninstall(); runBlocking { LyftTokenStore(context).clear() } }+ @BeforeTest fun setUp() {+ // Robolectric has no AndroidKeyStore; seal with the fake (contract-identical) sealer.+ LyftTokenStore.sealerForTest = com.vayunmathur.taxi.data.lyft.FakeTokenSealer()+ http.install(); runBlocking { LyftTokenStore(context).clear() }+ }+ @AfterTest fun tearDown() {+ http.uninstall(); runBlocking { LyftTokenStore(context).clear() }+ LyftTokenStore.sealerForTest = null+ } private val offersJson = """{"offers":{"purchase_session_id":"ps1","offers_response_id":"or1","offers_list":[ {"offer_product_id":"lyft","id":"o1","cost_estimate":{"ride_type":"Lyft","currency":"USD","estimated_cost_cents_min":500,"estimated_cost_cents_max":900},
taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.ktindex 4acd9a1f03..f9c09014cd 100644--- a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.kt+++ b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.kt@@ -81,6 +81,7 @@ class TaxiPass3ScreensTest { @BeforeTest fun setUp() {+ LyftTokenStore.sealerForTest = com.vayunmathur.taxi.data.lyft.FakeTokenSealer() http.install() runBlocking { LyftTokenStore(context).clear()@@ -95,6 +96,7 @@ class TaxiPass3ScreensTest { LyftTokenStore(context).clear() UberSession(context).clear() }+ LyftTokenStore.sealerForTest = null } private fun seedSignedIn() = runBlocking {
taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.ktindex 342aa4436f..8d902323b8 100644--- a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.kt+++ b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.kt@@ -41,6 +41,7 @@ class TaxiPass3TrackingScreenTest { @BeforeTest fun setUp() {+ LyftTokenStore.sealerForTest = com.vayunmathur.taxi.data.lyft.FakeTokenSealer() http.install() runBlocking { LyftTokenStore(context).save(@@ -53,6 +54,7 @@ class TaxiPass3TrackingScreenTest { fun tearDown() { http.uninstall() runBlocking { LyftTokenStore(context).clear() }+ LyftTokenStore.sealerForTest = null } private fun waitForText(text: String, timeoutMs: Long = 20_000) {
web/src/main/java/com/vayunmathur/web/platform/PwaBrowser.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/PwaBrowser.kt b/web/src/main/java/com/vayunmathur/web/platform/PwaBrowser.ktindex 135967f1a6..8c33d86d4b 100644--- a/web/src/main/java/com/vayunmathur/web/platform/PwaBrowser.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/PwaBrowser.kt@@ -321,8 +321,12 @@ private fun applyPwaWebSettings(webView: WebView, ctx: Context) { settings.domStorageEnabled = true settings.databaseEnabled = true settings.cacheMode = WebSettings.LOAD_DEFAULT- settings.allowFileAccess = true- settings.allowContentAccess = true+ // Installed sites are https web apps (see WebViewSettings): no feature+ // loads file:// or content:// into the page, and file-chooser uploads+ // return content URIs via onShowFileChooser without these. With JS on,+ // file/content access would let a compromised PWA origin read local files.+ settings.allowFileAccess = false+ settings.allowContentAccess = false settings.offscreenPreRaster = true settings.setSupportZoom(true) settings.builtInZoomControls = true
web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.kt b/web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.ktindex 088405ba72..fb234c0f22 100644--- a/web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.kt@@ -76,8 +76,13 @@ internal fun applyWebViewSettings(webView: WebView, viewModel: WebViewModel) { // HTTP cache — user selectable for speed / offline settings.cacheMode = viewModel.cacheMode.webSettingsValue - settings.allowFileAccess = true- settings.allowContentAccess = true+ // No local-file browsing: programmatic loads are http(s)/about:blank-gated+ // (BrowserUtils.canLoadInWebView) and no web feature loads file:// or+ // content:// into the page. File-chooser uploads hand content URIs back+ // via WebChromeClient.onShowFileChooser, which does not need these.+ // With JS enabled, file/content access would let a page read local files.+ settings.allowFileAccess = false+ settings.allowContentAccess = false // Offscreen pre-raster speeds first paint settings.offscreenPreRaster = true@@ -88,8 +93,12 @@ internal fun applyWebViewSettings(webView: WebView, viewModel: WebViewModel) { settings.useWideViewPort = true settings.loadWithOverviewMode = true - // Aggressive shields refuse plaintext subresources outright; otherwise stay permissive- // so pages with a few http:// images still render.+ // Shields owns the mixed-content decision (do not hardcode NEVER_ALLOW+ // here): httpsOnly is httpsUpgrade && AGGRESSIVE, and the shipped default+ // preset is AGGRESSIVE_DEFAULTS, so the default resolves to NEVER_ALLOW.+ // A user who lowers a site/global to the non-aggressive STANDARD preset+ // (httpsOnly=false) deliberately opts into COMPATIBILITY_MODE so pages+ // with a few http:// images still render. val globalShields = com.vayunmathur.web.domain.EffectiveShields.resolve(viewModel.shields) settings.mixedContentMode = if (globalShields.httpsOnly) { WebSettings.MIXED_CONTENT_NEVER_ALLOW