Modern Apps git

← Modern-Apps.git

communicate: Signal - send retry receipts so a broken session recovers

Commit
f79fb0d74b44a1af367866f9e2db7c4c4ff3b366
Author
vayun-mathur <[email protected]>
When
2026-08-22 21:33 UTC (3 months ago)
Parents
e9d3a35

Diff

communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.ktindex 1c76dc1fee..c5f8016b99 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt@@ -15,6 +15,8 @@ import com.vayunmathur.communicate.data.signal.transport.SignalSocket import com.vayunmathur.communicate.data.signal.transport.SignalTrust import org.signal.libsignal.metadata.certificate.SenderCertificate import org.signal.libsignal.protocol.UntrustedIdentityException+import org.signal.libsignal.protocol.message.DecryptionErrorMessage+import org.signal.libsignal.protocol.message.PlaintextContent import com.vayunmathur.library.network.NetworkClient import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -306,21 +308,40 @@ object SignalClient {      * Seed our own pre-keys into the protocol store and register anything the server does not yet have.      * Runs once per start; without it a peer's first message cannot be decrypted.      */+    /**+     * Seed our own pre-keys into the protocol store and register anything the server does not yet have.+     *+     * After seeding, our stored signed pre-key is checked against the bundle the server actually hands+     * out. That is the only authoritative comparison: senders encrypt to the server's copy, so if it+     * differs from ours every inbound pre-key message fails in the key agreement with an error that names+     * neither half. A mismatch is repaired by rotating and re-registering.+     */     private suspend fun ensureLocalPreKeys() {         if (!preKeysPrepared.compareAndSet(false, true)) return         val e = e2e ?: run {             preKeysPrepared.set(false)             return         }-        val upload = try {+        var upload = try {             e.ensureLocalPreKeys()         } catch (t: Throwable) {             preKeysPrepared.set(false)             Log.w(TAG, "could not prepare local pre-keys", t)             return         }++        if (upload.signedPreKey == null && !signedPreKeyMatchesServer(e)) {+            upload = try {+                upload.copy(signedPreKey = e.rotateSignedPreKeyNow())+            } catch (t: Throwable) {+                Log.w(TAG, "could not rotate the signed pre-key", t)+                upload+            }+        }+         if (upload.isEmpty) return         val ok = SignalKeysApi.uploadPreKeys(+            signedPreKey = upload.signedPreKey,             lastResortKyber = upload.lastResortKyber,             oneTimeEcPreKeys = upload.oneTimeEcPreKeys,             authHeader = basicAuthHeader(),@@ -334,6 +355,46 @@ object SignalClient {         }     } +    /**+     * Whether the signed pre-key the server serves for us is one we hold the private half of. Returns true+     * when it cannot be checked, so a network problem does not trigger a needless rotation.+     */+    private suspend fun signedPreKeyMatchesServer(e: SignalE2E): Boolean {+        val ourAci = authData?.aci?.takeIf { it.isNotEmpty() } ?: return true+        val bundles = try {+            SignalKeysApi.fetchPreKeys(ourAci, authData?.deviceId ?: PRIMARY_DEVICE_ID, basicAuthHeader(), signalTls())+        } catch (t: Throwable) {+            Log.i(TAG, "could not fetch our own bundle to verify the signed pre-key", t)+            return true+        }+        val ours = bundles.firstOrNull { it.deviceId == (authData?.deviceId ?: PRIMARY_DEVICE_ID) }+        if (ours == null) {+            Log.w(TAG, "the server has no bundle for our own device ${authData?.deviceId}")+            return true+        }+        val signedMatches = e.hasSignedPreKeyMatching(ours.bundle.signedPreKeyId, ours.bundle.signedPreKeyPublic)+        // The identity key is the other half of what a sender binds to; a mismatch here breaks every+        // inbound message and cannot be repaired by rotating pre-keys.+        val identityMatches = ours.bundle.identityKey.contentEquals(e.ownIdentityPublicKey)+        Log.i(+            TAG,+            "own bundle check: signedPreKeyId=${ours.bundle.signedPreKeyId} signedMatches=$signedMatches " ++                "identityMatches=$identityMatches kyberPreKeyId=${ours.bundle.kyberPreKeyId} " ++                "hasOneTime=${ours.bundle.preKeyId != null}",+        )+        if (!identityMatches) {+            Log.e(+                TAG,+                "our registered identity key differs from the one we hold; inbound messages cannot decrypt " ++                    "and re-registration is required",+            )+        }+        if (!signedMatches) {+            Log.w(TAG, "the server serves signed pre-key ${ours.bundle.signedPreKeyId} that we cannot use; rotating")+        }+        return signedMatches+    }+     /** Guards against overlapping discovery runs; `start()` can fire more than once. */     private val discoveryRunning = AtomicBoolean(false) @@ -1427,6 +1488,8 @@ object SignalClient {         } catch (t: Throwable) {             Log.w(TAG, "decrypt failed for ${env.sourceAci}:${env.sourceDevice}", t)             emitDecryptionError(env, t.message)+            // Ask the sender to rebuild the session; otherwise this fails identically forever.+            if (env.type != SignalServiceProtos.Envelope.Type.PLAINTEXT_CONTENT) sendRetryReceipt(env)             // Redelivery cannot fix a decrypt failure, so ack rather than spin on it.             return true         }@@ -1592,6 +1655,52 @@ object SignalClient {         return true     } +    /**+     * Tell [env]'s sender that we could not decrypt, so they rebuild the session.+     *+     * This is the protocol's recovery path: a `DecryptionErrorMessage` in a plaintext envelope makes the+     * sender archive their session and fetch a fresh pre-key bundle. Without it a session that has drifted+     * — for instance because our Kyber pre-key was replaced — stays broken forever, with every retry+     * failing identically.+     *+     * Sent unencrypted by design; `PLAINTEXT_CONTENT` is the one envelope type that may be, and it may+     * carry nothing but this.+     */+    private suspend fun sendRetryReceipt(env: SignalProtocol.SignalEnvelope) {+        val e = e2e ?: return+        val sender = env.sourceAci.takeIf { it.isNotEmpty() } ?: return+        if (env.content.isEmpty()) return+        try {+            val errorMessage = DecryptionErrorMessage.forOriginalMessage(+                env.content,+                env.type.number,+                env.timestamp,+                env.sourceDevice,+            )+            val body = PlaintextContent(errorMessage).serialize()+            // Their next message builds a new session, so drop ours rather than keep a chain they abandoned.+            e.archiveSession(sender, env.sourceDevice)+            val message = SignalPayload.OutgoingPushMessage(+                type = SignalServiceProtos.Envelope.Type.PLAINTEXT_CONTENT.number,+                destinationDeviceId = env.sourceDevice,+                destinationRegistrationId = 0,+                content = body,+            )+            val json = SignalPayload.buildPutMessagesBody(+                destinationAci = sender,+                messages = listOf(message),+                timestamp = System.currentTimeMillis(),+                urgent = false,+            )+            when (val outcome = putMessages(sender, json, accessKey = null)) {+                is SendOutcome.Success -> Log.i(TAG, "sent a retry receipt to $sender:${env.sourceDevice}")+                else -> Log.w(TAG, "could not send a retry receipt to $sender: $outcome")+            }+        } catch (t: Throwable) {+            Log.w(TAG, "could not build a retry receipt for $sender", t)+        }+    }+     private suspend fun emitDecryptionError(env: SignalProtocol.SignalEnvelope, message: String?) {         val cid = SignalProtocol.toConversationId(env.sourceAci, null as ByteArray?)         _events.emit(
communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.ktindex 0473027c6c..dae3b8ca1e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.kt@@ -312,12 +312,14 @@ class SignalE2E(      * Keys are the serialized public halves; signatures are over those, by our identity key.      */     data class PreKeyUpload(+        val signedPreKey: KeyEntity?,         val lastResortKyber: KeyEntity?,         val oneTimeEcPreKeys: List<KeyEntity>,     ) {         data class KeyEntity(val id: Int, val publicKey: ByteArray, val signature: ByteArray? = null) -        val isEmpty: Boolean get() = lastResortKyber == null && oneTimeEcPreKeys.isEmpty()+        val isEmpty: Boolean+            get() = signedPreKey == null && lastResortKyber == null && oneTimeEcPreKeys.isEmpty()     }      /**@@ -325,41 +327,98 @@ class SignalE2E(      * to decrypt. Registration only wrote them to preferences, so without this a first message from a      * peer fails with `InvalidKeyIdException: no signed pre-key <id>`.      *-     * The signed pre-key is reconstructed from the stored key material so it keeps the id the server-     * already hands out. A Kyber pre-key cannot be reconstructed — libsignal only exposes-     * `KEMKeyPair.generate()`, with no way back from persisted bytes — so a fresh one is generated and-     * must be registered, which is what the returned payload is for.+     * Stored material is reused only when it verifies against itself — the private half must derive the+     * public half, and the signature must check out under our identity key. Anything that fails is+     * regenerated and re-registered, because a key the server serves but we cannot use produces a+     * decryption failure with no way to tell from the error which half was wrong.+     *+     * A Kyber pre-key is always regenerated: libsignal only exposes `KEMKeyPair.generate()`, with no path+     * back from persisted bytes.      */     fun ensureLocalPreKeys(): PreKeyUpload {-        seedSignedPreKey()+        val signed = ensureSignedPreKey()         val kyber = ensureLastResortKyberPreKey()         val oneTime = ensureOneTimePreKeys()-        return PreKeyUpload(lastResortKyber = kyber, oneTimeEcPreKeys = oneTime)+        return PreKeyUpload(signedPreKey = signed, lastResortKyber = kyber, oneTimeEcPreKeys = oneTime)+    }++    /** Whether our store holds a signed pre-key [id] whose public half is exactly [publicKey]. */+    fun hasSignedPreKeyMatching(id: Int, publicKey: ByteArray?): Boolean {+        if (publicKey == null) return true+        return try {+            val record = protocolStore.loadSignedPreKey(id)+            record.keyPair.publicKey.serialize().contentEquals(publicKey)+        } catch (_: Throwable) {+            false+        }+    }++    /** Rotate the signed pre-key regardless of what is stored, for when the server's copy is unusable. */+    fun rotateSignedPreKeyNow(): PreKeyUpload.KeyEntity? = rotateSignedPreKey()++    /**+     * Returns a payload when the signed pre-key had to be regenerated and needs registering, null when the+     * stored one was sound and simply seeded.+     */+    private fun ensureSignedPreKey(): PreKeyUpload.KeyEntity? {+        val storedId = auth.signedPreKeyId+        if (storedId != 0 && protocolStore.containsSignedPreKey(storedId)) return null+        if (storedId != 0 && seedStoredSignedPreKey(storedId)) return null+        return rotateSignedPreKey()     } -    private fun seedSignedPreKey() {-        val id = auth.signedPreKeyId-        if (id == 0) return-        if (protocolStore.containsSignedPreKey(id)) return+    /** True when the stored material verified and was seeded into the store. */+    private fun seedStoredSignedPreKey(id: Int): Boolean {         val pub = b64(auth.signedPreKeyPublic)         val priv = b64(auth.signedPreKeyPrivate)         val signature = b64(auth.signedPreKeySignature)         if (pub.isEmpty() || priv.isEmpty()) {-            Log.w(TAG, "no stored signed pre-key material; inbound pre-key messages will not decrypt")-            return+            Log.w(TAG, "no stored signed pre-key material; rotating")+            return false         }-        try {-            val keyPair = ECKeyPair(ECPublicKey(pub), ECPrivateKey(priv))+        return try {+            val privateKey = ECPrivateKey(priv)+            val derived = privateKey.getPublicKey().serialize()+            if (!derived.contentEquals(pub)) {+                // The server serves the public half; without the matching private half every inbound+                // pre-key message fails in the key agreement rather than at lookup.+                Log.w(TAG, "stored signed pre-key $id is inconsistent (private half derives a different public key); rotating")+                return false+            }+            val identityOk = signature.isNotEmpty() &&+                ECPublicKey(ownIdentityPublicKey).verifySignature(pub, signature)+            if (!identityOk) {+                Log.w(TAG, "stored signed pre-key $id signature does not verify under our identity key; rotating")+                return false+            }             protocolStore.storeSignedPreKey(                 id,-                SignedPreKeyRecord(id, System.currentTimeMillis(), keyPair, signature),+                SignedPreKeyRecord(id, System.currentTimeMillis(), ECKeyPair(ECPublicKey(pub), privateKey), signature),             )             Log.i(TAG, "seeded signed pre-key $id into the protocol store")+            true         } catch (t: Throwable) {-            Log.w(TAG, "could not rebuild signed pre-key $id from stored material", t)+            Log.w(TAG, "could not rebuild signed pre-key $id; rotating", t)+            false         }     } +    private fun rotateSignedPreKey(): PreKeyUpload.KeyEntity? = try {+        val keyPair = ECKeyPair.generate()+        val publicKey = keyPair.publicKey.serialize()+        val signature = signSignedPreKey(ownIdentityPrivate, publicKey)+        val id = auth.signedPreKeyId.takeIf { it != 0 }?.plus(1) ?: 1+        protocolStore.storeSignedPreKey(+            id,+            SignedPreKeyRecord(id, System.currentTimeMillis(), keyPair, signature),+        )+        Log.i(TAG, "rotated signed pre-key to $id; needs registering")+        PreKeyUpload.KeyEntity(id, publicKey, signature)+    } catch (t: Throwable) {+        Log.e(TAG, "could not rotate the signed pre-key", t)+        null+    }+     private fun ensureLastResortKyberPreKey(): PreKeyUpload.KeyEntity? {         val existing = runBlocking { db.e2eKyberPreKeyDao().getAll() }         if (existing.any { it.lastResort }) return null@@ -414,7 +473,7 @@ class SignalE2E(     }      fun ensureSignedPreKeyStored() {-        seedSignedPreKey()+        ensureLocalPreKeys()     }      fun markPreKeysUploaded() {
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.ktindex b7c9e16451..acf37027da 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt@@ -154,12 +154,20 @@ object SignalKeysApi {      * or a fresh batch of one-time keys. Keys go up base64 **without** padding, matching the fetch format.      */     suspend fun uploadPreKeys(+        signedPreKey: SignalE2E.PreKeyUpload.KeyEntity?,         lastResortKyber: SignalE2E.PreKeyUpload.KeyEntity?,         oneTimeEcPreKeys: List<SignalE2E.PreKeyUpload.KeyEntity>,         authHeader: String,         sslSocketFactory: SSLSocketFactory?,     ): Boolean {         val body = buildJsonObject {+            if (signedPreKey != null) {+                putJsonObject("signedPreKey") {+                    put("keyId", signedPreKey.id)+                    put("publicKey", encodeUnpadded(signedPreKey.publicKey))+                    put("signature", encodeUnpadded(signedPreKey.signature ?: ByteArray(0)))+                }+            }             if (lastResortKyber != null) {                 putJsonObject("pqLastResortPreKey") {                     put("keyId", lastResortKyber.id)@@ -200,7 +208,7 @@ object SignalKeysApi {             Log.w(TAG, "pre-key registration rejected: ${resp.status} ${resp.statusMessage}")             return false         }-        Log.i(TAG, "registered pre-keys: kyber=${lastResortKyber != null} oneTime=${oneTimeEcPreKeys.size}")+        Log.i(TAG, "registered pre-keys: signed=${signedPreKey != null} kyber=${lastResortKyber != null} oneTime=${oneTimeEcPreKeys.size}")         return true     }