Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalSendPipeline.kt

SignalSendPipeline.kt502 lines · 21.4 KiBRaw
1package com.vayunmathur.communicate.data.signal
2
3import android.content.Context
4import com.vayunmathur.library.log.Log
5import com.vayunmathur.communicate.data.signal.e2e.SignalE2E
6import com.vayunmathur.communicate.data.signal.e2e.deviceIdsWithSessions
7import com.vayunmathur.communicate.data.signal.e2e.ensureLocalPreKeys
8import com.vayunmathur.communicate.data.signal.e2e.hasSignedPreKeyMatching
9import com.vayunmathur.communicate.data.signal.e2e.rotateSignedPreKeyNow
10import com.vayunmathur.communicate.data.signal.transport.SignalKeysApi
11import com.vayunmathur.communicate.data.signal.transport.SignalPayload
12import com.vayunmathur.communicate.data.signal.transport.SignalSocket
13import com.vayunmathur.library.network.NetworkClient
14import org.signal.libsignal.protocol.UntrustedIdentityException
15import org.whispersystems.signalservice.internal.push.SignalServiceProtos
16
17/**
18 * SignalClient send pipeline (split from SignalClient.kt for file length).
19 *
20 * Extension functions on [SignalClient]; behavior identical, call sites unchanged.
21 */
22private const val HTTP_UNAUTHORIZED = 401
23private const val HTTP_MISMATCH = 409
24private const val HTTP_STALE = 410
25
26// ---- internal single send path: Content -> encrypted -> PUT /v1/messages/{aci} ----
27
28/**
29 * The envelope timestamp for [content].
30 *
31 * Taken from the message rather than the clock: recipients reject a message whose
32 * `DataMessage.timestamp` differs from the envelope's (`EnvelopeContentValidator`: "Timestamps don't
33 * match!"). Generating the two independently means anything slow in between — a pre-key fetch on a
34 * first message — silently produces a message the peer discards.
35 */
36private fun SignalClient.envelopeTimestampFor(content: SignalServiceProtos.Content): Long = when {
37 content.hasDataMessage() && content.dataMessage.hasTimestamp() ->
38 content.dataMessage.timestamp
39 content.hasEditMessage() && content.editMessage.hasDataMessage() &&
40 content.editMessage.dataMessage.hasTimestamp() ->
41 content.editMessage.dataMessage.timestamp
42 else -> System.currentTimeMillis()
43}
44
45/**
46 * The `groupV2` context for [conversationId], or nulls when it is not a group.
47 *
48 * Every DataMessage sent to a group needs this or the recipient files it as a 1:1 message from the sender —
49 * which is how reactions, edits, deletes and polls used to escape their group thread.
50 */
51internal suspend fun SignalClient.groupContextFor(conversationId: String): Pair<ByteArray?, Int?> {
52 if (!SignalProtocol.isGroupConversation(conversationId)) return null to null
53 val masterKey = groupMasterKeyForConversation(conversationId) ?: return null to null
54 return masterKey to groupRevisionForConversation(conversationId)
55}
56
57internal suspend fun SignalClient.sendContent(
58 destinationAci: String,
59 content: SignalServiceProtos.Content,
60 urgent: Boolean = true,
61): Boolean {
62 val aci = destinationAci.trim()
63 if (aci.isEmpty()) return false
64 val padded = SignalProtocol.padMessageBody(content.toByteArray())
65 val timestamp = envelopeTimestampFor(content)
66
67 // Group send: expand to participants and encrypt per recipient. There is no shared ciphertext
68 // — sender keys would be the efficient path, but each member still needs their own envelope.
69 if (aci.startsWith("group:") || aci.startsWith("group-")) {
70 val participants: List<String> = try {
71 db?.conversationDao()?.getConversation(aci)?.participants
72 ?.split(",")?.map { it.trim() }?.filter { it.isNotEmpty() } ?: emptyList()
73 } catch (_: Exception) { emptyList() }
74 if (participants.isEmpty()) {
75 Log.status(TAG, "group send has no known participants for $aci, dropping")
76 return false
77 }
78 var allOk = true
79 for (pid in participants) {
80 if (!sendEncryptedTo(pid, padded, timestamp, urgent)) allOk = false
81 }
82 return allOk
83 }
84
85 return sendEncryptedTo(aci, padded, timestamp, urgent)
86}
87
88/**
89 * Seed our own pre-keys into the protocol store and register anything the server does not yet have.
90 *
91 * After seeding, our stored signed pre-key is checked against the bundle the server actually hands
92 * out. That is the only authoritative comparison: senders encrypt to the server's copy, so if it
93 * differs from ours every inbound pre-key message fails in the key agreement with an error that names
94 * neither half. A mismatch is repaired by rotating and re-registering.
95 */
96internal suspend fun SignalClient.ensureLocalPreKeys() {
97 if (!preKeysPrepared.compareAndSet(false, true)) return
98 val e = e2e ?: run {
99 preKeysPrepared.set(false)
100 return
101 }
102 var upload = try {
103 e.ensureLocalPreKeys()
104 } catch (expected: Throwable) {
105 preKeysPrepared.set(false)
106 Log.status(TAG, "could not prepare local pre-keys", expected)
107 return
108 }
109
110 if (upload.signedPreKey == null && !signedPreKeyMatchesServer(e)) {
111 upload = try {
112 upload.copy(signedPreKey = e.rotateSignedPreKeyNow())
113 } catch (expected: Throwable) {
114 Log.status(TAG, "could not rotate the signed pre-key", expected)
115 upload
116 }
117 }
118
119 if (upload.isEmpty) return
120 val ok = SignalKeysApi.uploadPreKeys(
121 signedPreKey = upload.signedPreKey,
122 lastResortKyber = upload.lastResortKyber,
123 oneTimeEcPreKeys = upload.oneTimeEcPreKeys,
124 authHeader = basicAuthHeader(),
125 sslSocketFactory = signalTls(),
126 )
127 if (ok) {
128 e.markPreKeysUploaded()
129 } else {
130 // Let a later start retry rather than leaving keys stored but unregistered.
131 preKeysPrepared.set(false)
132 }
133}
134
135/**
136 * Whether the signed pre-key the server serves for us is one we hold the private half of. Returns true
137 * when it cannot be checked, so a network problem does not trigger a needless rotation.
138 */
139private suspend fun SignalClient.signedPreKeyMatchesServer(e: SignalE2E): Boolean {
140 val ourAci = authData?.aci?.takeIf { it.isNotEmpty() } ?: return true
141 val bundles = try {
142 SignalKeysApi.fetchPreKeys(ourAci, authData?.deviceId ?: PRIMARY_DEVICE_ID, basicAuthHeader(), signalTls())
143 } catch (expected: Throwable) {
144 Log.status(TAG, "could not fetch our own bundle to verify the signed pre-key", expected)
145 return true
146 }
147 val ours = bundles.firstOrNull { it.deviceId == (authData?.deviceId ?: PRIMARY_DEVICE_ID) }
148 if (ours == null) {
149 Log.status(TAG, "the server has no bundle for our own device ${authData?.deviceId}")
150 return true
151 }
152 val signedMatches = e.hasSignedPreKeyMatching(ours.bundle.signedPreKeyId, ours.bundle.signedPreKeyPublic)
153 // The identity key is the other half of what a sender binds to; a mismatch here breaks every
154 // inbound message and cannot be repaired by rotating pre-keys.
155 val identityMatches = ours.bundle.identityKey.contentEquals(e.ownIdentityPublicKey)
156 Log.status(
157 TAG,
158 "own bundle check: signedPreKeyId=${ours.bundle.signedPreKeyId} signedMatches=$signedMatches " +
159 "identityMatches=$identityMatches kyberPreKeyId=${ours.bundle.kyberPreKeyId} " +
160 "hasOneTime=${ours.bundle.preKeyId != null}",
161 )
162 if (!identityMatches) {
163 Log.error(
164 TAG,
165 "our registered identity key differs from the one we hold; inbound messages cannot decrypt " +
166 "and re-registration is required",
167 )
168 }
169 if (!signedMatches) {
170 Log.status(TAG, "the server serves signed pre-key ${ours.bundle.signedPreKeyId} that we cannot use; rotating")
171 }
172 return signedMatches
173}
174
175/**
176 * Run contact discovery once. Returns whether it completed, so a caller waiting on a resolution knows
177 * whether the result is meaningful or a concurrent run simply owned it.
178 */
179internal suspend fun SignalClient.runContactDiscovery(ctx: Context): Boolean {
180 if (!discoveryRunning.compareAndSet(false, true)) return false
181 return try {
182 val result = SignalContactSync.sync(ctx)
183 Log.status(
184 TAG,
185 "contact discovery: ${result.onSignalCount}/${result.e164Count} on Signal" +
186 (result.transportError?.let { " ($it)" } ?: ""),
187 )
188 result.transportError == null
189 } catch (expected: Throwable) {
190 Log.status(TAG, "contact discovery failed", expected)
191 false
192 } finally {
193 discoveryRunning.set(false)
194 }
195}
196
197/**
198 * The service id to address on the wire for [destination], which the app may hand us as a phone
199 * number. May be an ACI (a bare UUID) or a PNI (`PNI:<uuid>`) — both are valid destinations.
200 *
201 * Contact discovery returns a PNI rather than an ACI unless we already hold the contact's profile
202 * key, so a contact we have never messaged is addressed by PNI. Their ACI arrives with their reply.
203 */
204internal suspend fun SignalClient.resolveDestinationAci(destination: String): String? {
205 val trimmed = destination.trim()
206 if (trimmed.isEmpty()) return null
207 if (ACI_REGEX.matches(trimmed) || trimmed.startsWith(PNI_PREFIX)) return trimmed
208
209 knownServiceIdFor(trimmed)?.let { return it }
210 // Not in the contact table: the number may have joined Signal since the last sync, or we may
211 // never have synced. Discovery is the only way to find out.
212 val ctx = appContext
213 if (ctx != null) {
214 runContactDiscovery(ctx)
215 knownServiceIdFor(trimmed)?.let { return it }
216 }
217 Log.status(TAG, "$trimmed is not a registered Signal user, or discovery could not confirm it")
218 return null
219}
220
221/** An ACI if we know one, otherwise the PNI, for [e164]. */
222private suspend fun SignalClient.knownServiceIdFor(e164: String): String? {
223 val contact = try { db?.contactDao()?.getByPhone(e164) } catch (_: Exception) { null } ?: return null
224 if (!contact.onSignal) return null
225 // The `aci` column falls back to the phone number when discovery returned no ACI.
226 contact.aci.takeIf { ACI_REGEX.matches(it) }?.let { return it }
227 return contact.pni.takeIf { it.isNotEmpty() }?.let { pni ->
228 if (pni.startsWith(PNI_PREFIX)) pni else "$PNI_PREFIX$pni"
229 }
230}
231
232private suspend fun SignalClient.sendEncryptedTo(
233 destination: String,
234 padded: ByteArray,
235 timestamp: Long,
236 urgent: Boolean = true,
237): Boolean {
238 val e = e2e
239 if (e == null) {
240 Log.status(TAG, "no protocol store, cannot send to $destination")
241 return false
242 }
243 val aci = resolveDestinationAci(destination) ?: return false
244 if (!e.hasSession(aci, PRIMARY_DEVICE_ID) && !establishSession(e, aci)) return false
245
246 // Sealed sender when we can: a delivery certificate proves who we are to the recipient without
247 // telling the server, and the access key authorises the unauthenticated send. Absent either,
248 // fall back to an identified send rather than not sending.
249 val sealedSender = sealedSenderFor(aci)
250
251 // The server reports device-set disagreements as 409/410; correcting them changes which
252 // devices we encrypt for, so the whole encrypt-and-send has to be redone. [timestamp] comes from
253 // the message itself and is never regenerated — it is both the message's identity for dedup and a
254 // value the recipient checks against the DataMessage.
255 repeat(SEND_ATTEMPTS) {
256 when (sendEncryptedAttempt(e, aci, padded, sealedSender, timestamp, urgent)) {
257 true -> return true
258 false -> return false
259 null -> Unit // device set reconciled; retry
260 }
261 }
262 Log.status(TAG, "giving up on $aci after $SEND_ATTEMPTS attempts to resolve its device set")
263 return false
264}
265
266/**
267 * One encrypt-and-send attempt; returns true on success, false when the send
268 * is abandoned or must stop retrying. Device-set changes are reconciled and
269 * reported via null (caller retries).
270 */
271private suspend fun SignalClient.sendEncryptedAttempt(
272 e: SignalE2E,
273 aci: String,
274 padded: ByteArray,
275 sealedSender: SignalClient.SealedSenderAccess?,
276 timestamp: Long,
277 urgent: Boolean,
278): Boolean? {
279 val targets = e.deviceIdsWithSessions(aci).toSet()
280 val messages = encryptForTargets(e, aci, padded, sealedSender, targets) ?: return false
281 if (messages.isEmpty()) {
282 Log.status(TAG, "no device of $aci could be encrypted for")
283 return false
284 }
285 if (messages.size < targets.size) {
286 Log.status(TAG, "sending to ${messages.size} of ${targets.size} devices for $aci")
287 }
288 val body = SignalPayload.buildPutMessagesBody(aci, messages, timestamp, urgent = urgent)
289 return when (val outcome = putMessages(aci, body, sealedSender?.accessKey)) {
290 is SignalClient.SendOutcome.Success -> true
291 is SignalClient.SendOutcome.Failed -> false
292 is SignalClient.SendOutcome.DeviceSetChanged -> {
293 if (!reconcileDevices(e, aci, outcome.status, outcome.body)) false
294 else {
295 Log.status(TAG, "device set for $aci changed (${outcome.status}), retrying send")
296 null
297 }
298 }
299 }
300}
301
302/** Encrypt [padded] for every target device; null when the send must be abandoned. */
303private suspend fun SignalClient.encryptForTargets(
304 e: SignalE2E,
305 aci: String,
306 padded: ByteArray,
307 sealedSender: SignalClient.SealedSenderAccess?,
308 targets: Set<Int>,
309): ArrayList<SignalPayload.OutgoingPushMessage>? {
310 val messages = ArrayList<SignalPayload.OutgoingPushMessage>(targets.size)
311 var primaryFailed = false
312 for (deviceId in targets) {
313 try {
314 val enc = if (sealedSender != null) {
315 e.sealedSenderEncrypt(aci, deviceId, padded, sealedSender.certificate)
316 } else {
317 e.encryptDM(aci, deviceId, padded)
318 }
319 messages.add(
320 SignalPayload.OutgoingPushMessage(
321 type = SignalPayload.envelopeTypeFor(enc.ciphertextType),
322 destinationDeviceId = deviceId,
323 destinationRegistrationId = enc.remoteRegistrationId,
324 content = enc.data,
325 ),
326 )
327 } catch (ignored: UntrustedIdentityException) {
328 // Already reported by the store; abandon the send rather than encrypting to a key
329 // the user has not accepted.
330 Log.status(TAG, "untrusted identity for $aci:$deviceId, abandoning send")
331 return null
332 } catch (expected: Throwable) {
333 Log.status(TAG, "encrypt failed for $aci:$deviceId", expected)
334 if (deviceId == PRIMARY_DEVICE_ID) primaryFailed = true
335 }
336 }
337 if (primaryFailed) {
338 // Delivering to linked devices but not the recipient's primary is not a send.
339 Log.status(TAG, "could not encrypt for $aci's primary device, abandoning send")
340 return null
341 }
342 return messages
343}
344
345/**
346 * The certificate and access key needed to send sealed to [aci], or null when either is missing and
347 * the send must be identified instead.
348 */
349private suspend fun SignalClient.sealedSenderFor(aci: String): SignalClient.SealedSenderAccess? {
350 val database = db ?: return null
351 val accessKey = SignalSealedSender.accessKeyFor(database, aci) ?: return null
352 val certificate = SignalSealedSender.senderCertificate(
353 db = database,
354 authHeader = basicAuthHeader(),
355 sslSocketFactory = signalTls(),
356 ) ?: return null
357 return SignalClient.SealedSenderAccess(certificate, accessKey)
358}
359
360internal suspend fun SignalClient.putMessages(
361 aci: String,
362 jsonBody: ByteArray,
363 accessKey: ByteArray?): SignalClient.SendOutcome {
364 // Sealed sends go over the credential-free socket. A 401 means the access key was refused, so
365 // retry over the authenticated socket with the same body — the recipient still receives a sealed
366 // envelope, which official clients expect on an identified channel (SignalServiceCipher logs
367 // exactly this case), but the server learns the sender. That is the intended degradation: the
368 // alternative is not delivering at all.
369 if (accessKey != null) {
370 val outcome = putMessagesOverSocket(unauthSocket, aci, jsonBody, accessKey)
371 if (outcome != null && !isAuthRefused(outcome)) return outcome
372 if (outcome != null) Log.status(TAG, "sealed send to $aci refused with 401, retrying authenticated")
373 }
374
375 val identified = putMessagesOverSocket(socket, aci, jsonBody, accessKey = null)
376 if (identified != null) return identified
377 return putMessagesOverRest(aci, jsonBody)
378}
379
380/** True when the outcome is an auth refusal (retry authenticated). */
381private fun isAuthRefused(outcome: SignalClient.SendOutcome): Boolean =
382 outcome is SignalClient.SendOutcome.Failed && outcome.status == HTTP_UNAUTHORIZED
383
384/** Null when the socket is absent or gave no response, so the caller can fall back. */
385private suspend fun SignalClient.putMessagesOverSocket(
386 sock: SignalSocket?,
387 aci: String,
388 jsonBody: ByteArray,
389 accessKey: ByteArray?,
390): SignalClient.SendOutcome? {
391 if (sock == null) return null
392 val headers = buildList {
393 add("content-type:application/json")
394 if (accessKey != null) add(SignalSealedSender.accessKeyHeader(accessKey))
395 }
396 val result = try {
397 sock.sendRequestAwaitingResponse(
398 SignalPayload.buildPutMessagesRequest(aci, jsonBody, headers = headers),
399 )
400 } catch (_: Exception) { null } ?: return null
401
402 return when {
403 result.isSuccess -> SignalClient.SendOutcome.Success
404 result.status == HTTP_MISMATCH || result.status == HTTP_STALE -> SignalClient.SendOutcome.DeviceSetChanged(
405 result.status,
406 result.body)
407 else -> {
408 Log.status(TAG, "PUT messages to $aci rejected: ${result.status} ${result.message}")
409 SignalClient.SendOutcome.Failed(result.status)
410 }
411 }
412}
413
414/** Fallback for when neither socket is connected. Authenticated transport, whatever the body holds. */
415private suspend fun SignalClient.putMessagesOverRest(aci: String, jsonBody: ByteArray): SignalClient.SendOutcome = try {
416 val headers = mapOf(
417 "Authorization" to "Basic ${basicAuthHeader()}",
418 "Content-Type" to "application/json",
419 )
420 val resp = NetworkClient.execute(
421 "https://chat.signal.org${SignalPayload.putMessagesPath(aci)}",
422 method = "PUT",
423 headers = headers,
424 body = jsonBody,
425 sslSocketFactory = signalTls(),
426 )
427 when {
428 resp.isSuccess -> SignalClient.SendOutcome.Success
429 resp.status == HTTP_MISMATCH || resp.status == HTTP_STALE -> {
430 SignalClient.SendOutcome.DeviceSetChanged(resp.status, resp.bytes)
431 }
432 else -> {
433 Log.status(TAG, "PUT messages to $aci rejected: ${resp.status} ${resp.statusMessage}")
434 SignalClient.SendOutcome.Failed(resp.status)
435 }
436 }
437} catch (_: Exception) { SignalClient.SendOutcome.Failed(0) }
438
439/**
440 * Bring our device set for [aci] back in line with the server's. Returns whether anything actually
441 * changed — retrying with an identical device set would just produce the same rejection.
442 *
443 * 409 reports `missingDevices` (fetch pre-keys and build sessions) and `extraDevices` (archive).
444 * 410 reports `staleDevices`, which are archived and then rebuilt. Sessions are archived rather
445 * than deleted so in-flight messages on the old chain stay decryptable.
446 */
447private suspend fun SignalClient.reconcileDevices(e: SignalE2E, aci: String, status: Int, body: ByteArray): Boolean {
448 val devices = SignalDeviceMismatch.parse(status, body.toString(Charsets.UTF_8)) ?: run {
449 Log.status(TAG, "could not parse $status device mismatch body for $aci")
450 return false
451 }
452 var changed = devices.archive.count { e.archiveSession(aci, it) } > 0
453 if (devices.fetch.isEmpty()) return changed
454
455 val bundles = try {
456 SignalKeysApi.fetchPreKeys(aci, 1, basicAuthHeader(), signalTls())
457 } catch (expected: Throwable) {
458 Log.status(TAG, "prekey fetch for changed devices of $aci failed", expected)
459 return changed
460 }
461 for (device in bundles.filter { it.deviceId in devices.fetch }) {
462 try {
463 e.processPreKeyBundle(aci, device.deviceId, device.bundle)
464 changed = true
465 } catch (expected: Throwable) {
466 Log.status(TAG, "failed to build session for $aci:${device.deviceId}", expected)
467 }
468 }
469 return changed
470}
471
472/**
473 * Fetch pre-keys for [aci] and build sessions for every device the server reports. Returns whether
474 * device 1 ended up with a usable session, since that is the one this send targets.
475 */
476internal suspend fun SignalClient.establishSession(e: SignalE2E, aci: String): Boolean {
477 val bundles = try {
478 SignalKeysApi.fetchPreKeys(aci, 1, basicAuthHeader(), signalTls())
479 } catch (expected: SignalKeysApi.UnregisteredUserException) {
480 Log.status(TAG, "cannot send to $aci: ${expected.message}")
481 return false
482 } catch (expected: Throwable) {
483 Log.status(TAG, "prekey fetch failed for $aci", expected)
484 return false
485 }
486 if (bundles.isEmpty()) {
487 Log.status(TAG, "no usable prekey bundles for $aci")
488 return false
489 }
490 for (device in bundles) {
491 try {
492 e.processPreKeyBundle(aci, device.deviceId, device.bundle)
493 } catch (ignored: UntrustedIdentityException) {
494 // The store has already reported the change; a new session must not be built on a key
495 // the user has not accepted.
496 Log.status(TAG, "untrusted identity for $aci:${device.deviceId}, not building a session")
497 } catch (expected: Throwable) {
498 Log.status(TAG, "failed to build session for $aci:${device.deviceId}", expected)
499 }
500 }
501 return e.hasSession(aci, 1)
502}