diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7d7fdae0..da0a70a0 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -131,6 +131,7 @@ Require the group's signature for changes From then on, adding or removing a member, or changing who the admins are, is proposed and has to be signed by the group before it happens. Before changes can need the group's signature, %1$s need to update Giza. + Proposed; it happens once the group signs it Sent; changes will need the group's signature once a relay accepts it Stepping down; you'll leave once a relay accepts it Remove from group diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt index ae9dd30b..7853d805 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt @@ -7,6 +7,8 @@ import com.vitorpamplona.crypto.random.RandomInstance import com.vitorpamplona.marmot.appComponents.AdminPolicyV1 import com.vitorpamplona.marmot.appComponents.AppComponentIds import com.vitorpamplona.marmot.appComponents.GroupProfileV1 +import com.vitorpamplona.marmot.appComponents.GroupLifecycleV1 +import com.vitorpamplona.mls.components.ComponentsList import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent import com.vitorpamplona.marmot.groups.MlsGroupManager import com.vitorpamplona.marmot.groups.currentAdminIdentities @@ -61,6 +63,7 @@ import mobi.giza.compose.extensions.shortened import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.AdminGovernance import mobi.giza.compose.managers.GovernanceGate +import mobi.giza.compose.managers.GovernanceManager import mobi.giza.compose.managers.GovernanceMarker import mobi.giza.compose.managers.GovernanceSupport import mobi.giza.compose.managers.ChronicleManager @@ -639,6 +642,18 @@ abstract class MarmotOutboundDao( "An earlier change to this room is still waiting for a relay to accept it; try again in a moment" ) } + // A governed room: proposed and signed by the group; the Welcome goes out + // once a relay accepts the carried commit, as it does for a bare one. + // docs/member-admin-promotion.md, Phase 5. + if (!isOneMemberInitialGroupCreation && GovernanceGate.isGoverned(mlsGroup)) { + val room = database.chatRoomDao().findChatRoomById(chatRoomId) + ?: throw MarmotMissingChatGroupException("No room $chatRoomId") + GovernanceManager.propose( + database, room, userPublicKey, peerKeyPackageEventId = peerKeyPackage.id, + propose = GovernanceManager.addition(peerKeyPackage.tlsEncodedMarmotKeyPackage), + ) + return + } engine.awaitSettled(routingId) val staged = engine.groupManager.stageAddMember(routingId, peerKeyPackage.tlsEncodedMarmotKeyPackage) if (isOneMemberInitialGroupCreation) { @@ -847,6 +862,13 @@ abstract class MarmotOutboundDao( if (!group.isLocalAdmin() || !engine.groupManager.hasPendingProposals(routingId)) return if (!engine.gate.canPrepareLocalCommit(routingId)) return + // In a governed room a member's leave is committed inside this account's own + // envelope, not bare (docs/member-admin-promotion.md, D6). + if (GovernanceGate.isGoverned(group)) { + GovernanceManager.publishOwnCommit(database, localChatRoom) + return + } + publishGatedCommit(localChatRoom) { manager, id -> manager.stageCommit(id) } } @@ -886,6 +908,16 @@ abstract class MarmotOutboundDao( throw IllegalStateException("A group with a shared key needs at least $floor admins, so ${memberName(memberPublicKey)} can't be removed") } + // A governed room: one change, proposed and signed by the group -- the + // removal and, for an admin, their admin entry in the same commit, which a + // copy of the group can build where the manager cannot. + // docs/member-admin-promotion.md, Phase 5. + if (GovernanceGate.isGoverned(group)) { + val admins = group.currentAdminIdentities() + GovernanceManager.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, propose = GovernanceManager.removal(leafIndex, memberPublicKey, admins)) + return + } + if (memberPublicKey in group.currentAdminIdentities()) { thenAfterConfirmed(localChatRoom, publish = { publishAdmins(localChatRoom) { admins -> admins - memberPublicKey } }) { database.chatRoomDao().findChatRoomById(localChatRoom.chatRoom.id) @@ -1067,6 +1099,19 @@ abstract class MarmotOutboundDao( val group = engine.groupFor(routingId) ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}") require(group.isLocalAdmin()) { "Only an admin can disband the group" } + + // A governed room ends only with the group's signature. One that has not yet + // agreed it can be disbanded agrees to that first, as its own signed change. + if (GovernanceGate.isGoverned(group)) { + val me = localChatRoom.chatRoom.userPublicKey + if (group.currentGroupState().requires(AppComponentIds.GROUP_LIFECYCLE_V1)) { + GovernanceManager.propose(database, localChatRoom, me, propose = GovernanceManager.disbanding) + return + } + GovernanceManager.propose(database, localChatRoom, me, propose = GovernanceManager.enablingDisbanding) + throw IllegalStateException("The group first has to agree it can be disbanded, and that has been proposed. Disband again once the group has signed it") + } + if (!engine.gate.canPrepareLocalCommit(routingId)) { throw MarmotCommitPendingException( "An earlier change to this room is still waiting for a relay to accept it; try again in a moment" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceGate.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceGate.kt index cd8ce24f..70056556 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceGate.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceGate.kt @@ -2,6 +2,7 @@ package mobi.giza.compose.managers import com.vitorpamplona.marmot.groups.MarmotGroupPolicy import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.marmot.groups.currentGroupState import com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption import com.vitorpamplona.mls.codec.TlsReader import com.vitorpamplona.mls.framing.ContentType @@ -86,7 +87,10 @@ object GovernanceGate { val copy = MlsGroup.restore(group.saveState(), recorder) copy.processFramedCommit(mlsBytes) val seen = recorder.seen ?: return null - Inspection(seen.first, seen.second, seen.first.memberIdentityHex(seen.third), copy) + // Identities from the group as it stood before the commit, which [group] + // still is: the copy's view can already have a removed leaf blank. + val before = group.view() + Inspection(before, seen.second, before.memberIdentityHex(seen.third), copy) }.getOrNull() /** Why an envelope was refused, in words for the room. */ @@ -127,9 +131,12 @@ object GovernanceGate { if (requireSignature && !GovernanceStatementEvent.authorises(envelope, chatRoomId, group.epoch, change)) { return refuse("the group's signature is not on this change") } - val floor = minimumAdmins(group) ?: 1 - val admins = inspection.after.currentAdminIdentities() intersect inspection.after.currentMemberIdentities() - if (admins.size < floor) return refuse("it would leave fewer than $floor admins") + // A disband ends the group, so no floor applies to what it leaves. + if (!inspection.after.currentGroupState().isDisbanded) { + val floor = minimumAdmins(group) ?: 1 + val admins = inspection.after.currentAdminIdentities() intersect inspection.after.currentMemberIdentities() + if (admins.size < floor) return refuse("it would leave fewer than $floor admins") + } } OwnCommitEvent.KIND -> { if (!GovernanceChange.isExempt(inspection.proposals)) return refuse("only the group can sign a change like this one") diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt index d5778311..f537b4bf 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt @@ -31,6 +31,10 @@ import mobi.giza.compose.nostr.Relays import mobi.giza.compose.nostr.frost.GovernanceCarrierEvent import mobi.giza.compose.nostr.frost.GovernanceChange import mobi.giza.compose.nostr.frost.GovernanceStatementEvent +import mobi.giza.compose.nostr.frost.OwnCommitEvent +import com.vitorpamplona.marmot.appComponents.GroupLifecycleV1 +import com.vitorpamplona.marmot.appComponents.AdminPolicyV1 +import com.vitorpamplona.mls.components.ComponentsList /** * How a change to a governed room becomes a commit: built, signed by the group, then @@ -71,8 +75,13 @@ object GovernanceManager { val copy = MlsGroup.restore(prior, recorder) propose(copy) val result = copy.commit() - val (view, proposals, _) = checkNotNull(recorder.seen) { "The commit was built without being checked" } - val change = checkNotNull(GovernanceChange.of(view, proposals)) { "This change cannot be described, so the group could not approve it" } + val (_, proposals, _) = checkNotNull(recorder.seen) { "The commit was built without being checked" } + // Who a Remove names is read off the group as it stood before the commit: + // the copy's own view can already have the removed leaf blank. + val change = checkNotNull(GovernanceChange.of(live.view(), proposals)) { + "This change cannot be described, so the group could not approve it: " + + proposals.joinToString { it.proposal::class.simpleName.orEmpty() } + } val commitEvent: GroupEvent = NostrSignerInternal(KeyPair()).sign( GroupEvent.build( encryptedContentBase64 = GroupEventEncryption.encrypt(result.framedCommitBytes, result.preCommitExporterSecret), @@ -105,7 +114,9 @@ object GovernanceManager { } val prepared = prepare(live, routingId, propose) - GovernanceGate.minimumAdmins(live)?.let { floor -> + // A disband ends the group, so no floor applies to what it leaves behind. + val disbands = GroupLifecycleV1.COMPONENT_ID in prepared.change.components + GovernanceGate.minimumAdmins(live)?.takeUnless { disbands }?.let { floor -> val admins = prepared.change.admins ?: live.currentAdminIdentitiesSet() val remaining = admins - prepared.change.removes check(remaining.size >= floor) { "A group with a shared key needs at least $floor admins. Make someone else an admin first" } @@ -234,23 +245,106 @@ object GovernanceManager { MlsGroupState.decodeTls(proposal.pendingStateHex.hexToByteArray()), ) - // The carrier first, at this epoch: the gate raised after it. - val createdAt = Clock.System.now().epochSeconds - val payload = MarmotAppEvent.build( - pubKey = me, - kind = GovernanceCarrierEvent.KIND, - content = signed.toJson(), - createdAt = createdAt, - tags = GovernanceCarrierEvent.assembleTags(proposal.chatRoomId), - ).encodeToPayload() - val carrier = engine.outbound.buildGroupEventFromBytes(routingId, payload).signedEvent - val obligation = engine.gate.prepare(groupId = routingId, staged = staged, outboundBytes = result.framedCommitBytes, recipientScope = relays) - - // The commit is filed as the event it is, so a carrier coming back from a - // relay -- or carried again by another member -- is known for this one. val commitEvent = Event.fromJson(proposal.commitEventJson).let { GroupEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) } + sendEnvelope( + database = database, + chatRoomId = proposal.chatRoomId, + routingId = routingId, + me = me, + staged = staged, + commitEvent = commitEvent, + commitRow = commitRow, + carrierKind = GovernanceCarrierEvent.KIND, + carrierContent = signed.toJson(), + carrierTags = GovernanceCarrierEvent.assembleTags(proposal.chatRoomId), + relays = relays, + ) + database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.PUBLISHED, updatedAt = Clock.System.now())) + } + + /** + * Commits whatever members' own leaves are waiting in a governed room's pool, as + * an admin's device does on receipt -- inside this account's own envelope (D6), + * not bare. Nothing when nothing is waiting. + */ + suspend fun publishOwnCommit( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + relays: List = Relays.DefaultDMRelayList.map { it.url }, + ) { + val engine = database.marmotEngine + val routingId = localChatRoom.routingId + val me = localChatRoom.chatRoom.userPublicKey + if (!engine.groupManager.hasPendingProposals(routingId) || !engine.gate.canPrepareLocalCommit(routingId)) return + engine.awaitSettled(routingId) + val live = engine.groupFor(routingId) ?: return + val prepared = prepare(live, routingId) { } + // Only members' own leaves are ever pooled (MIP-03), and they need nobody's + // signature; anything else would not be this envelope's to carry. + check(prepared.change == GovernanceChange()) { "Only a member's own leave can be committed without the group's signature" } + val commitRow = MarmotCommitResult.from( + commitEventId = prepared.commitEvent.id, + commitResult = prepared.staged.result, + chatRoomId = localChatRoom.chatRoom.id, + userPublicKey = me, + peerKeyPackageEventId = MarmotCommitResult.NO_INVITEE, + isOneMemberInitialGroupCreation = false, + createdAt = Instant.fromEpochSeconds(prepared.commitEvent.createdAt), + ) + database.marmotCommitResultDao().upsert(commitRow) + sendEnvelope( + database = database, + chatRoomId = localChatRoom.chatRoom.id, + routingId = routingId, + me = me, + staged = prepared.staged, + commitEvent = prepared.commitEvent, + commitRow = commitRow, + carrierKind = OwnCommitEvent.KIND, + carrierContent = prepared.commitEvent.toJson(), + carrierTags = OwnCommitEvent.assembleTags(localChatRoom.chatRoom.id, prepared.epoch), + relays = relays, + ) + } + + /** + * Puts a commit on the wire inside an envelope: the envelope as an application + * message at the commit's epoch, then the publish gate raised with the staged + * state, the commit filed as the event it is -- so the envelope coming back is + * known for this device's own -- and the relay's OK on the envelope made the + * commit's confirmation, as `publishCommit` does for a bare one. + */ + private suspend fun sendEnvelope( + database: GizaDatabase, + chatRoomId: String, + routingId: HexKey, + me: HexKey, + staged: MlsGroupManager.StagedCommit, + commitEvent: GroupEvent, + commitRow: MarmotCommitResult, + carrierKind: Int, + carrierContent: String, + carrierTags: Array>, + relays: List, + ) { + val engine = database.marmotEngine + val payload = MarmotAppEvent.build( + pubKey = me, + kind = carrierKind, + content = carrierContent, + createdAt = Clock.System.now().epochSeconds, + tags = carrierTags, + ).encodeToPayload() + val carrier = engine.outbound.buildGroupEventFromBytes(routingId, payload).signedEvent + val obligation = engine.gate.prepare( + groupId = routingId, + staged = staged, + outboundBytes = staged.result.framedCommitBytes, + recipientScope = relays, + ) + listOf(commitEvent, carrier).forEach { event -> database.nostrEventDao().upsert( NostrEvent( @@ -261,17 +355,47 @@ object GovernanceManager { database.marmotGroupEventDao().upsert( MarmotGroupEvent( id = event.id, createdAt = Instant.fromEpochSeconds(event.createdAt), encryptedContent = event.encryptedContent(), - publicKey = event.pubKey, userPublicKey = me, expiresAt = null, chatRoomId = proposal.chatRoomId, signature = event.sig, + publicKey = event.pubKey, userPublicKey = me, expiresAt = null, chatRoomId = chatRoomId, signature = event.sig, ) ) } - // The relay's OK on the carrier is what confirms the commit: filed under the - // carrier's id, with the obligation, as `publishCommit` files a bare one. database.marmotCommitResultDao().upsert( commitRow.copy(id = carrier.id, obligationId = obligation.obligationId, createdAt = Instant.fromEpochSeconds(carrier.createdAt)) ) database.broadcastNostrEventRequestDao().insert(relays.map { BroadcastNostrEventRequest(nostrEventId = carrier.id, relayURL = it) }) - database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.PUBLISHED, updatedAt = Clock.System.now())) + } + + // --- The changes, as the proposals a copy of the group is given ---------------- + + /** Removing the member at [leafIndex], and their admin entry in the same commit when [admins] names [member]. */ + fun removal(leafIndex: Int, member: HexKey, admins: Set): (MlsGroup) -> Unit = { copy -> + copy.proposeRemove(leafIndex) + if (member in admins) { + copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins - member).encode()) + } + } + + /** Adding the holder of [keyPackageBytes]. */ + fun addition(keyPackageBytes: ByteArray): (MlsGroup) -> Unit = { copy -> copy.proposeAdd(keyPackageBytes) } + + /** Ending the group, as the library's own disband does: everyone else removed, this device its last admin. */ + val disbanding: (MlsGroup) -> Unit = { copy -> + copy.proposeAppDataUpdate(GroupLifecycleV1.COMPONENT_ID, GroupLifecycleV1.DISBANDED.encode()) + copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1(listOf(checkNotNull(copy.memberIdentity(copy.leafIndex)))).encode()) + for ((leafIndex, _) in copy.members()) { + if (leafIndex != copy.leafIndex) copy.proposeRemove(leafIndex) + } + } + + /** Agreeing the group can be disbanded, as the library's enablement does: the lifecycle component required, and active. */ + val enablingDisbanding: (MlsGroup) -> Unit = { copy -> + val dictionary = copy.appDataDictionary() + val required = ComponentsList.supportedOrRequired(dictionary).toMutableSet() + required.add(GroupLifecycleV1.COMPONENT_ID) + copy.proposeAppDataUpdate(ComponentsList.APP_COMPONENTS_ID, ComponentsList.encode(required)) + if (dictionary[GroupLifecycleV1.COMPONENT_ID] == null) { + copy.proposeAppDataUpdate(GroupLifecycleV1.COMPONENT_ID, GroupLifecycleV1.ACTIVE.encode()) + } } private suspend fun announce(database: GizaDatabase, chatRoomId: String, me: HexKey, content: String) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 4170bf84..4241f545 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -86,6 +86,8 @@ import mobi.giza.compose.resources.couldn_t_leave_the_group import mobi.giza.compose.resources.admin_change_requested import mobi.giza.compose.resources.stepping_down_to_leave import mobi.giza.compose.resources.require_signatures_sent +import mobi.giza.compose.resources.change_proposed +import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.resources.admin_badge import mobi.giza.compose.resources.holds_a_share import mobi.giza.compose.ui.view.state.AdminLeave @@ -196,6 +198,7 @@ fun ChatRoomDetailScreen( val adminChangeRequested = stringResource(Res.string.admin_change_requested) val steppingDownToLeave = stringResource(Res.string.stepping_down_to_leave) val requireSignaturesSent = stringResource(Res.string.require_signatures_sent) + val changeProposed = stringResource(Res.string.change_proposed) val adminLabel = stringResource(Res.string.admin_badge) val shareLabel = stringResource(Res.string.holds_a_share) val rotationRequested = stringResource(Res.string.share_rotation_requested) @@ -785,7 +788,10 @@ fun ChatRoomDetailScreen( localChatRoom = chatRoomDetailUIState.localChatRoom, memberPublicKey = memberPublicKey, ) { failure -> - notify(failure ?: removalRequested) + // In a governed room the removal is a proposal + // the group still has to sign. + val governed = chatRoomDetailUIState.governance is GovernanceStatus.Governed + notify(failure ?: if (governed) changeProposed else removalRequested) } } else { confirmingAdminChange = action to memberPublicKey diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 4759c5a0..35d4ed09 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -31,6 +31,7 @@ import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.navigation.routes.HomeRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState +import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.ui.view.state.SharesSummary class ChatRoomDetailViewModel( @@ -158,7 +159,10 @@ class ChatRoomDetailViewModel( // can still help sign until the shares are rotated without them. // A second act, offered rather than folded in -- it needs every // remaining holder (docs/frost-share-refresh.md, Phase 9). - if (failure == null && heldShare) rotationOffer = RotationOffer(localChatRoom, memberPublicKey) + // Not for a removal the group has yet to sign: they are still in the + // room, and the offer would come before the fact it is about. + val proposed = (chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.governance is GovernanceStatus.Governed + if (failure == null && heldShare && !proposed) rotationOffer = RotationOffer(localChatRoom, memberPublicKey) } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt index a4978c78..64547705 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt @@ -12,6 +12,7 @@ import com.vitorpamplona.quartz.nip01Core.core.toHexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync import kotlin.test.AfterTest +import mobi.giza.compose.extensions.toHex import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.nostr.frost.GovernanceSupportEvent import mobi.giza.compose.database.repository.DatabaseNostrRepository @@ -400,4 +401,112 @@ class GovernanceGateJvmTest { assertEquals(null, GovernanceManager.refusalOf(db, room(), unsigned(GovernanceChange(admins = setOf(dana.hex, userHex))))) assertNotNull(GovernanceManager.refusalOf(db, room(), unsigned(GovernanceChange(admins = setOf(dana.hex))))) } + + // --- Phase 5b: the room's ordinary changes, governed -------------------------- + + /** Erin added by Dana inside the group's signature, joined from the Welcome. */ + private suspend fun erinAddedSigned() { + MarmotStandIn.seedProfile(db, erin.hex, "Erin") + erin.makeBundle() + val epoch = appGroup().epoch + val staged = dana.manager.stageAddMember(routingId, erin.bundle.keyPackage.toTlsBytes()) + val added = mobi.giza.compose.nostr.frost.AddedMember(erin.hex, erin.bundle.keyPackage.reference().toHex()) + danaCarries(statement(commitEvent(staged.result), GovernanceChange(adds = setOf(added)), epoch)) + dana.manager.installState(routingId, staged.pendingState) + erin.manager.processWelcome(assertNotNull(staged.result.welcomeBytes), erin.bundle) + erin.inbound.trackGroup(routingId) + assertTrue(erin.hex in appGroup().currentMemberIdentities(), "Erin's signed add did not land") + } + + /** Dana applies the commit inside the carrier this device sent. */ + private suspend fun danaFollows(carrier: GroupEvent) { + val carried = assertIs(dana.inbound.processGroupEvent(carrier)) + val envelope = Event.fromJson(carried.innerEventJson) + val statement = GovernanceCarrierEvent.statementOf(envelope) ?: envelope + dana.inbound.processGroupEvent(assertNotNull(mobi.giza.compose.nostr.frost.GovernanceEvents.innerCommitOf(statement))) + } + + @Test + fun `a member's leave is committed by an admin's device inside its own envelope`() = runBlocking { + governedRoom() + appIsAdmin() + erinAddedSigned() + val epoch = appGroup().epoch + + val (framed, exporter) = erin.manager.leaveGroup(routingId) + val leave = com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal(KeyPair()).sign( + GroupEvent.build(encryptedContentBase64 = com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption.encrypt(framed, exporter), nostrGroupId = routingId) + ) + // Every member pools the proposal; the commit only refers to it. + dana.inbound.processGroupEvent(leave) + MarmotStandIn.storeInApp(db, user, leave) + val carrier = okTheLatestCommit() + + assertEquals(epoch + 1, appGroup().epoch) + assertFalse(erin.hex in appGroup().currentMemberIdentities(), "Erin is still in the tree") + danaFollows(carrier) + assertFalse(erin.hex in dana.manager.getGroup(routingId)!!.currentMemberIdentities(), "Dana is in another group") + } + + @Test + fun `removing an admin is one signed commit that takes their admin entry with them`() = runBlocking { + governedRoom() + appIsAdmin() + val epoch = appGroup().epoch + val danaLeaf = appGroup().members().first { (_, leaf) -> + (leaf.credential as com.vitorpamplona.mls.tree.Credential.Basic).identity.toHexKey() == dana.hex + }.first + + val prepared = GovernanceManager.prepare(appGroup(), routingId, GovernanceManager.removal(danaLeaf, dana.hex, appGroup().currentAdminIdentities())) + val signed = statement(prepared.commitEvent, prepared.change, prepared.epoch) + assertEquals(GovernanceChange(removes = setOf(dana.hex), admins = setOf(userHex)), prepared.change) + GovernanceManager.publish(db, GovernanceManager.record(db, room(), userHex, prepared, signed.id, "s"), signed) + okTheLatestCommit() + + assertEquals(epoch + 1, appGroup().epoch, "the removal took more than one commit") + assertEquals(setOf(userHex), appGroup().currentAdminIdentities()) + assertFalse(dana.hex in appGroup().currentMemberIdentities()) + assertTrue(lines(ChatMessage.TYPE_ADMIN_REMOVED).isEmpty(), "a departure was captioned twice") + } + + @Test + fun `an invite signed by the group sends its Welcome once the carrier is accepted`() = runBlocking { + governedRoom() + appIsAdmin() + MarmotStandIn.seedProfile(db, erin.hex, "Erin") + erin.makeBundle() + val welcomesBefore = db.giftWrapPayloadDao().getAllGiftWrapUnsigned().count { it.kind == com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent.KIND } + val packageRow = mobi.giza.compose.database.model.MarmotKeyPackage( + id = erin.hex, publicKey = erin.hex, + tlsEncodedMarmotKeyPackage = erin.bundle.keyPackage.toTlsBytes(), profile = mobi.giza.compose.nostr.MarmotProfile.CURRENT.wireName, + ) + db.participantDao().upsert(listOf(mobi.giza.compose.database.model.Participant(participantPublicKey = erin.hex, chatRoomId = roomId, relayHint = null))) + + val prepared = GovernanceManager.prepare(appGroup(), routingId, GovernanceManager.addition(packageRow.tlsEncodedMarmotKeyPackage)) + val signed = statement(prepared.commitEvent, prepared.change, prepared.epoch) + GovernanceManager.publish(db, GovernanceManager.record(db, room(), userHex, prepared, signed.id, "s", peerKeyPackageEventId = packageRow.id), signed) + assertEquals(welcomesBefore, db.giftWrapPayloadDao().getAllGiftWrapUnsigned().count { it.kind == com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent.KIND }, "the Welcome went before the commit was accepted") + + okTheLatestCommit() + + assertTrue(erin.hex in appGroup().currentMemberIdentities()) + assertEquals(welcomesBefore + 1, db.giftWrapPayloadDao().getAllGiftWrapUnsigned().count { it.kind == com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent.KIND }, "no Welcome for Erin") + } + + @Test + fun `a removal signed by the group, from another member, lands here`() = runBlocking { + governedRoom() + erinAddedSigned() + val epoch = appGroup().epoch + val erinLeaf = dana.manager.getGroup(routingId)!!.members().first { (_, leaf) -> + (leaf.credential as com.vitorpamplona.mls.tree.Credential.Basic).identity.toHexKey() == erin.hex + }.first + + val staged = dana.manager.stageRemoveMember(routingId, erinLeaf) + danaCarries(statement(commitEvent(staged.result), GovernanceChange(removes = setOf(erin.hex)), epoch)) + + assertEquals(epoch + 1, appGroup().epoch, "a signed removal was refused at the door") + assertFalse(erin.hex in appGroup().currentMemberIdentities()) + assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).isEmpty()) + } }