communicate: self-guard the tap-adjacent E2E paths
- Commit
b2a6dd83792f63e0668e7c6190547f12d5abec58- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-20 19:41 UTC (15 days ago)
- Parents
489f16f
An audit proved communicate's E2E runBlocking bridges are only
reached from IO today, but two user-tap-adjacent paths relied on
every caller remembering Dispatchers.IO: SignalClient
safetyNumber()/acceptIdentityChange() hit the protocol store
(runBlocking inside) with no shift of their own. Both now wrap
in withContext(Dispatchers.IO).
WhatsAppClient.init() also ran runBlocking{ auth load } and
markRegistered is called from the registration screens on a
Main rememberCoroutineScope, blocking sign-in briefly. The
saved-auth load now runs on the client's IO scope behind an
awaitInitAuth() join; session init and markRegistered suspend
on it, so registration still waits for the load - just not on
the main thread.
Verified: :communicate:testDevUnitTest 1954 tests, 0 failures.Diff
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalIdentity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalIdentity.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalIdentity.ktindex f7658b8a38..c580b91300 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalIdentity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalIdentity.kt@@ -3,7 +3,9 @@ package com.vayunmathur.communicate.data.signal import com.vayunmathur.library.log.Log import com.vayunmathur.communicate.data.signal.e2e.acceptIdentity import com.vayunmathur.communicate.data.signal.e2e.storedIdentityKey+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import org.signal.libsignal.protocol.IdentityKey import org.whispersystems.signalservice.internal.push.SignalServiceProtos @@ -51,11 +53,13 @@ fun SignalClient.pendingIdentityChange(peerAci: String): ByteArray? = pendingIde * The safety number to show for [peerAci] — for the key they are currently presenting when that * differs from the one on record, otherwise for the accepted one. Null when it cannot be computed. */-suspend fun SignalClient.safetyNumber(peerAci: String): String? {- val e = e2e ?: return null- val localAci = authData?.aci?.takeIf { it.isNotEmpty() } ?: return null- val remoteKey = pendingIdentityChanges[peerAci] ?: e.storedIdentityKey(peerAci) ?: return null- return SignalSafetyNumber.compute(+suspend fun SignalClient.safetyNumber(peerAci: String): String? = withContext(Dispatchers.IO) {+ // protocolStore hits Room via runBlocking inside, so self-guard on IO:+ // callers may invoke this from any dispatcher (incl. Main-adjacent scopes).+ val e = e2e ?: return@withContext null+ val localAci = authData?.aci?.takeIf { it.isNotEmpty() } ?: return@withContext null+ val remoteKey = pendingIdentityChanges[peerAci] ?: e.storedIdentityKey(peerAci) ?: return@withContext null+ SignalSafetyNumber.compute( localAci = localAci, localIdentityKey = e.ownIdentityPublicKeySerialized, remoteAci = peerAci,@@ -70,23 +74,26 @@ suspend fun SignalClient.safetyNumber(peerAci: String): String? { * whose safety number was actually shown — otherwise a key swapped in between display and tap would * be trusted instead. Existing sessions are archived so the next send builds against the new key. */-suspend fun SignalClient.acceptIdentityChange(peerAci: String, expectedKeyHex: String): Boolean {- val e = e2e ?: return false- val pending = pendingIdentityChanges[peerAci] ?: run {- Log.status(TAG, "no pending identity change for $peerAci")- return false- }- if (!SignalGroups.run { pending.toHex() }.equals(expectedKeyHex, ignoreCase = true)) {- Log.status(TAG, "refusing to accept a different key than the one shown for $peerAci")- return false+suspend fun SignalClient.acceptIdentityChange(peerAci: String, expectedKeyHex: String): Boolean =+ withContext(Dispatchers.IO) {+ // protocolStore hits Room via runBlocking inside, so self-guard on IO+ // (see safetyNumber); double-shifting an already-IO caller is harmless.+ val e = e2e ?: return@withContext false+ val pending = pendingIdentityChanges[peerAci] ?: run {+ Log.status(TAG, "no pending identity change for $peerAci")+ return@withContext false+ }+ if (!SignalGroups.run { pending.toHex() }.equals(expectedKeyHex, ignoreCase = true)) {+ Log.status(TAG, "refusing to accept a different key than the one shown for $peerAci")+ return@withContext false+ }+ val accepted = e.acceptIdentity(peerAci, pending)+ if (accepted) {+ pendingIdentityChanges.remove(peerAci)+ Log.status(TAG, "accepted the new identity key for $peerAci")+ }+ accepted }- val accepted = e.acceptIdentity(peerAci, pending)- if (accepted) {- pendingIdentityChanges.remove(peerAci)- Log.status(TAG, "accepted the new identity key for $peerAci")- }- return accepted-} /** * Associate a sender's ACI with the PNI we already knew them by, when they prove the link.
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.ktindex 7fb43dc42f..d3f482a5f7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt@@ -32,7 +32,6 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch-import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull /** The WhatsApp primary client: owns the socket, E2E stores and event stream for the WhatsApp line. */@@ -165,13 +164,22 @@ object WhatsAppClient { // Pages requested per chat, to bound pagination (see MAX_ON_DEMAND_PAGES_PER_CHAT). internal val onDemandPageCount = ConcurrentHashMap<String, Int>() + // The one-shot saved-auth load launched by init(); joinable so a suspend+ // caller (registration) can wait for it without blocking its own thread.+ @Volatile+ private var initAuthJob: Job? = null+ fun init(context: Context) { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext as Application db = WhatsAppDatabase.getDatabase(appContext) WhatsAppCallManager.init(appContext, callBridge) Log.status(TAG, "init")- runBlocking {+ // Load saved auth off the caller's thread: init() is reachable from+ // Main-adjacent registration scopes, and SharedPreferences + JSON+ // decode must not block there. State/authData land asynchronously;+ // suspend callers that must observe them use awaitInitAuth().+ initAuthJob = scope.launch { val auth = WhatsAppAuthData.load(appContext) if (auth != null) { authData = auth@@ -183,6 +191,11 @@ object WhatsAppClient { } } + /** Wait (suspending, never blocking) until init()'s saved-auth load has landed. */+ internal suspend fun awaitInitAuth() {+ initAuthJob?.join()+ }+ fun start() { if (!initialized.load()) return // Only skip if fully connected. (Connecting is intentionally NOT skipped: a stale/stuck
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.ktindex 1ffe36b3c5..d68ef256fd 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.kt@@ -3,9 +3,11 @@ package com.vayunmathur.communicate.data.whatsapp import android.content.Context import com.vayunmathur.communicate.data.whatsapp.registration.WhatsAppDeviceFingerprint import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.map+import kotlinx.coroutines.withContext /** * Session facade for the WhatsApp primary line, mirroring [GoogleVoiceSession]'s shape so the UI and@@ -45,9 +47,12 @@ class WhatsAppLineSession private constructor( * Initialize + connect the primary client if we have usable credentials. Safe to call repeatedly * (WhatsAppClient.init is idempotent). Call from the sync service / MainActivity. */- fun init(context: Context) {+ suspend fun init(context: Context) { WhatsAppClient.init(context.applicationContext)- if (hasUsableCredentials(context)) {+ // Suspend until the saved-auth load lands (on IO, never blocking the+ // caller), preserving the old synchronous-init ordering.+ WhatsAppClient.awaitInitAuth()+ if (withContext(Dispatchers.IO) { hasUsableCredentials(context) }) { WhatsAppClient.start() } }@@ -57,6 +62,10 @@ class WhatsAppLineSession private constructor( store.setString(KEY_PHONE_NUMBER, auth.phoneNumber) store.setBoolean(KEY_SIGNED_IN, true) WhatsAppClient.init(context.applicationContext)+ // Registration still waits for init's saved-auth load before+ // proceeding (incl. the caller's onVerified), just not on Main:+ // this suspends on the client's IO scope instead of runBlocking.+ WhatsAppClient.awaitInitAuth() WhatsAppClient.start() }
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y3AppStatePageTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y3AppStatePageTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y3AppStatePageTest.ktindex a6f06610af..0eefc0f6b8 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y3AppStatePageTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y3AppStatePageTest.kt@@ -451,6 +451,8 @@ class Y3AppStatePageTest { try { setInitialized(false) WhatsAppClient.init(app)+ // Saved auth loads asynchronously off the calling thread; await it.+ runBlocking { WhatsAppClient.awaitInitAuth() } // Saved auth: the client arms the network monitor and starts connecting. assertEquals(WhatsAppClient.State.Connecting, WhatsAppClient.stateMutable.value) assertEquals(AUTH.wid, WhatsAppClient.authData?.wid)