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

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

Y3SignalGroupOpsServerTest.kt293 lines · 15.5 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.google.protobuf.ByteString
9import com.sun.net.httpserver.HttpServer
10import com.vayunmathur.communicate.data.signal.SignalAuthData
11import com.vayunmathur.communicate.data.signal.SignalClient
12import com.vayunmathur.communicate.data.signal.SignalConversation
13import com.vayunmathur.communicate.data.signal.SignalDatabase
14import com.vayunmathur.communicate.data.signal.SignalEvent
15import com.vayunmathur.communicate.data.signal.SignalGroups
16import com.vayunmathur.communicate.data.signal.SignalProtocol
17import com.vayunmathur.communicate.data.signal.refreshGroup
18import com.vayunmathur.communicate.data.signal.registration.SignalRegistrationKeys
19import com.vayunmathur.communicate.data.signal.setGroupName
20import com.vayunmathur.communicate.data.signal.transport.SignalGroupsApi
21import com.vayunmathur.communicate.data.signal.updateGroupParticipants
22import java.net.InetSocketAddress
23import java.security.SecureRandom
24import java.time.Instant
25import java.util.Collections
26import java.util.UUID
27import kotlin.io.encoding.Base64
28import kotlin.io.encoding.ExperimentalEncodingApi
29import kotlin.test.AfterTest
30import kotlin.test.BeforeTest
31import kotlin.test.Test
32import kotlin.test.assertEquals
33import kotlin.test.assertFalse
34import kotlin.test.assertNotNull
35import kotlin.test.assertTrue
36import kotlinx.coroutines.Dispatchers
37import kotlinx.coroutines.launch
38import kotlinx.coroutines.test.runTest
39import org.junit.runner.RunWith
40import org.robolectric.RobolectricTestRunner
41import org.robolectric.annotation.Config
42import org.signal.libsignal.protocol.ServiceId
43import org.signal.libsignal.zkgroup.ServerSecretParams
44import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations
45import org.signal.libsignal.zkgroup.groups.ClientZkGroupCipher
46import org.signal.libsignal.zkgroup.groups.GroupSecretParams
47import org.signal.libsignal.zkgroup.groups.UuidCiphertext
48import org.signal.storageservice.storage.protos.groups.Group
49import org.signal.storageservice.storage.protos.groups.GroupAttributeBlob
50import org.signal.storageservice.storage.protos.groups.GroupChange
51import org.signal.storageservice.storage.protos.groups.GroupResponse
52import org.signal.storageservice.storage.protos.groups.Member
53
54/**
55 * Y3 group ops, server-accepted: a locally minted zkgroup server
56 * ([ServerSecretParams.generate] + [ServerZkAuthOperations]) issues the
57 * auth credential, `serverPublicParamsForTest` points the client's
58 * verification at that server's public params, and chat (credentials) +
59 * storage (group GET/PATCH) are scripted on localhost. The private
60 * `groupChange`/`fetchGroupState` are covered through their public callers
61 * [setGroupName], [updateGroupParticipants] and [refreshGroup], with real
62 * asserts on DB rows, events and recorded requests.
63 */
64@OptIn(ExperimentalEncodingApi::class)
65@RunWith(RobolectricTestRunner::class)
66@Config(sdk = [34])
67class Y3SignalGroupOpsServerTest {
68
69 private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()
70 private val selfAci = "123e4567-e89b-42d3-a456-426614174000"
71 private val pniUuid = "123e4567-e89b-42d3-a456-426614174001"
72 private val bobAci = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff"
73 private val carolAci = "123e4567-e89b-42d3-a456-426614174002"
74
75 private lateinit var db: SignalDatabase
76 private lateinit var authA: SignalAuthData
77 private lateinit var serverSecret: ServerSecretParams
78 private val servers = mutableListOf<HttpScript>()
79
80 @BeforeTest fun setUp() {
81 db = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java)
82 .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()
83 authA = SignalRegistrationKeys.generate("+14155552671").authScaffold
84 .copy(aci = selfAci, pni = "PNI:$pniUuid")
85 SignalClient.db = db; SignalClient.authData = authA; SignalClient.e2e = null
86 SignalClient.socket = null; SignalClient.unauthSocket = null; SignalClient.appContext = null
87 // Local zkgroup server: client verification trusts THIS server's params.
88 serverSecret = ServerSecretParams.generate()
89 SignalGroupsApi.serverPublicParamsForTest = serverPublicParamsBytes(serverSecret)
90 }
91 @AfterTest fun tearDown() {
92 SignalGroupsApi.storageBaseForTest = null
93 SignalGroupsApi.chatBaseForTest = null
94 SignalGroupsApi.serverPublicParamsForTest = null
95 servers.forEach { it.close() }; servers.clear()
96 SignalClient.db = null; SignalClient.authData = null; SignalClient.e2e = null
97 db.close()
98 }
99
100 // ---------- scripted HTTP ----------
101 data class HReq(val method: String, val path: String, val query: String?, val headers: Map<String, String>, val body: ByteArray)
102 data class HResp(val status: Int, val body: ByteArray, val type: String = "application/json") {
103 constructor(status: Int, text: String) : this(status, text.encodeToByteArray())
104 }
105 class HttpScript(private val handler: (HReq) -> HResp) : AutoCloseable {
106 val requests = Collections.synchronizedList(mutableListOf<HReq>())
107 private val http = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
108 val base: String get() = "http://127.0.0.1:${http.address.port}"
109 init {
110 http.createContext("/") { ex ->
111 val req = HReq(ex.requestMethod, ex.requestURI.path, ex.requestURI.rawQuery,
112 ex.requestHeaders.mapValues { it.value.firstOrNull() ?: "" }, ex.requestBody.readBytes())
113 requests.add(req)
114 val resp = runCatching { handler(req) }.getOrElse { HResp(500, "handler: $it") }
115 ex.responseHeaders.add("Content-Type", resp.type)
116 ex.sendResponseHeaders(resp.status, resp.body.size.toLong())
117 ex.responseBody.use { it.write(resp.body) }
118 }; http.start()
119 }
120 fun header(req: HReq, name: String): String? =
121 req.headers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value
122 override fun close() = http.stop(0)
123 }
124 private fun http(handler: (HReq) -> HResp) = HttpScript(handler).also { servers.add(it) }
125
126 private fun todayAligned(): Long { val now = System.currentTimeMillis() / 1000; return now - (now % 86_400) }
127
128 /** Serialized ServerPublicParams for [secret], via whichever accessor this libsignal exposes. */
129 private fun serverPublicParamsBytes(secret: ServerSecretParams): ByteArray {
130 val method = secret.javaClass.methods.first {
131 it.parameterCount == 0 && it.returnType.simpleName == "ServerPublicParams"
132 }
133 val params = method.invoke(secret)
134 return params.javaClass.getMethod("serialize").invoke(params) as ByteArray
135 }
136
137 /** Credential for our own ACI/PNI at today's redemption boundary, from the local zk server. */
138 private fun mintedCredential(): ByteArray =
139 ServerZkAuthOperations(serverSecret).issueAuthCredentialWithPniZkc(
140 SecureRandom(),
141 ServiceId.Aci.parseFromString(selfAci),
142 ServiceId.Pni(UUID.fromString(pniUuid)),
143 Instant.ofEpochSecond(todayAligned()),
144 ).serialize()
145
146 private class World(val convId: String, val masterKey: ByteArray, val secretParams: GroupSecretParams)
147
148 private fun world(name: String = "Before", revision: Int = 0, participants: String = bobAci): World {
149 val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams()
150 val convId = SignalProtocol.toConversationId("", masterKey)
151 kotlinx.coroutines.runBlocking {
152 db.conversationDao().upsert(SignalConversation(chatId = convId, isGroup = true, name = name,
153 participants = participants, groupMasterKey = masterKey, groupRevision = revision))
154 }
155 return World(convId, masterKey, GroupSecretParams(SignalGroups.secretParamsFor(masterKey)))
156 }
157
158 /** Chat serves the locally minted credential; storage is per-test. */
159 private fun wire(storage: (HReq) -> HResp): Pair<HttpScript, HttpScript> {
160 val credB64 = Base64.Default.encode(mintedCredential())
161 val chat = http { req ->
162 if (req.path == "/v1/certificate/auth/group")
163 HResp(200, """{"credentials":[{"redemptionTime":${todayAligned()},"credential":"$credB64"}]}""")
164 else HResp(404, "{}")
165 }
166 val store = http(storage)
167 SignalGroupsApi.chatBaseForTest = chat.base
168 SignalGroupsApi.storageBaseForTest = store.base
169 return chat to store
170 }
171
172 // ---------- groupChange via setGroupName / updateGroupParticipants ----------
173
174 @Test fun setGroupName_serverAccepted_updatesRowEmitsEventAndPatchesProto() = runTest {
175 val w = world()
176 var patch: HReq? = null
177 val (chat, store) = wire { req ->
178 if (req.method == "PATCH") { patch = req; HResp(200, byteArrayOf(), "application/x-protobuf") }
179 else HResp(404, "{}")
180 }
181 val seen = mutableListOf<SignalEvent>()
182 val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } }
183 assertTrue(SignalClient.setGroupName(w.convId, "After"))
184 job.cancel()
185
186 val row = db.conversationDao().getConversation(w.convId)!!
187 assertEquals("After", row.name); assertEquals(1, row.groupRevision)
188 assertTrue(seen.any { it is SignalEvent.ConversationNameChanged && it.newName == "After" }, "$seen")
189 // Credential dance really happened against both scripted servers.
190 assertEquals(1, chat.requests.size)
191 assertEquals("/v1/certificate/auth/group", chat.requests[0].path)
192 assertTrue(chat.requests[0].query!!.contains("redemptionStartSeconds="))
193 val p = assertNotNull(patch)
194 assertEquals("/v2/groups/", p.path)
195 assertTrue(store.header(p, "Authorization")!!.startsWith("Basic "))
196 assertEquals("application/x-protobuf", store.header(p, "Content-Type"))
197 // PATCH body is the encrypted title change at the new revision.
198 val actions = GroupChange.Actions.parseFrom(p.body)
199 assertEquals(1, actions.version); assertTrue(actions.hasModifyTitle())
200 val blob = GroupAttributeBlob.parseFrom(
201 ClientZkGroupCipher(w.secretParams).decryptBlob(actions.modifyTitle.title.toByteArray()))
202 assertEquals("After", blob.title)
203 }
204
205 @Test fun setGroupName_serverRejectedPatch_keepsRowButServerWasAsked() = runTest {
206 val w = world()
207 val (_, store) = wire { HResp(403, byteArrayOf(), "application/x-protobuf") }
208 assertFalse(SignalClient.setGroupName(w.convId, "After"))
209 val row = db.conversationDao().getConversation(w.convId)!!
210 assertEquals("Before", row.name); assertEquals(0, row.groupRevision)
211 // Rejection is now a real server round-trip, not an offline failure.
212 assertTrue(store.requests.any { it.method == "PATCH" && it.path == "/v2/groups/" })
213 }
214
215 @Test fun updateGroupParticipants_addAccepted_emitsEventAndPatchesMember() = runTest {
216 val w = world()
217 var patch: HReq? = null
218 wire { req ->
219 if (req.method == "PATCH") { patch = req; HResp(200, byteArrayOf(), "application/x-protobuf") }
220 else HResp(404, "{}")
221 }
222 val seen = mutableListOf<SignalEvent>()
223 val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } }
224 assertTrue(SignalClient.updateGroupParticipants(w.convId, listOf(carolAci), "add"))
225 job.cancel()
226 assertTrue(seen.any { it is SignalEvent.ParticipantAdded && it.participantId == carolAci }, "$seen")
227 val actions = GroupChange.Actions.parseFrom(assertNotNull(patch).body)
228 assertEquals(1, actions.version); assertEquals(1, actions.addMembersCount)
229 val member = actions.getAddMembers(0).added
230 assertEquals(Member.Role.DEFAULT, member.role)
231 val decrypted = ClientZkGroupCipher(w.secretParams)
232 .decrypt(UuidCiphertext(member.userId.toByteArray()))
233 assertTrue(decrypted.toString().contains(carolAci), "$decrypted")
234 }
235
236 @Test fun updateGroupParticipants_addRejected_emitsNothingAndKeepsServerVerdict() = runTest {
237 val w = world()
238 val (_, store) = wire { HResp(409, byteArrayOf(), "application/x-protobuf") }
239 val seen = mutableListOf<SignalEvent>()
240 val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } }
241 assertFalse(SignalClient.updateGroupParticipants(w.convId, listOf(carolAci), "add"))
242 job.cancel()
243 assertTrue(seen.none { it is SignalEvent.ParticipantAdded }, "$seen")
244 assertTrue(store.requests.any { it.method == "PATCH" })
245 }
246
247 // ---------- fetchGroupState via refreshGroup ----------
248
249 @Test fun refreshGroup_serverAccepted_fetchesStateAndUpdatesRow() = runTest {
250 val w = world(name = "Old", revision = 0)
251 val cipher = ClientZkGroupCipher(w.secretParams)
252 val titleBlob = GroupAttributeBlob.newBuilder().setTitle("Fresh title").build().toByteArray()
253 val group = Group.newBuilder()
254 .setTitle(ByteString.copyFrom(cipher.encryptBlob(titleBlob))).setVersion(12)
255 .addMembers(Member.newBuilder().setUserId(ByteString.copyFrom(
256 cipher.encrypt(ServiceId.Aci.parseFromString(bobAci)).serialize())).build())
257 .addMembers(Member.newBuilder().setUserId(ByteString.copyFrom(
258 cipher.encrypt(ServiceId.Aci.parseFromString(carolAci)).serialize())).build())
259 .build()
260 val (chat, store) = wire { req ->
261 if (req.method == "GET" && req.path == "/v2/groups/")
262 HResp(200, GroupResponse.newBuilder().setGroup(group).build().toByteArray(), "application/x-protobuf")
263 else HResp(404, "{}")
264 }
265 assertTrue(SignalClient.refreshGroup(w.convId))
266 val row = db.conversationDao().getConversation(w.convId)!!
267 assertEquals("Fresh title", row.name); assertEquals(12, row.groupRevision)
268 assertTrue(row.participants.contains(bobAci), row.participants)
269 assertTrue(row.participants.contains(carolAci), row.participants)
270 assertTrue(chat.requests.any { it.path == "/v1/certificate/auth/group" })
271 val get = store.requests.single { it.method == "GET" }
272 assertEquals("/v2/groups/", get.path)
273 assertTrue(store.header(get, "Authorization")!!.startsWith("Basic "))
274 }
275
276 @Test fun refreshGroup_storageNotFound_keepsRowAfterRealFetch() = runTest {
277 val w = world(name = "Old", revision = 3)
278 val (_, store) = wire { HResp(404, byteArrayOf(), "application/x-protobuf") }
279 assertFalse(SignalClient.refreshGroup(w.convId))
280 val row = db.conversationDao().getConversation(w.convId)!!
281 assertEquals("Old", row.name); assertEquals(3, row.groupRevision)
282 assertEquals(bobAci, row.participants)
283 assertTrue(store.requests.any { it.method == "GET" && it.path == "/v2/groups/" })
284 }
285
286 @Test fun refreshGroup_malformedGroupBytes_keepsRow() = runTest {
287 val w = world(name = "Old", revision = 1)
288 wire { HResp(200, byteArrayOf(-1, -1, -1), "application/x-protobuf") }
289 assertFalse(SignalClient.refreshGroup(w.convId))
290 val row = db.conversationDao().getConversation(w.convId)!!
291 assertEquals("Old", row.name); assertEquals(1, row.groupRevision)
292 }
293}