diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 1fce5938..7d7fdae0 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -127,6 +127,11 @@ You're the only admin. Pick someone to make an admin before you leave. Make admin and leave Disband group instead + Changes to who is in this group need the group's signature. It always keeps at least %1$d admins. + 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. + 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 Disband 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 f0330b91..ae9dd30b 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 @@ -6,6 +6,7 @@ import co.touchlab.kermit.Logger 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.foundation.appEvents.MarmotAppEvent import com.vitorpamplona.marmot.groups.MlsGroupManager import com.vitorpamplona.marmot.groups.currentAdminIdentities @@ -59,6 +60,9 @@ import mobi.giza.compose.extensions.exporterSecret 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.GovernanceMarker +import mobi.giza.compose.managers.GovernanceSupport import mobi.giza.compose.managers.ChronicleManager import mobi.giza.compose.managers.MarmotGroupFactory import mobi.giza.compose.managers.MarmotInboundManager @@ -989,6 +993,42 @@ abstract class MarmotOutboundDao( } } + /** + * Makes a keyed room's changes need the group's signature from the next epoch: + * one ordinary commit adding [GovernanceMarker]'s line to the profile + * description, with the floor the room's quorum sets. It is the room's last bare + * commit, and every device that applies it enforces the rule from the state it + * just applied. docs/member-admin-promotion.md, D4 and Phase 4b. + * + * Refused while any member has not said their device can follow signed commits + * -- they would be left in a different group by the first change -- and while + * the room has fewer admins than the floor it would set. + */ + @Transaction + open suspend fun requireSignatures(localChatRoom: LocalChatRoom) { + val group = governedGroup(localChatRoom) + val roomId = localChatRoom.chatRoom.id + check(AdminGovernance.isKeyedRoom(group)) { "Only a group with a shared key can require its signature" } + if (GovernanceGate.isGoverned(group)) return + val missing = GovernanceSupport.missing(database, roomId, group) + if (missing.isNotEmpty()) { + throw IllegalStateException("Waiting for ${missing.map { memberName(it) }.sorted().joinToString()} to update Giza") + } + val floor = AdminGovernance.adminFloor(database, roomId, group) + val admins = group.currentAdminIdentities() intersect AdminGovernance.members(group) + check(admins.size >= floor) { "A group with a shared key needs at least $floor admins first" } + + publishGatedCommit(localChatRoom) { manager, id -> + val live = manager.getGroup(id) ?: throw MarmotMissingChatGroupException("No live group for $id") + val profile = live.currentGroupState().profile ?: throw IllegalStateException("The group has no profile to record the rule in") + manager.stageAppDataUpdate( + id, + GroupProfileV1.COMPONENT_ID, + GroupProfileV1(profile.name, GovernanceMarker.describe(profile.description, floor)).encode(), + ) + } + } + /** The room's live group, when this device may change who administers it. */ private suspend fun governedGroup(localChatRoom: LocalChatRoom): MlsGroup { require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room has admins to change" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 5fc32356..1ccd8dba 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -7,6 +7,8 @@ import com.vitorpamplona.marmot.GroupEventResult import com.vitorpamplona.marmot.groups.MarmotGroupPolicy import com.vitorpamplona.marmot.groups.currentAdminIdentities import mobi.giza.compose.managers.GovernanceGate +import mobi.giza.compose.managers.GovernanceSupport +import mobi.giza.compose.nostr.frost.GovernanceSupportEvent import mobi.giza.compose.nostr.frost.GovernanceEvents import mobi.giza.compose.nostr.frost.GovernanceCarrierEvent import mobi.giza.compose.nostr.frost.OwnCommitEvent @@ -1670,6 +1672,16 @@ abstract class NostrDao( // A change to a governed room, inside the group's signature or, // for a member's own leave, its committer's. Checked, and its // commit applied, only here (docs/member-admin-promotion.md). + // Another member says their device follows signed commits: + // this one says so back, once, so that a member who never + // opens the room's screen is still counted (Phase 4b). + innerEvent.kind == GovernanceSupportEvent.KIND -> + if (localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { + database.marmotEngine.groupFor(localChatRoom.routingId)?.let { group -> + GovernanceSupport.announce(database, localChatRoom.chatRoom.id, group, activeKeyPair.pubKey.toHex()) + } + } + innerEvent.kind == OwnCommitEvent.KIND -> admitEnvelopedCommit(localChatRoom, innerEvent, activeKeyPair) innerEvent.kind == GovernanceCarrierEvent.KIND -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index ea1c9d92..d59d9826 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -8,6 +8,8 @@ import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import mobi.giza.compose.managers.AdminGovernance +import mobi.giza.compose.managers.GovernanceGate +import mobi.giza.compose.managers.GovernanceSupport import mobi.giza.compose.managers.MarmotInboundManager import mobi.giza.compose.managers.CeremonyFollowThrough import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl @@ -44,6 +46,7 @@ import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.identity.Identity import mobi.giza.compose.identity.toKeyPair import mobi.giza.compose.managers.ShareRefreshManager +import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.ui.view.state.SharesSummary import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.database.model.types.ShareRepairStage @@ -658,6 +661,22 @@ class DatabaseChatRepository( return AdminGovernance.adminFloor(database, chatRoomId, group) } + override suspend fun governanceStatus(chatRoomId: String): GovernanceStatus? { + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return null + if (room.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return null + val group = database.marmotEngine.groupFor(room.routingId) ?: return null + if (!AdminGovernance.isKeyedRoom(group)) return null + GovernanceGate.minimumAdmins(group)?.let { return GovernanceStatus.Governed(it) } + if (room.chatRoom.leftGroupAt == null) GovernanceSupport.announce(database, chatRoomId, group, room.chatRoom.userPublicKey) + val missing = GovernanceSupport.missing(database, chatRoomId, group) + return if (missing.isEmpty()) GovernanceStatus.Ready(AdminGovernance.adminFloor(database, chatRoomId, group)) + else GovernanceStatus.Waiting(missing) + } + + override suspend fun requireSignatures(localChatRoom: LocalChatRoom) { + database.marmotOutboundDao().requireSignatures(localChatRoom) + } + override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) { database.marmotOutboundDao().promote(localChatRoom, memberPublicKey) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt new file mode 100644 index 00000000..88b4469e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt @@ -0,0 +1,62 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.mls.group.MlsGroup +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.nostr.frost.GovernanceSupportEvent + +/** + * Who in a keyed room has said their device follows signed commits, and this + * device saying it. docs/member-admin-promotion.md, D4 and Phase 4b. + * + * The rule cannot be switched on while anybody in the room would be left behind + * by it: a device that does not know it applies the bare commits Giza drops and + * reads none of the envelopes, and is in a different group from the first change. + * So each device says, once per room, that it can follow -- and says it back when + * it hears another say it, which is how a member who never opens the room's screen + * still gets counted. + */ +object GovernanceSupport { + + /** The accounts that have said, in [chatRoomId], that they follow signed commits. */ + suspend fun supporters(database: GizaDatabase, chatRoomId: String): Set = + database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GovernanceSupportEvent.KIND)) + .filter { row -> row.tags.any { it.size >= 2 && it[0] == GovernanceSupportEvent.VERSION_TAG && it[1] == GovernanceSupportEvent.VERSION } } + .map { it.publicKey } + .toSet() + + /** The members of [group] who have not said it yet. */ + suspend fun missing(database: GizaDatabase, chatRoomId: String, group: MlsGroup): Set = + AdminGovernance.members(group) - supporters(database, chatRoomId) + + /** + * Says, for [me], that this device follows signed commits in [chatRoomId] -- once: + * nothing happens when it already has. Only in a keyed room, which is the only + * kind the rule can be switched on in. Returns whether it said it now. + */ + suspend fun announce(database: GizaDatabase, chatRoomId: String, group: MlsGroup, me: HexKey): Boolean { + if (!AdminGovernance.isKeyedRoom(group)) return false + if (me in supporters(database, chatRoomId)) return false + val tags = GovernanceSupportEvent.assembleTags(chatRoomId) + val createdAt = Clock.System.now().epochSeconds + val id = EventHasher.hashId(pubKey = me, createdAt = createdAt, kind = GovernanceSupportEvent.KIND, tags = tags, content = "") + // Unsent: the outbound worker puts an inner event with no group event behind + // it into the room, as it does for every manager's messages. + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = me, + kind = GovernanceSupportEvent.KIND, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = "", + chatRoomId = chatRoomId, + ) + ) + return true + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index 6bf895f1..577505da 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -21,6 +21,7 @@ import mobi.giza.compose.managers.MarmotGroupCreation import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.nostr.MarmotProfile +import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.ui.view.state.SharesSummary interface ChatRepository { @@ -274,6 +275,16 @@ interface ChatRepository { */ suspend fun adminFloor(chatRoomId: String): Int + /** + * Where a keyed room stands on needing the group's signature, or null for any + * other room. Says, for this device, that it follows signed commits, if it has + * not yet. docs/member-admin-promotion.md, Phase 4b. + */ + suspend fun governanceStatus(chatRoomId: String): GovernanceStatus? + + /** Makes a keyed room's changes need the group's signature. Throws with words a person can act on. */ + suspend fun requireSignatures(localChatRoom: LocalChatRoom) + /** * Removes [memberPublicKey] from a current-profile room this device administers: * a commit through the publish gate, applied when a relay accepts it. See @@ -523,6 +534,10 @@ interface ChatRepository { override suspend fun adminFloor(chatRoomId: String): Int = 1 + override suspend fun governanceStatus(chatRoomId: String): GovernanceStatus? = null + + override suspend fun requireSignatures(localChatRoom: LocalChatRoom) = Unit + override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit override suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) = Unit 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 2189e571..4170bf84 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 @@ -85,6 +85,7 @@ import mobi.giza.compose.ui.theme.spacing 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.admin_badge import mobi.giza.compose.resources.holds_a_share import mobi.giza.compose.ui.view.state.AdminLeave @@ -194,6 +195,7 @@ fun ChatRoomDetailScreen( val couldNotLeave = stringResource(Res.string.couldn_t_leave_the_group) 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 adminLabel = stringResource(Res.string.admin_badge) val shareLabel = stringResource(Res.string.holds_a_share) val rotationRequested = stringResource(Res.string.share_rotation_requested) @@ -836,6 +838,23 @@ fun ChatRoomDetailScreen( HorizontalDivider() } + // Whether the room's changes need the group's signature, and the + // switch that makes them. docs/member-admin-promotion.md, Phase 4b. + chatRoomDetailUIState.governance?.let { governance -> + item { + GovernanceSection( + governance = governance, + canGovern = chatRoomDetailUIState.canGovern, + nameOf = nameOf, + onRequireSignatures = { + chatRoomDetailViewModel.requireSignatures(chatRoomDetailUIState.localChatRoom) { failure -> + notify(failure ?: requireSignaturesSent) + } + }, + ) + } + } + if (chatRoomDetailUIState.isDisbanded) { item { Text( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt index 64a6710a..08b4ac14 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt @@ -9,6 +9,7 @@ import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.Verified import androidx.compose.material3.AlertDialog import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem @@ -31,6 +32,10 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.cancel import mobi.giza.compose.resources.disband_group_instead +import mobi.giza.compose.resources.governance_on +import mobi.giza.compose.resources.governance_waiting +import mobi.giza.compose.resources.require_signatures +import mobi.giza.compose.resources.require_signatures_explainer import mobi.giza.compose.resources.make_admin import mobi.giza.compose.resources.make_admin_and_leave import mobi.giza.compose.resources.make_admin_body @@ -49,7 +54,9 @@ import mobi.giza.compose.resources.step_down_as_admin import mobi.giza.compose.resources.step_down_body import mobi.giza.compose.resources.step_down_title import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.composable.widgets.Decorative import mobi.giza.compose.ui.view.state.AdminLeave +import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.ui.view.state.MemberAction import org.jetbrains.compose.resources.stringResource @@ -188,3 +195,52 @@ internal fun LeaveAsAdminDialog( dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } }, ) } + +/** + * Whether a keyed room's changes need the group's signature. Once they do, a line + * saying so; before, for an admin, the switch -- or who it is still waiting on, + * since switching it on with a member whose device cannot follow would leave them + * in a different group from the first change. docs/member-admin-promotion.md, Phase 4b. + */ +@Composable +internal fun GovernanceSection( + governance: GovernanceStatus, + canGovern: Boolean, + nameOf: (HexKey) -> String, + onRequireSignatures: () -> Unit, +) { + val explainer = Modifier.padding( + horizontal = MaterialTheme.spacing.containerPadding, + vertical = MaterialTheme.spacing.compactPadding, + ) + Column(modifier = Modifier.fillMaxWidth()) { + when (governance) { + is GovernanceStatus.Governed -> Text( + text = stringResource(Res.string.governance_on, governance.minimumAdmins), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = explainer, + ) + is GovernanceStatus.Ready -> if (canGovern) { + TextButton(onClick = onRequireSignatures) { + Icon(Icons.Default.Verified, contentDescription = Decorative) + Text(stringResource(Res.string.require_signatures), modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap)) + } + Text( + text = stringResource(Res.string.require_signatures_explainer), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = explainer, + ) + } + is GovernanceStatus.Waiting -> if (canGovern) { + Text( + text = stringResource(Res.string.governance_waiting, governance.missing.map(nameOf).sorted().joinToString()), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = explainer, + ) + } + } + } +} 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 9a6afcf1..4759c5a0 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 @@ -132,6 +132,9 @@ class ChatRoomDetailViewModel( }, memberActions = group?.takeIf { canGovern }?.let { AdminGovernance.memberActions(it, me, chatRepository.adminFloor(chatRoomId)) }.orEmpty(), adminLeave = group?.takeIf { roomIsOpen }?.let { AdminGovernance.adminLeave(it, me) }, + governance = runCatching { chatRepository.governanceStatus(chatRoomId) } + .onFailure { if (it is CancellationException) throw it } + .getOrNull(), ) } } @@ -175,6 +178,10 @@ class ChatRoomDetailViewModel( } } + /** Makes the room's changes need the group's signature. docs/member-admin-promotion.md, Phase 4b. */ + fun requireSignatures(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) = + adminAction(onDone) { chatRepository.requireSignatures(localChatRoom) } + fun makeAdmin(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (String?) -> Unit) = adminAction(onDone) { chatRepository.promoteMember(localChatRoom, memberPublicKey) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 0a73fcd9..1b340f37 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -101,6 +101,8 @@ sealed interface ChatRoomDetailUIState { val memberActions: Map> = emptyMap(), /** How **Leave group** goes when this device is an admin; null when it is not. */ val adminLeave: AdminLeave? = null, + /** Where a keyed room stands on needing the group's signature; null for any other room. */ + val governance: GovernanceStatus? = null, ): ChatRoomDetailUIState data class Error( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt new file mode 100644 index 00000000..cc6f0897 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt @@ -0,0 +1,18 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey + +/** + * Where a keyed room stands on needing the group's signature for its changes. + * docs/member-admin-promotion.md, R2 and Phase 4b. + */ +sealed interface GovernanceStatus { + /** It does: every change is proposed, signed by the group, and only then applied. */ + data class Governed(val minimumAdmins: Int) : GovernanceStatus + + /** It does not yet, and every member's device could follow if it were switched on. */ + data class Ready(val minimumAdmins: Int) : GovernanceStatus + + /** It does not yet, and these members have not said their device could follow. */ + data class Waiting(val missing: Set) : GovernanceStatus +} 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 c9ca220b..daea9fbd 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,12 @@ 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.ui.view.state.GovernanceStatus +import mobi.giza.compose.nostr.frost.GovernanceSupportEvent +import mobi.giza.compose.database.repository.DatabaseNostrRepository +import mobi.giza.compose.database.repository.DatabaseChatRepository +import kotlin.test.assertIs +import kotlin.test.assertFailsWith import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -42,6 +48,8 @@ class GovernanceGateJvmTest { private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) private val marmotRepository = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default)) + private val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default)) + private val nostrRepository = DatabaseNostrRepository(db, CoroutineScope(Dispatchers.Default)) @AfterTest fun closeDb() = db.close() @@ -207,4 +215,96 @@ class GovernanceGateJvmTest { assertEquals(epoch + 1, appGroup().epoch) assertEquals(setOf(dana.hex, userHex), appGroup().currentAdminIdentities()) } + + // --- Phase 4b: who can follow, and the switch --------------------------------- + + private val erin = MarmotStandIn() + + /** Erin joins Dana's room, by Dana's bare commit; the app applies it. */ + private suspend fun erinJoins() { + MarmotStandIn.seedProfile(db, erin.hex, "Erin") + erin.makeBundle() + val add = dana.commitLocally(routingId) { dana.manager.addMember(routingId, erin.bundle.keyPackage.toTlsBytes()) } + erin.manager.processWelcome(assertNotNull(add.welcomeBytes), erin.bundle) + erin.inbound.trackGroup(routingId) + MarmotStandIn.storeInApp(db, user, commitEvent(add)) + } + + /** Dana makes [admins] the admin list by a bare commit, which Erin and the app apply. */ + private suspend fun danaSetsAdminsBare(admins: List) { + val commit = dana.commitLocally(routingId) { + val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins).encode()) + dana.manager.installState(routingId, staged.pendingState) + staged.result + } + val event = commitEvent(commit) + erin.inbound.processGroupEvent(event) + MarmotStandIn.storeInApp(db, user, event) + } + + /** [member] says, in the room, that their device follows signed commits. */ + private suspend fun says(member: MarmotStandIn) { + val payload = MarmotAppEvent.build( + pubKey = member.hex, kind = GovernanceSupportEvent.KIND, content = "", createdAt = 1_700_000_002, + tags = GovernanceSupportEvent.assembleTags(roomId), + ).encodeToPayload() + MarmotStandIn.storeInApp(db, user, member.outbound.buildGroupEventFromBytes(routingId, payload).signedEvent) + } + + private suspend fun room() = db.chatRoomDao().findChatRoomById(roomId)!! + + /** The relay's OK on the newest commit this device put on the wire. */ + private suspend fun okTheLatestCommit(): GroupEvent { + val event = db.nostrEventDao().getMLSGroupEvents(since = kotlin.time.Instant.fromEpochSeconds(0), limit = 50) + .filter { it.kind == GroupEvent.KIND } + .filter { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null } + .first { db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(it.id)?.status == "pending" } + nostrRepository.broadcastProcessed(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id)!!, "published") + return event.toGroupEvent(userHex)!! + } + + @Test + fun `hearing another member say it, this device says it back`() = runBlocking { + governedRoom(governed = false) + assertFalse(userHex in GovernanceSupport.supporters(db, roomId)) + + says(dana) + + assertTrue(userHex in GovernanceSupport.supporters(db, roomId), "the app did not answer") + assertTrue(dana.hex in GovernanceSupport.supporters(db, roomId)) + } + + @Test + fun `the switch waits for every member, then turns the rule on for everyone`() = runBlocking { + governedRoom(governed = false) + erinJoins() + danaSetsAdminsBare(listOf(dana.hex, userHex, erin.hex)) + says(dana) + + val waiting = assertIs(chatRepository.governanceStatus(roomId)) + assertEquals(setOf(erin.hex), waiting.missing) + val refusal = assertFailsWith { chatRepository.requireSignatures(room()) } + assertTrue("Erin" in refusal.message.orEmpty(), refusal.message) + + says(erin) + assertEquals(GovernanceStatus.Ready(minimumAdmins = 3), chatRepository.governanceStatus(roomId)) + + chatRepository.requireSignatures(room()) + val switch = okTheLatestCommit() + + assertEquals(3, GovernanceGate.minimumAdmins(appGroup()), "the rule is not on here") + dana.inbound.processGroupEvent(switch) + assertEquals(3, GovernanceMarker.minimumAdmins(dana.manager.getGroup(routingId)!!.roomDescription()), "the rule did not reach Dana") + assertEquals(GovernanceStatus.Governed(3), chatRepository.governanceStatus(roomId)) + + // And from here, Dana's bare commit is refused. + val epoch = appGroup().epoch + val bare = dana.commitLocally(routingId) { + val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(listOf(dana.hex, userHex)).encode()) + dana.manager.installState(routingId, staged.pendingState) + staged.result + } + MarmotStandIn.storeInApp(db, user, commitEvent(bare)) + assertEquals(epoch, appGroup().epoch, "a bare commit landed after the switch") + } }