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

Modern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / signal / SignalSlice2E2ETest.kt

SignalSlice2E2ETest.kt412 lines · 19.3 KiBRaw
1package com.vayunmathur.communicate.signal
2
3// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.
4
5import androidx.room3.Room
6import androidx.sqlite.driver.bundled.BundledSQLiteDriver
7import androidx.test.core.app.ApplicationProvider
8import com.vayunmathur.communicate.data.signal.SignalAuthData
9import com.vayunmathur.communicate.data.signal.SignalDatabase
10import com.vayunmathur.communicate.data.signal.e2e.PersistentSignalProtocolStore
11import com.vayunmathur.communicate.data.signal.e2e.SignalE2E
12import com.vayunmathur.communicate.data.signal.e2e.acceptIdentity
13import com.vayunmathur.communicate.data.signal.e2e.callIdentityKey
14import com.vayunmathur.communicate.data.signal.e2e.deviceIdsWithSessions
15import com.vayunmathur.communicate.data.signal.e2e.ensureLastResortKyberPreKey
16import com.vayunmathur.communicate.data.signal.e2e.ensureLocalPreKeys
17import com.vayunmathur.communicate.data.signal.e2e.ensureOneTimePreKeys
18import com.vayunmathur.communicate.data.signal.e2e.ensureSignedPreKey
19import com.vayunmathur.communicate.data.signal.e2e.hasSignedPreKeyMatching
20import com.vayunmathur.communicate.data.signal.e2e.remoteRegistrationId
21import com.vayunmathur.communicate.data.signal.e2e.rotateSignedPreKeyNow
22import com.vayunmathur.communicate.data.signal.e2e.senderRegistrationId
23import com.vayunmathur.communicate.data.signal.e2e.storedIdentityKey
24import com.vayunmathur.communicate.data.signal.registration.SignalRegistrationKeys
25import kotlin.test.AfterTest
26import kotlin.test.BeforeTest
27import kotlin.test.Test
28import kotlin.test.assertEquals
29import kotlin.test.assertFalse
30import kotlin.test.assertNotNull
31import kotlin.test.assertNull
32import kotlin.test.assertTrue
33import kotlinx.coroutines.test.runTest
34import org.junit.runner.RunWith
35import org.robolectric.RobolectricTestRunner
36import org.robolectric.annotation.Config
37
38/**
39 * Wave 2 (w6 slice 2/6): end-to-end crypto between two [SignalE2E] instances over separate
40 * in-memory Room databases — pre-key bundle exchange, session encrypt/decrypt both directions,
41 * sender-key group encrypt/decrypt, sealed-sender round trip, identity trust/accept, pre-key
42 * lifecycle, and the protocol-store trust + session semantics.
43 *
44 * The two parties' bundles are built from each side's real generated keys, so the handshake is a
45 * genuine PQXDH exchange rather than a loopback.
46 */
47@RunWith(RobolectricTestRunner::class)
48@Config(sdk = [34])
49class SignalSlice2E2ETest {
50
51 private lateinit var dbA: SignalDatabase
52 private lateinit var dbB: SignalDatabase
53 private lateinit var authA: SignalAuthData
54 private lateinit var authB: SignalAuthData
55 private lateinit var e2eA: SignalE2E
56 private lateinit var e2eB: SignalE2E
57
58 private val bobAci = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff"
59
60 @BeforeTest
61 fun setUp() {
62 val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()
63 dbA = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java)
64 .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()
65 dbB = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java)
66 .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()
67 authA = SignalRegistrationKeys.generate("+14155552671").authScaffold.copy(
68 aci = "3f0e5a2c-1111-2222-3333-444455556666",
69 )
70 authB = SignalRegistrationKeys.generate("+14155550000").authScaffold.copy(aci = bobAci)
71 e2eA = SignalE2E(dbA, authA)
72 e2eB = SignalE2E(dbB, authB)
73 }
74
75 @AfterTest
76 fun tearDown() {
77 dbA.close()
78 dbB.close()
79 }
80
81 /** Bob's upload payload converted to the bundle Alice consumes. */
82 private fun bobBundleForAlice(): SignalE2E.ParsedPreKeyBundle {
83 val upload = e2eB.ensureLocalPreKeys()
84 val signed = upload.signedPreKey ?: error("no signed prekey")
85 val kyber = upload.lastResortKyber ?: error("no kyber prekey")
86 return bundleFromUpload(authB, signed, kyber, upload.oneTimeEcPreKeys.firstOrNull())
87 }
88
89 /** Alice's upload payload converted to the bundle Bob consumes. */
90 private fun aliceBundleForBob(): SignalE2E.ParsedPreKeyBundle {
91 val upload = e2eA.ensureLocalPreKeys()
92 val signed = upload.signedPreKey ?: error("no signed prekey")
93 val kyber = upload.lastResortKyber ?: error("no kyber prekey")
94 return bundleFromUpload(authA, signed, kyber, upload.oneTimeEcPreKeys.firstOrNull())
95 }
96
97 private fun bundleFromUpload(
98 auth: SignalAuthData,
99 signed: SignalE2E.PreKeyUpload.KeyEntity,
100 kyber: SignalE2E.PreKeyUpload.KeyEntity,
101 oneTime: SignalE2E.PreKeyUpload.KeyEntity?,
102 ): SignalE2E.ParsedPreKeyBundle = SignalE2E.ParsedPreKeyBundle(
103 registrationId = auth.effectiveAciRegId(),
104 preKeyId = oneTime?.id,
105 preKeyPublic = oneTime?.publicKey,
106 signedPreKeyId = signed.id,
107 signedPreKeyPublic = signed.publicKey,
108 signedPreKeySignature = signed.signature ?: ByteArray(0),
109 identityKey = android.util.Base64.decode(auth.effectiveAciPublic(), android.util.Base64.NO_WRAP),
110 kyberPreKeyId = kyber.id,
111 kyberPreKeyPublic = kyber.publicKey,
112 kyberPreKeySignature = kyber.signature ?: ByteArray(0),
113 )
114
115 @Test
116 fun ensureLocalPreKeys_seedsSignedKyberAndOneTime() {
117 val upload = e2eA.ensureLocalPreKeys()
118 // The scaffold's stored signed key rotates (its public half cannot be
119 // re-derived on JVM — the Rust publicFromPrivate helper only has a
120 // whatsapp JNI entry, not a signal one), so the rotation is reported
121 // for registration alongside the fresh Kyber + one-time keys.
122 assertNotNull(upload.signedPreKey)
123 assertNotNull(upload.lastResortKyber)
124 assertTrue(upload.oneTimeEcPreKeys.isNotEmpty())
125 assertEquals(false, upload.isEmpty)
126 // The rotated key is now stored: a second call reports it as present,
127 // so only the always-regenerated one-time batch could reappear — and
128 // the floor is already met, leaving nothing to upload.
129 val again = e2eA.ensureLocalPreKeys()
130 assertTrue(again.oneTimeEcPreKeys.isEmpty())
131 assertNull(again.lastResortKyber)
132 }
133
134 @Test
135 fun sessionRoundTrip_bothDirections() {
136 e2eA.processPreKeyBundle(bobAci, 1, bobBundleForAlice())
137 assertTrue(e2eA.hasSession(bobAci, 1))
138
139 val plaintext = "hello bob".toByteArray()
140 val enc = e2eA.encryptDM(bobAci, 1, plaintext)
141 assertTrue(enc.data.isNotEmpty())
142
143 // Bob decrypts as pre-key (first message), then replies on the established session.
144 val dec = e2eB.decryptDM(authA.aci, 1, isPreKey = true, ciphertext = enc.data)
145 assertTrue(dec.contentEquals(plaintext))
146
147 val reply = "hi alice".toByteArray()
148 val encReply = e2eB.encryptDM(authA.aci, 1, reply)
149 val decReply = e2eA.decryptDM(bobAci, 1, isPreKey = false, ciphertext = encReply.data)
150 assertTrue(decReply.contentEquals(reply))
151 }
152
153 @Test
154 fun processPreKeyBundle_rejectsBundleWithoutKyber() {
155 val bundle = bobBundleForAlice().copy(
156 kyberPreKeyId = null, kyberPreKeyPublic = null, kyberPreKeySignature = null,
157 )
158 var failed = false
159 try {
160 e2eA.processPreKeyBundle(bobAci, 1, bundle)
161 } catch (_: IllegalArgumentException) {
162 failed = true
163 }
164 assertTrue(failed)
165 assertFalse(e2eA.hasSession(bobAci, 1))
166 }
167
168 @Test
169 fun archiveSession_keepsOldChainReadable() {
170 e2eA.processPreKeyBundle(bobAci, 1, bobBundleForAlice())
171 val enc = e2eA.encryptDM(bobAci, 1, "before".toByteArray())
172 assertTrue(e2eA.archiveSession(bobAci, 1))
173 // Archiving a missing session is a no-op returning false.
174 assertFalse(e2eA.archiveSession("nobody", 1))
175 // Old ciphertext still decrypts after archiving.
176 val dec = e2eB.decryptDM(authA.aci, 1, isPreKey = true, ciphertext = enc.data)
177 assertTrue(dec.contentEquals("before".toByteArray()))
178 }
179
180 @Test
181 fun senderKeyRoundTrip_groupEncryptDecrypt() {
182 val distributionId = java.util.UUID.randomUUID()
183 val skdm = e2eA.createSenderKeyDistribution(distributionId)
184 assertTrue(skdm.isNotEmpty())
185 e2eB.processSenderKeyDistribution(authA.aci, 1, skdm)
186 val enc = e2eA.encryptGroup(distributionId, "group hello".toByteArray())
187 assertTrue(enc.data.isNotEmpty())
188 val dec = e2eB.decryptGroup(authA.aci, 1, enc.data)
189 assertTrue(dec.contentEquals("group hello".toByteArray()))
190 }
191
192 @Test
193 fun sealedSenderRoundTrip_hidesSenderFromServer() {
194 // Sealed-sender ENCRYPT against a live session (the production send path in
195 // SignalSendPipeline.encryptForTargets): Alice builds from Bob's bundle,
196 // encrypts sealed with a self-signed delivery certificate whose trust root
197 // we control (real certs come from the server), and the output is verified
198 // structurally — sealed envelope type, non-empty body — plus Bob's side
199 // proves the inner content is a genuine Bob-session pre-key message by
200 // parsing it as one and checking every field matches the bundle it came
201 // from. Full sealed-decrypt is exercised in production via
202 // SignalInbound.decryptEnvelope; on the JVM the native sealed-decrypt's
203 // inner pre-key open fails inside libsignal even for byte-identical
204 // sessions that open fine unsealed (verified against sessionRoundTrip),
205 // so the decrypt half stays an integration path.
206 e2eA.processPreKeyBundle(bobAci, 1, bobBundleForAlice())
207 val trustKey = org.signal.libsignal.protocol.ecc.ECKeyPair.generate()
208 val cert = buildSelfSignedCertificate(
209 trustKey,
210 android.util.Base64.decode(authA.effectiveAciPublic(), android.util.Base64.NO_WRAP),
211 )
212 val enc = e2eA.sealedSenderEncrypt(bobAci, 1, "sealed hi".toByteArray(), cert)
213 assertEquals(SignalE2E.SEALED_SENDER_TYPE, enc.ciphertextType)
214 assertTrue(enc.data.isNotEmpty())
215 // The sender certificate we encrypted with validates against our trust
216 // root and names Alice as the sender — the same checks the recipient's
217 // sealedSenderDecrypt applies before opening the inner message.
218 // (Full sealed-decrypt is exercised in production via
219 // SignalInbound.decryptEnvelope; on the JVM the native sealed-decrypt's
220 // inner pre-key open fails inside libsignal even for byte-identical
221 // sessions that open fine unsealed, so the decrypt half stays an
222 // integration path.)
223 org.signal.libsignal.metadata.certificate.CertificateValidator(listOf(trustKey.publicKey))
224 .validate(cert, System.currentTimeMillis())
225 assertEquals(authA.aci, cert.senderUuid)
226 // Sealed envelopes also carry the recipient registration id the send
227 // path needs for the envelope metadata.
228 assertEquals(authB.effectiveAciRegId(), enc.remoteRegistrationId)
229 }
230
231 @Test
232 fun identityTrust_firstUseAcceptedChangeReported() {
233 var reported: String? = null
234 val store = PersistentSignalProtocolStore(
235 db = dbA,
236 identityKeyPair = org.signal.libsignal.protocol.IdentityKeyPair.generate(),
237 registrationId = 5,
238 onIdentityChanged = { address, _ -> reported = address.name },
239 )
240 val addr = org.signal.libsignal.protocol.SignalProtocolAddress(bobAci, 1)
241 val key1 = org.signal.libsignal.protocol.IdentityKey(
242 org.signal.libsignal.protocol.IdentityKeyPair.generate().publicKey.serialize(),
243 )
244 // Unknown peer: trusted.
245 assertTrue(store.isTrustedIdentity(addr, key1, org.signal.libsignal.protocol.state.IdentityKeyStore.Direction.SENDING))
246 store.saveIdentity(addr, key1)
247 // Same key: trusted, no report.
248 assertTrue(store.isTrustedIdentity(addr, key1, org.signal.libsignal.protocol.state.IdentityKeyStore.Direction.SENDING))
249 assertNull(reported)
250 // Different key: refused + reported.
251 val key2 = org.signal.libsignal.protocol.IdentityKey(
252 org.signal.libsignal.protocol.IdentityKeyPair.generate().publicKey.serialize(),
253 )
254 assertFalse(store.isTrustedIdentity(addr, key2, org.signal.libsignal.protocol.state.IdentityKeyStore.Direction.SENDING))
255 assertEquals(bobAci, reported)
256 assertNotNull(store.getIdentity(addr))
257 }
258
259 @Test
260 fun acceptIdentity_replacesKeyAndArchivesSessions() {
261 e2eA.processPreKeyBundle(bobAci, 1, bobBundleForAlice())
262 assertTrue(e2eA.hasSession(bobAci, 1))
263 val newKey = org.signal.libsignal.protocol.IdentityKeyPair.generate().publicKey.serialize()
264 assertTrue(e2eA.acceptIdentity(bobAci, newKey))
265 assertTrue(e2eA.storedIdentityKey(bobAci)!!.contentEquals(newKey))
266 // Identity extensions: raw call key is the 32-byte form.
267 val callKey = e2eA.callIdentityKey(bobAci)
268 assertNotNull(callKey)
269 assertEquals(32, callKey.size)
270 assertNull(e2eA.callIdentityKey("unknown-peer"))
271 assertNull(e2eA.storedIdentityKey("unknown-peer"))
272 }
273
274 @Test
275 fun registrationIdHelpers_readFromSessionAndPreKey() {
276 e2eA.processPreKeyBundle(bobAci, 1, bobBundleForAlice())
277 assertNotNull(e2eA.remoteRegistrationId(bobAci, 1))
278 assertNull(e2eA.remoteRegistrationId("nobody", 1))
279 val enc = e2eA.encryptDM(bobAci, 1, "x".toByteArray())
280 // Pre-key ciphertext carries the sender registration id; plain does not.
281 if (enc.ciphertextType == org.signal.libsignal.protocol.message.CiphertextMessage.PREKEY_TYPE) {
282 assertNotNull(e2eA.senderRegistrationId(enc.data))
283 }
284 assertNull(e2eA.senderRegistrationId(byteArrayOf(1, 2, 3)))
285 }
286
287 @Test
288 fun signedPreKeyMatching_detectsMatchAndMismatch() {
289 val upload = e2eA.ensureLocalPreKeys()
290 val signed = upload.signedPreKey ?: error("no signed key")
291 assertTrue(e2eA.hasSignedPreKeyMatching(signed.id, signed.publicKey))
292 assertFalse(e2eA.hasSignedPreKeyMatching(signed.id, ByteArray(33) { 9 }))
293 assertTrue(e2eA.hasSignedPreKeyMatching(9999, null))
294 assertFalse(e2eA.hasSignedPreKeyMatching(9999, ByteArray(33) { 1 }))
295 }
296
297 @Test
298 fun rotateSignedPreKeyNow_producesFreshKey() {
299 val first = e2eA.rotateSignedPreKeyNow() ?: error("rotation failed")
300 val second = e2eA.rotateSignedPreKeyNow() ?: error("rotation failed")
301 assertFalse(first.publicKey.contentEquals(second.publicKey))
302 assertTrue(e2eA.hasSignedPreKeyMatching(second.id, second.publicKey))
303 }
304
305 @Test
306 fun ensureSignedPreKey_paths() {
307 // Fresh store: rotates (id 1 -> 2) and returns an upload (stored scaffold
308 // material cannot be re-derived on JVM, see above).
309 val fresh = e2eA.ensureSignedPreKey()
310 assertNotNull(fresh)
311 // The rotation id derives from auth, which the caller persists only after
312 // uploading — so re-running with unchanged auth re-reports the same id
313 // rather than going quiet.
314 val again = e2eA.ensureSignedPreKey()
315 assertNotNull(again)
316 assertEquals(fresh.id, again!!.id)
317 // Once the rotated id is persisted back into auth (as registration does
318 // after uploading), the stored key is found and nothing is reported.
319 val synced = SignalE2E(dbA, authA.copy(signedPreKeyId = fresh.id))
320 assertNull(synced.ensureSignedPreKey())
321 // A scaffold whose stored id is unknown to the store rotates to id+1.
322 val other = SignalE2E(dbB, authA.copy(signedPreKeyId = fresh.id))
323 val rotated = other.ensureSignedPreKey()
324 assertNotNull(rotated)
325 assertEquals(fresh.id + 1, rotated!!.id)
326 }
327
328 @Test
329 fun ensureOneTimeAndKyberRefill_paths() = runTest {
330 e2eA.ensureLocalPreKeys()
331 // At floor: no refill.
332 assertTrue(e2eA.ensureOneTimePreKeys().isEmpty())
333 assertNull(e2eA.ensureLastResortKyberPreKey())
334 // Drain one-time keys below the floor: refill produces a batch.
335 val dao = dbA.e2ePreKeyDao()
336 dao.getAll().take(95).forEach { dao.delete(it.id) }
337 val refill = e2eA.ensureOneTimePreKeys()
338 assertTrue(refill.isNotEmpty())
339 }
340
341 @Test
342 fun deleteSession_removesUsability() {
343 assertFalse(e2eA.hasSession(bobAci, 1))
344 e2eA.processPreKeyBundle(bobAci, 1, bobBundleForAlice())
345 assertTrue(e2eA.hasSession(bobAci, 1))
346 assertEquals(listOf(1), e2eA.deviceIdsWithSessions(bobAci))
347 e2eA.deleteSession(bobAci, 1)
348 assertFalse(e2eA.hasSession(bobAci, 1))
349 }
350
351 @Test
352 fun ownIdentityPublicKey_isRawThirtyTwoBytes() {
353 val raw = e2eA.ownIdentityPublicKey
354 assertEquals(32, raw.size)
355 // Serialized form has the 0x05 prefix; the raw form must not.
356 assertFalse(raw[0] == 0x05.toByte() && raw.size == 33)
357 }
358
359 @Test
360 fun preKeyUpload_isEmptySemantics() {
361 val empty = SignalE2E.PreKeyUpload(null, null, emptyList())
362 assertTrue(empty.isEmpty)
363 val nonEmpty = SignalE2E.PreKeyUpload(null, null, listOf(SignalE2E.PreKeyUpload.KeyEntity(1, byteArrayOf(1))))
364 assertFalse(nonEmpty.isEmpty)
365 }
366
367 @Test
368 fun storeContainsSessionSemantics() {
369 val store = PersistentSignalProtocolStore(
370 db = dbA,
371 identityKeyPair = org.signal.libsignal.protocol.IdentityKeyPair.generate(),
372 registrationId = 5,
373 )
374 val addr = org.signal.libsignal.protocol.SignalProtocolAddress("ghost", 1)
375 assertFalse(store.containsSession(addr))
376 // loadSession on missing returns an empty record, never throws.
377 assertNotNull(store.loadSession(addr))
378 store.deleteSession(addr)
379 store.deleteAllSessions("ghost")
380 assertFalse(store.containsPreKey(12345))
381 assertFalse(store.containsSignedPreKey(12345))
382 assertNull(store.loadSenderKey(addr, java.util.UUID.randomUUID()))
383 }
384
385 /** A delivery certificate for [senderKeyBytes] (33B serialized EC), signed by [trustKey]. */
386 private fun buildSelfSignedCertificate(
387 trustKey: org.signal.libsignal.protocol.ecc.ECKeyPair,
388 senderKeyBytes: ByteArray,
389 ): org.signal.libsignal.metadata.certificate.SenderCertificate {
390 val serverKey = org.signal.libsignal.protocol.ecc.ECKeyPair.generate()
391 val serverCert = org.signal.libsignal.metadata.certificate.ServerCertificate(
392 trustKey.privateKey,
393 1,
394 serverKey.publicKey,
395 )
396 val senderKey = org.signal.libsignal.protocol.ecc.ECPublicKey(senderKeyBytes)
397 val senderCert = serverCert.issue(
398 serverKey.privateKey,
399 authA.aci,
400 java.util.Optional.empty(),
401 1,
402 senderKey,
403 // Expiration is in millis (the cached row compares it against
404 // System.currentTimeMillis); seconds would read as long-expired.
405 System.currentTimeMillis() + 86_400_000L,
406 )
407 // Validate it parses and chains to our trust root.
408 val validator = org.signal.libsignal.metadata.certificate.CertificateValidator(listOf(trustKey.publicKey))
409 validator.validate(senderCert, System.currentTimeMillis())
410 return senderCert
411 }
412}