From 6f33f6f12897f65d7f6eb5b2ec7e70a2f20e25d3 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:03:50 +0200 Subject: [PATCH] feat: admin changes for the group's direct messages (group-threshold-ecdh, Phase 10) A device that sees its member removed as an admin forgets the room's kept conversation keys, its opened messages and its rounds, and says so in the room, once. Partials stop reaching it the moment the removal lands. A promoted admin answers rounds and reads the group's history; a share rotation after a removal leaves every kept key valid, since the group's key never changed. Co-Authored-By: Claude Opus 5.5 --- .../compose/database/model/ChatMessage.kt | 7 + .../giza/compose/managers/GroupDmReceiver.kt | 32 ++++ .../giza/compose/managers/GroupEcdhManager.kt | 11 +- .../managers/GroupDmAdminChangeJvmTest.kt | 156 ++++++++++++++++++ 4 files changed, 204 insertions(+), 2 deletions(-) create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmAdminChangeJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index c45323fc..650181a5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -527,6 +527,12 @@ data class ChatMessage( */ const val TYPE_GROUP_DM_RELAYS_SIGNED = "groupDmRelaysSigned" + /** + * This device forgot the group's direct messages on seeing its member removed as an + * admin. docs/group-threshold-ecdh.md, D14. + */ + const val TYPE_GROUP_DM_FORGOTTEN = "groupDmForgotten" + /** * Every line the group signed, for the one check the transcript * dispatches on. A type missing from here renders as a chat bubble, @@ -568,6 +574,7 @@ data class ChatMessage( TYPE_LEGACY_GROUP_RELAYS_SIGNED, TYPE_GROUP_POST_SIGNED, TYPE_GROUP_DM_RELAYS_SIGNED, + TYPE_GROUP_DM_FORGOTTEN, TYPE_LEGACY_GROUP_SCHEMA_SIGNED, TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_WALLET_NOT_TAKEN_PART_IN, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt index 36f6f018..9faa21b9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt @@ -171,6 +171,38 @@ object GroupDmReceiver { if (inserted > 0) logger.i { "Filed a message of kind ${rumor.kind} to ${roomId.take(8)}" } } + /** + * A device whose member is no longer one of [chatRoomId]'s admins forgets the room's mail: + * its kept conversation keys, what it opened and the rounds in flight, and says so in the + * room (D14). Cooperation, not enforcement -- what was read stays read -- and it is the + * device's own: the group cut it off from new mail the moment the removal landed (D4). + * Returns whether it forgot anything. + */ + suspend fun forgetIfRemoved(database: GizaDatabase, chatRoomId: HexKey, userPublicKey: HexKey): Boolean { + val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return false + if (userPublicKey in admins) return false + val dao = database.groupDmDao() + val holds = dao.getConversationKeys(chatRoomId).isNotEmpty() || dao.getMessages(chatRoomId).isNotEmpty() || + dao.getAllOpenRounds().any { it.chatRoomId == chatRoomId } || dao.newestWrapCreatedAt(chatRoomId) != null + if (!holds) return false + dao.wipeRoom(chatRoomId) + database.scrubFreedPages() + database.chatMessageDao().upsert( + mobi.giza.compose.database.model.ChatMessage( + senderPublicKey = userPublicKey, + isUserMessage = true, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = chatRoomId, + content = "You are no longer an admin, so this device forgot the group's direct messages", + messageType = mobi.giza.compose.database.model.ChatMessage.TYPE_GROUP_DM_FORGOTTEN, + ) + ) + logger.i { "Forgot ${chatRoomId.take(8)}'s direct messages: no longer an admin" } + return true + } + /** * What [ledger] waits on: how many more admins have to answer its open round, and which * current admins have not. Read from public rows only, so a screen can show it. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt index 9387e538..304767b7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt @@ -200,7 +200,12 @@ object GroupEcdhManager { return } if (innerEvent.kind != GroupEcdhEvents.PARTIALS) return - val context = contextFor(database, localChatRoom, userPublicKey, nostrPrivateKey) ?: return + val context = contextFor(database, localChatRoom, userPublicKey, nostrPrivateKey) + if (context == null) { + // Partials still reaching a device whose member was removed: it forgets (D14). + GroupDmReceiver.forgetIfRemoved(database, localChatRoom.chatRoom.id, userPublicKey) + return + } val sender = innerEvent.pubKey if (sender == userPublicKey) return val (senderId, senderHost) = context.admins[sender] ?: return @@ -288,7 +293,9 @@ object GroupEcdhManager { suspend fun sweep(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray) { database.chatRoomDao().getChatRoomListByUserPublicKey(userPublicKey).forEach { room -> runCatching { - contextFor(database, room, userPublicKey, nostrPrivateKey)?.let { advance(database, it) } + val context = contextFor(database, room, userPublicKey, nostrPrivateKey) + if (context != null) advance(database, context) + else GroupDmReceiver.forgetIfRemoved(database, room.chatRoom.id, userPublicKey) }.onFailure { logger.e("Could not advance the rounds of ${room.chatRoom.id}", it) } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmAdminChangeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmAdminChangeJvmTest.kt new file mode 100644 index 00000000..5f6fd9c3 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmAdminChangeJvmTest.kt @@ -0,0 +1,156 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip44Encryption.Nip44v2 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.KeyShareMember +import mobi.giza.compose.database.model.types.ShareGenerationState +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.groupdm.AdminSeal +import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents + +/** + * Phase 10 of docs/group-threshold-ecdh.md: admin changes need nothing new. A removed admin is + * cut off from new mail at once and forgets what it kept; a promoted one reads the history; + * and a share rotation leaves every kept key valid, because the group's key never changed (D1). + */ +class GroupDmAdminChangeJvmTest { + private val net = GroupDmNetwork(n = 4, t = 2) + private val a get() = net.devices[0] + private val b get() = net.devices[1] + private val c get() = net.devices[2] + private val d get() = net.devices[3] + + @BeforeTest + fun setUp() = runBlocking { + ExperimentalFeatures.groupDirectMessagesOverride = true + net.admins = net.members.take(3).toSet() + net.install() + net.all() + net.openMessages() + } + + @AfterTest + fun tearDown() { + net.close() + ExperimentalFeatures.groupDirectMessagesOverride = null + } + + private val sender = KeyPair() + + private suspend fun texts(device: GroupDmNetwork.Device) = + device.db.groupDmDao().getMessages(net.roomId).map { Event.fromJson(it.rumorJson).content }.sorted() + + @Test + fun `after C's removal a new message opens on A and B, and C gets no slot, opens nothing, and forgets`(): Unit = runBlocking { + net.receive(net.wrapFrom(sender, "before"), a, b, c) + net.pump() + assertEquals(listOf("before"), texts(c)) + assertNotNull(c.db.groupDmDao().getConversationKey(net.roomId, sender.pubKey.toHexKey())) + + net.admins = setOf(net.members[0], net.members[1]) + val after = net.wrapFrom(sender, "after") + net.receive(after, a, b, c) + val sentBefore = net.outbox(a).map { it.id }.toSet() + net.pump() + assertEquals(listOf("after", "before"), texts(a)) + assertEquals(listOf("after", "before"), texts(b)) + net.outbox(a).filter { it.id !in sentBefore && it.kind == GroupEcdhEvents.PARTIALS }.forEach { + assertFalse(net.hostKeys[2] in AdminSeal.parseSlots(it.tags).keys, "no slot for C") + } + + // C's device sees itself removed on its next sweep, and forgets. + GroupEcdhManager.sweep(c.db, c.publicKey, c.privateKey) + assertEquals(emptyList(), texts(c)) + assertEquals(emptyList(), c.db.groupDmDao().getConversationKeys(net.roomId)) + val line = c.db.chatMessageDao().getChatMessagesByChatRoomId(net.roomId).map { it.chatMessage } + .single { it.messageType == ChatMessage.TYPE_GROUP_DM_FORGOTTEN } + assertTrue("forgot" in line.content) + // Once: a second sweep has nothing to forget. + assertFalse(GroupDmReceiver.forgetIfRemoved(c.db, net.roomId, c.publicKey)) + } + + @Test + fun `after a promotion, the new admin's device answers rounds and reads the history`(): Unit = runBlocking { + net.receive(net.wrapFrom(sender, "history"), a, b, c, d) + net.pump() + assertEquals(emptyList(), texts(d)) + + net.admins = net.members.toSet() + // D's catch-up brings the old wrap; the others answer it although they combined long ago. + net.devices.forEach { device -> device.db.groupDmDao().getWrapsInState(net.roomId, "OPENED").firstOrNull()?.let { net.receive(Event.fromJson(it.wrapJson), d) } } + net.pump() + assertEquals(listOf("history"), texts(d)) + + // And D answers a new round as one of the admins, with A's app closed. + val fresh = net.wrapFrom(KeyPair(), "new") + net.receive(fresh, b, d) + net.pump(between = listOf(b, d)) + assertEquals(listOf("history", "new"), texts(d)) + assertEquals(listOf("history", "new"), texts(b)) + } + + @Test + fun `a share rotation after the removal leaves every kept key valid on A and B`(): Unit = runBlocking { + net.receive(net.wrapFrom(sender, "one"), a, b, c) + net.pump() + val keyBefore = a.db.groupDmDao().getConversationKey(net.roomId, sender.pubKey.toHexKey())!!.conversationKey + + net.admins = setOf(net.members[0], net.members[1]) + rotate(without = c) + assertEquals(1, a.context()!!.generation) + + // The kept key opens the next message's seal; only the wrap's round runs, at generation 1. + net.receive(net.wrapFrom(sender, "two"), a, b) + net.pump(between = listOf(a, b)) + assertEquals(listOf("one", "two"), texts(a)) + assertEquals(keyBefore, a.db.groupDmDao().getConversationKey(net.roomId, sender.pubKey.toHexKey())!!.conversationKey) + + // A new correspondent's key, made at generation 1, is the one their own app computes. + val newcomer = KeyPair() + net.receive(net.wrapFrom(newcomer, "hello"), a, b) + net.pump(between = listOf(a, b)) + val kept = a.db.groupDmDao().getConversationKey(net.roomId, newcomer.pubKey.toHexKey())!!.conversationKey + assertEquals(Nip44v2().computeConversationKey(newcomer.privKey!!, net.roomId.hexToByteArray()).toHex(), kept) + // C, rotated out and no longer an admin, takes no part. + assertNull(c.context()) + } + + /** Generation 1 on the same key, `s'ᵢ = sᵢ + k·(i+1)`, with [without] withheld, as a rotation would leave it. */ + private suspend fun rotate(without: GroupDmNetwork.Device) { + val k = PrivateKey(Crypto.sha256("rotation".encodeToByteArray())) + val shares = net.keyMaterial.secretShares.mapIndexed { id, s -> s + k * PrivateKey(ByteArray(32).also { it[31] = (id + 1).toByte() }) } + val publicShares = shares.joinToString(",") { it.publicKey().value.toHex() } + net.devices.forEach { device -> + val withheld = device === without + device.db.keyShareDao().upsert( + KeyShareGeneration( + dkgSessionId = net.ceremonyId, generation = 1, + secretShare = if (withheld) null else shares[net.idOf[device.index]].value.toHex(), + publicShares = publicShares, state = ShareGenerationState.ACTIVE, activatedAt = Clock.System.now(), + ) + ) + device.db.keyShareDao().upsert(net.members.indices.map { i -> + KeyShareMember(net.ceremonyId, 1, net.idOf[i], net.members[i], net.hostKeys[i], if (net.devices[i] === without) ShareStanding.RETIRED else ShareStanding.LIVE) + }) + } + } +}