From c7d46258ebabb5770db76e873514c3fbfa31d142 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 10:55:19 +0200 Subject: [PATCH] feat: admin changes and rotations take turns (admin-change-rotation, Phases 3 and 4) A change that moves who holds a share -- any change of admins, or the removal of a holder -- is refused while a rotation is under way, until its key state is signed, and so are offers and step-down requests. A step-down request or an accepted offer that arrives meanwhile waits and is taken up on the next pass. A removal whose owed rotation would fail the majority rule is refused before anyone signs (A12). The member rows list the rotation as the reason, with whom it waits on. rotateAway no longer takes a running rotation that still deals to the removed member for the one it owes, which left them a live share and said nothing. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 4 + .../compose/database/dao/ShareRefreshDao.kt | 4 + .../repository/DatabaseChatRepository.kt | 24 +++++- .../giza/compose/managers/AdminGovernance.kt | 46 ++++++++++- .../managers/GovernanceFollowThrough.kt | 21 ++++- .../compose/managers/GovernanceManager.kt | 4 + .../compose/managers/MemberActionPolicy.kt | 17 +++- .../giza/compose/managers/PromotionManager.kt | 6 ++ .../compose/managers/ShareRefreshManager.kt | 16 ++++ .../MemberActionUnavailableScreen.kt | 18 +++++ .../model/MemberActionUnavailableViewModel.kt | 1 + .../compose/ui/view/state/MemberAction.kt | 7 ++ .../managers/MemberActionPolicyTest.kt | 23 ++++++ .../compose/managers/GovernanceGateJvmTest.kt | 66 +++++++++++++++- .../managers/ShareRefreshRitualJvmTest.kt | 77 +++++++++++++++++-- 15 files changed, 316 insertions(+), 18 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 12f1e60d..925f98f3 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -581,6 +581,10 @@ A relay hasn't accepted the last change to this group yet. This clears by itself. %1$s has already been asked They've been offered admin and haven't answered yet. + The group's shares are being rotated + Admins can change once the group has signed the new shares. This clears by itself. + Waiting on %1$s. Admins can change once the group has signed the new shares. + See the rotation Also in the way You can do this now Nothing stands in the way any more. Go back to the group to do it. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt index bb4d1fee..f540657a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt @@ -35,6 +35,10 @@ abstract class ShareRefreshDao { @Query("SELECT * FROM ShareRefreshSession WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED') ORDER BY createdAt ASC") abstract suspend fun getRunningSessionsFor(userPublicKey: HexKey): List + /** How many refreshes are running on this device: what an admin change waits on. */ + @Query("SELECT COUNT(*) FROM ShareRefreshSession WHERE stage NOT IN ('COMPLETE', 'FAILED')") + abstract fun observeRunningCount(): Flow + @Query("SELECT * FROM ShareRefreshSession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") abstract fun observeSessionsForRoom(chatRoomId: String): Flow> 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 883b5ce9..d910e73d 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 @@ -62,6 +62,7 @@ import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.ui.view.state.MemberActionOption import mobi.giza.compose.managers.RotationHold +import mobi.giza.compose.ui.view.state.MemberActionBlocker import mobi.giza.compose.ui.view.state.SharesSummary import mobi.giza.compose.ui.view.state.RotationPreview import mobi.giza.compose.database.model.types.ShareStanding @@ -753,12 +754,33 @@ class DatabaseChatRepository( changePending = engine.groupFor(localChatRoom.routingId) != null && !engine.gate.canPrepareLocalCommit(localChatRoom.routingId), offeredAdmin = if (context.isKeyed) PromotionManager.unansweredOfferTargets(database, chatRoom.id) else emptySet(), - ) + ).let { if (it.isKeyed) withShares(localChatRoom, it) else it } } } return MemberActionPolicy.options(context, rows) } + /** + * [context] with what the room's shares say about its member rows: a rotation + * still under way, and whom it waits on, and who holds a live share. + * docs/admin-change-rotation.md, Phase 3. + */ + private suspend fun withShares(localChatRoom: LocalChatRoom, context: MemberActionContext): MemberActionContext { + val key = AdminGovernance.keyOf(database, localChatRoom.chatRoom.id) ?: return context + val holders = ShareGenerations.active(database, key).roster + .filter { it.standing == ShareStanding.LIVE } + .map { it.memberPublicKey } + .toSet() + val pending = AdminGovernance.adminChangeHold(database, localChatRoom)?.let { hold -> + val waitingOn = (hold as? RotationHold.Running) + ?.let { database.shareRefreshDao().getSessionById(it.refreshId) } + ?.let { ShareRefreshManager.progress(database, it)?.waitingOn } + .orEmpty() + MemberActionBlocker.RotationPending(waitingOn.toSet()) + } + return context.copy(rotationPending = pending, shareHolders = holders) + } + override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) { database.marmotOutboundDao().promote(localChatRoom, memberPublicKey) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt index 0a4ecc68..62b6c25d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt @@ -145,11 +145,55 @@ object AdminGovernance { return ShareRefreshManager.rotationPending(database, localChatRoom, key) } + /** What a change waits on while the room's shares are being rotated. */ + const val ROTATION_PENDING_REFUSAL = "The group's shares are still being rotated. Admins can change once the group has signed the new shares" + + /** + * Whether [change] moves who holds a share of the room's key: it changes the + * admins -- every admin holds a share (R1), so a promotion enrolls one and a + * demotion rotates one away -- or removes a member who holds one of + * [holders]. Inviting or removing anyone else leaves the roster alone, and + * does not wait on a rotation (docs/admin-change-rotation.md, A6). + */ + fun touchesShares(change: mobi.giza.compose.nostr.frost.GovernanceChange, holders: Set): Boolean = + change.admins != null || change.removes.any { it in holders } + + /** + * Why [change] must not be proposed in [localChatRoom] now, as far as the + * room's shares go, or null (docs/admin-change-rotation.md, Phase 3): a + * change that moves who holds a share waits while a rotation is pending + * ([adminChangeHold]), and one that takes a holder's share away is refused + * when the rotation it owes could not run (A12) -- before anybody signs it, + * since a change that lands with a rotation nobody can run leaves a + * non-admin holding a live share. + */ + suspend fun sharesRefusal( + database: GizaDatabase, + localChatRoom: mobi.giza.compose.database.model.intermdiate.LocalChatRoom, + change: mobi.giza.compose.nostr.frost.GovernanceChange, + currentAdmins: Set, + ): String? { + val key = keyOf(database, localChatRoom.chatRoom.id) ?: return null + val shares = ShareGenerations.active(database, key) + val holders = shares.roster.filter { it.standing == mobi.giza.compose.database.model.types.ShareStanding.LIVE }.map { it.memberPublicKey }.toSet() + if (!touchesShares(change, holders)) return null + if (adminChangeHold(database, localChatRoom) != null) return ROTATION_PENDING_REFUSAL + + val adminsAfter = (change.admins ?: currentAdmins) - change.removes + val missing = RoomAdmins.of(database, localChatRoom.chatRoom.id)?.missingFounders.orEmpty() + val retire = holders - adminsAfter - missing + // Only a change that itself takes a share away owes a rotation. + if (retire.none { it in change.removes || it in currentAdmins }) return null + return ShareRefreshManager.owedRotationRefusal(key, shares, retire)?.let { + "This would owe a rotation of the shares the group can't run: $it. Rotate the shares, or bring stale members back, first" + } + } + /** * The key [chatRoomId] signs with, as this device holds it -- whether or not it * can sign with it now: a member withheld from a rotation still follows it. */ - private suspend fun keyOf(database: GizaDatabase, chatRoomId: String): mobi.giza.compose.database.model.DkgSession? = + suspend fun keyOf(database: GizaDatabase, chatRoomId: String): mobi.giza.compose.database.model.DkgSession? = GroupKeyStateManager.keyStateFor(database, chatRoomId)?.dkgSessionId ?.let { database.dkgSessionDao().getSessionById(it) } ?.takeIf { it.stage == DkgRitualStage.COMPLETE } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt index f832f01f..1dc91853 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt @@ -18,6 +18,7 @@ import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.model.GovernanceProposal import mobi.giza.compose.database.model.GovernanceProposalStage +import mobi.giza.compose.database.model.types.ShareStanding /** * What a governed room's signed changes need after they land, taken by the device @@ -39,7 +40,9 @@ object GovernanceFollowThrough { database.governanceProposalDao().observeAll(), database.marmotInnerEventDao().observeCountByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, PromotionEvents.STEP_DOWN)), database.groupSignedEventDao().observeByKind(GroupKeyStateEvent.KIND), - ) { _, _, _ -> Unit } + // A rotation abandoned or failed releases what waited on it, with no key state filed. + database.shareRefreshDao().observeRunningCount(), + ) { _, _, _, _ -> Unit } .conflate() .collect { try { @@ -64,6 +67,9 @@ object GovernanceFollowThrough { PromotionManager.acceptedOffers(database, me).forEach { (offer, acceptance) -> if (offer.id in failedOffers) return@forEach val room = database.chatRoomDao().findChatRoomById(offer.chatRoomId) ?: return@forEach + // Waits while the shares are being rotated, rather than failing + // (docs/admin-change-rotation.md, A7): proposed on the pass after. + if (AdminGovernance.adminChangeHold(database, room) != null) return@forEach runCatching { PromotionManager.propose(database, room, me, offer, acceptance) }.onFailure { if (it is CancellationException) throw it failedOffers += offer.id @@ -129,7 +135,18 @@ object GovernanceFollowThrough { val room = database.chatRoomDao().findChatRoomById(proposal.chatRoomId) ?: return val me = keyPair.pubKey.toHexKey() val privateKey = keyPair.privKey ?: return - val failure = runCatching { ShareRefreshManager.proposeWithout(database, room, me, privateKey, member) }.exceptionOrNull() + val failure = runCatching { + val rotation = ShareRefreshManager.proposeWithout(database, room, me, privateKey, member) + // A rotation already running is handed back. If it was proposed before + // the change and deals to the member, it is not the one owed: it would + // leave them a live share of the next generation + // (docs/admin-change-rotation.md, H1). + val id = ShareGenerations.at(database, database.dkgSessionDao().getSessionById(rotation.dkgSessionId)!!, rotation.baseGeneration) + ?.signerIds?.get(member) + check(id == null || rotation.withheldStandings()[id] == ShareStanding.RETIRED) { + "a rotation that still deals to them was already running" + } + }.exceptionOrNull() if (failure is CancellationException) throw failure database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.DONE, updatedAt = Clock.System.now())) if (failure != null) { 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 0fa0f5d8..556edf4d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt @@ -125,6 +125,10 @@ object GovernanceManager { 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" } } + // Admin changes and rotations take turns, and a change that owes a rotation + // has to owe one the group can run. docs/admin-change-rotation.md, Phase 3. + AdminGovernance.sharesRefusal(database, localChatRoom, prepared.change, live.currentAdminIdentitiesSet()) + ?.let { throw IllegalStateException(it) } // The statement leads; anything signed with it -- a promotion's key state -- // is one decision by one quorum, so it is one batch. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberActionPolicy.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberActionPolicy.kt index fab025b6..2b20daf1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberActionPolicy.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberActionPolicy.kt @@ -46,6 +46,14 @@ data class MemberActionContext( val changePending: Boolean = false, /** Members this account has offered admin and who have not answered. */ val offeredAdmin: Set = emptySet(), + /** + * A rotation of the room's key still under way, which every change to who holds + * a share waits on, with whom it waits on; null when none is. + * docs/admin-change-rotation.md, Phase 3. + */ + val rotationPending: MemberActionBlocker.RotationPending? = null, + /** Who holds a live share of the room's key: their removal waits on a rotation too. */ + val shareHolders: Set = emptySet(), ) /** @@ -84,6 +92,7 @@ object MemberActionPolicy { // proposes, because a rotation's proposer has to keep a share. So the // room's rules, the floor, and another admin with a leaf to ask. context.governed && context.shareRefresh && + context.rotationPending == null && me in context.admins && keepsFloor(context, me) && context.admins.any { it != me && it in context.members } @@ -121,20 +130,22 @@ object MemberActionPolicy { else -> null } val pending = listOfNotNull(MemberActionBlocker.ChangePending.takeIf { context.changePending }) + // Every role change moves a share (R1); a removal does only for a holder (A6). + val rotating = listOfNotNull(context.rotationPending) val role = if (isAdmin) { - room + actor + keyed + listOfNotNull(floor) + pending + room + actor + keyed + listOfNotNull(floor) + pending + rotating } else { room + actor + keyed + listOfNotNull( MemberActionBlocker.NotInGroupYet.takeUnless { inGroup }, - ) + pending + listOfNotNull( + ) + pending + rotating + listOfNotNull( MemberActionBlocker.OfferPending.takeIf { member in context.offeredAdmin }, ) } val removal = room + actor + listOfNotNull( MemberActionBlocker.NotInGroupYet.takeUnless { inGroup }, floor, - ) + pending + ) + pending + rotating.takeIf { member in context.shareHolders }.orEmpty() return listOf(MemberActionOption(roleAction, role), MemberActionOption(MemberAction.REMOVE_FROM_GROUP, removal)) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt index 91b3a6c0..3dc136af 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt @@ -125,6 +125,8 @@ object PromotionManager { check(me in group.currentAdminIdentities()) { "Only an admin can make someone else one" } require(target in AdminGovernance.members(group)) { "They are not in the group any more" } if (target in group.currentAdminIdentities()) return "" + // An offer the group cannot act on until a rotation ends only asks them to wait. + check(AdminGovernance.adminChangeHold(database, localChatRoom) == null) { AdminGovernance.ROTATION_PENDING_REFUSAL } val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id) ?: throw IllegalStateException("This device holds no share of the group's key") check(ShareGenerations.active(database, key).generation >= 1) { @@ -194,6 +196,7 @@ object PromotionManager { ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}") check(me in group.currentAdminIdentities()) { "You're not an admin of this group" } check(AdminGovernance.stepDownProposer(group, me) != null) { "You're the only admin. Make someone else an admin first" } + check(AdminGovernance.adminChangeHold(database, localChatRoom) == null) { AdminGovernance.ROTATION_PENDING_REFUSAL } val id = send(database, localChatRoom.chatRoom.id, me, PromotionEvents.STEP_DOWN, "", PromotionEvents.stepDownTags(localChatRoom.chatRoom.id)) announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_ADMIN_OFFERED, "You asked to step down as admin. The group signs it next") return id @@ -224,6 +227,9 @@ object PromotionManager { return@forEach } if (room.chatRoom.userPublicKey != me || AdminGovernance.stepDownProposer(group, requester) != me) return@forEach + // Kept, not used up, while the room's shares are being rotated: taken up by + // the first pass after the group signs the new ones (docs/admin-change-rotation.md, A7). + if (AdminGovernance.adminChangeHold(database, room) != null) return@forEach val failure = runCatching { database.marmotOutboundDao().demote(room, requester) }.exceptionOrNull() if (failure is kotlinx.coroutines.CancellationException) throw failure diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt index a5c78bd6..f82e67c2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -143,6 +143,22 @@ object ShareRefreshManager { private data class Plan(val recipients: List, val withheld: Map, val refusal: String?) + /** + * Why the rotation a change would owe could not run, or null when it could + * (docs/admin-change-rotation.md, A12): every live holder of [shares] in + * [retire] withheld for good, every stale one withheld again, and the rest + * dealt to -- checked by the same [refusal] the rotation itself will meet. The + * admin floor counts admins; this counts recipients against every id not yet + * retired, so a share left live by an abandoned rotation makes the two differ. + */ + fun owedRotationRefusal(key: DkgSession, shares: ShareGenerations.Shares, retire: Set): String? { + val withheld = shares.roster + .filter { it.standing == ShareStanding.LIVE && it.memberPublicKey in retire } + .associate { it.participantId to ShareStanding.RETIRED } + val plan = plan(key, shares, userPublicKey = "", withheld) + return refusal(key, shares, plan.recipients, plan.withheld) + } + /** A refresh as it would be proposed, by member rather than by id. */ data class Preview( val takingPart: List, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreen.kt index fa192f97..8562b84c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreen.kt @@ -17,6 +17,7 @@ import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Schedule +import androidx.compose.material.icons.filled.Sync import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon @@ -68,6 +69,10 @@ import mobi.giza.compose.resources.step_down_as_admin import mobi.giza.compose.resources.this_no_longer_applies import mobi.giza.compose.resources.you_can_do_this_now import mobi.giza.compose.resources.you_can_do_this_now_body +import mobi.giza.compose.resources.member_action_rotation_pending_title +import mobi.giza.compose.resources.member_action_rotation_pending_body +import mobi.giza.compose.resources.member_action_rotation_pending_waiting_body +import mobi.giza.compose.resources.see_the_rotation import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute @@ -187,6 +192,14 @@ fun MemberActionUnavailableScreen( } } + // The rotation is on the group's screen, under Shares, with Abandon + // for one that has stalled (docs/admin-change-rotation.md, A10). + if (lead is MemberActionBlocker.RotationPending) { + Button(onClick = onNavigateBack) { + Text(stringResource(Res.string.see_the_rotation)) + } + } + val rest = state.blockers.drop(1) if (rest.isNotEmpty()) { Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { @@ -270,6 +283,7 @@ private fun MemberActionBlocker.icon(): ImageVector = when (this) { is MemberActionBlocker.BelowFloor -> Icons.Default.AdminPanelSettings MemberActionBlocker.ChangePending, MemberActionBlocker.OfferPending -> Icons.Default.Schedule + is MemberActionBlocker.RotationPending -> Icons.Default.Sync } @Composable @@ -286,6 +300,7 @@ private fun MemberActionBlocker.title(memberName: String): String = when (this) is MemberActionBlocker.BelowFloor -> stringResource(Res.string.member_action_below_floor_title, floor.toString()) MemberActionBlocker.ChangePending -> stringResource(Res.string.member_action_change_pending_title) MemberActionBlocker.OfferPending -> stringResource(Res.string.member_action_offer_pending_title, memberName) + is MemberActionBlocker.RotationPending -> stringResource(Res.string.member_action_rotation_pending_title) } @Composable @@ -302,6 +317,9 @@ private fun MemberActionBlocker.body(names: Map): String = when is MemberActionBlocker.BelowFloor -> stringResource(Res.string.member_action_below_floor_body) MemberActionBlocker.ChangePending -> stringResource(Res.string.member_action_change_pending_body) MemberActionBlocker.OfferPending -> stringResource(Res.string.member_action_offer_pending_body) + is MemberActionBlocker.RotationPending -> + if (waitingOn.isEmpty()) stringResource(Res.string.member_action_rotation_pending_body) + else stringResource(Res.string.member_action_rotation_pending_waiting_body, waitingOn.namedBy(names)) } /** The menu's word for [this], which is also this screen's title. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberActionUnavailableViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberActionUnavailableViewModel.kt index 5fe0d886..b5b11b48 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberActionUnavailableViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberActionUnavailableViewModel.kt @@ -77,6 +77,7 @@ class MemberActionUnavailableViewModel( val named = option.blockers.flatMap { blocker -> when (blocker) { is MemberActionBlocker.NotAnAdmin -> blocker.admins + is MemberActionBlocker.RotationPending -> blocker.waitingOn else -> emptySet() } }.toSet() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt index f49dfe71..489708d5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt @@ -74,6 +74,13 @@ sealed interface MemberActionBlocker { /** The member has already been offered admin, and has not answered. */ data object OfferPending : MemberActionBlocker + + /** + * The group's shares are being rotated, until the group signs the new ones; + * a change to who holds a share waits for that (docs/admin-change-rotation.md, + * Phase 3). [waitingOn]: whom the rotation is waiting on, when it is still dealing. + */ + data class RotationPending(val waitingOn: Set = emptySet()) : MemberActionBlocker } /** diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/MemberActionPolicyTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/MemberActionPolicyTest.kt index e846203d..e7040436 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/MemberActionPolicyTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/MemberActionPolicyTest.kt @@ -191,4 +191,27 @@ class MemberActionPolicyTest { context.blockers(bob, MemberAction.REMOVE_FROM_GROUP), ) } + + // docs/admin-change-rotation.md, Phase 3 + + @Test + fun `a rotation under way holds every change of role, and the removal of a share holder only`() { + val rotating = MemberActionBlocker.RotationPending(waitingOn = setOf(carol)) + val context = keyed( + admins = setOf(me, bob, carol, dana), + members = setOf(me, bob, carol, dana, gone), + ).copy(rotationPending = rotating, shareHolders = setOf(me, bob, carol, dana)) + + assertEquals(listOf(rotating), context.blockers(bob, MemberAction.REMOVE_AS_ADMIN)) + assertEquals(listOf(rotating), context.blockers(bob, MemberAction.REMOVE_FROM_GROUP)) + assertEquals(listOf(rotating), context.blockers(gone, MemberAction.MAKE_ADMIN)) + // Someone with no share leaves the roster alone: their removal does not wait. + assertTrue(context.blockers(gone, MemberAction.REMOVE_FROM_GROUP).isEmpty()) + // Your own row lists nothing it cannot do. + assertNull(MemberActionPolicy.options(context, listOf(me))[me]) + + val settled = context.copy(rotationPending = null) + assertTrue(settled.blockers(bob, MemberAction.REMOVE_AS_ADMIN).isEmpty()) + assertTrue(settled.option(me, MemberAction.STEP_DOWN)!!.isAvailable) + } } 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 3629c3f2..c7a17a62 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt @@ -619,20 +619,78 @@ class GovernanceGateJvmTest { } } - /** Pinned before Phase 3 (H5): a step-down request taken up while a rotation runs is used up, whatever it meets. */ + /** H5: a step-down request that arrives during a rotation waits for it, and is taken up after. */ @Test - fun `pinned -- a step-down request taken up during a rotation is used up`() = runBlocking { + fun `a step-down request waits through a rotation and is taken up once it ends`() = runBlocking { governedRoom() appIsAdmin() roomKeyHeldBy(listOf(dana.hex, userHex)) - rotationRunning() + val rotation = rotationRunning() mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true try { danaSays(PromotionEvents.STEP_DOWN, "", PromotionEvents.stepDownTags(roomId)) + assertEquals(0, PromotionManager.followStepDowns(db, userHex)) + assertEquals(1, db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(PromotionEvents.STEP_DOWN)).size, "the request was used up") + assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).isEmpty()) + + // The rotation ends; the next pass takes the request up. This room is at its + // floor, so the demotion is refused there, out loud, and the request is used. + db.shareRefreshDao().upsert(rotation.copy(stage = mobi.giza.compose.database.model.types.ShareRefreshStage.FAILED)) PromotionManager.followStepDowns(db, userHex) - assertTrue(db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(PromotionEvents.STEP_DOWN)).isEmpty(), "the request was kept") + assertTrue(db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(PromotionEvents.STEP_DOWN)).isEmpty()) + assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).any { "as they asked" in it.content }) } finally { mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = null } } + + /** H1, from the admin side: a demotion is not proposed while the shares are being rotated. */ + @Test + fun `a demotion proposed while the shares are being rotated is refused, and nothing is signed`() = runBlocking { + governedRoom() + appIsAdmin() + roomKeyHeldBy(listOf(dana.hex, userHex)) + rotationRunning() + + val refused = assertFailsWith { + GovernanceManager.propose(db, room(), userHex, thenRotateWithout = dana.hex, propose = ::demoteDana) + } + assertEquals(AdminGovernance.ROTATION_PENDING_REFUSAL, refused.message) + assertTrue(db.governanceProposalDao().getAll().isEmpty()) + assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(roomId).isEmpty(), "a signature was asked for") + } + + @Test + fun `nobody is offered admin, and nobody asks to step down, while the shares are being rotated`() = runBlocking { + governedRoom() + appIsAdmin() + erinAddedSigned() + roomKeyHeldBy(listOf(dana.hex, userHex)) + rotationRunning() + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true + try { + assertEquals(AdminGovernance.ROTATION_PENDING_REFUSAL, assertFailsWith { PromotionManager.offer(db, room(), userHex, erin.hex) }.message) + assertEquals(AdminGovernance.ROTATION_PENDING_REFUSAL, assertFailsWith { PromotionManager.requestStepDown(db, room(), userHex) }.message) + assertTrue(db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(PromotionEvents.OFFER, PromotionEvents.STEP_DOWN)).isEmpty()) + + // The member rows say why, with the share holders' removal held and nobody else's. + val options = chatRepository.memberActionOptions(room()) + val rotating = options.getValue(dana.hex).first { it.action == mobi.giza.compose.ui.view.state.MemberAction.REMOVE_AS_ADMIN }.blockers + assertTrue(rotating.any { it is mobi.giza.compose.ui.view.state.MemberActionBlocker.RotationPending }, rotating.toString()) + val erinRemoval = options.getValue(erin.hex).first { it.action == mobi.giza.compose.ui.view.state.MemberAction.REMOVE_FROM_GROUP }.blockers + assertTrue(erinRemoval.none { it is mobi.giza.compose.ui.view.state.MemberActionBlocker.RotationPending }, erinRemoval.toString()) + } finally { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = null + } + } + + /** A6: only a change that moves who holds a share waits on a rotation. */ + @Test + fun `inviting or removing a member with no share does not touch the shares`() { + val holders = setOf(dana.hex, userHex) + assertFalse(AdminGovernance.touchesShares(GovernanceChange(removes = setOf(erin.hex)), holders)) + assertFalse(AdminGovernance.touchesShares(GovernanceChange(adds = setOf(mobi.giza.compose.nostr.frost.AddedMember(erin.hex, "r"))), holders)) + assertTrue(AdminGovernance.touchesShares(GovernanceChange(removes = setOf(dana.hex)), holders)) + assertTrue(AdminGovernance.touchesShares(GovernanceChange(admins = setOf(userHex)), holders)) + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt index 1351d17b..df3a0364 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -1514,12 +1514,14 @@ class ShareRefreshRitualJvmTest { } /** - * H1: a removal that lands while a rotation runs. The rotation it owes is handed - * the running one back -- which was proposed before the removal, deals to the - * removed member, and leaves them a live share of the new generation. + * H1: a removal that lands while a rotation runs is handed the running one, which + * was proposed before the removal and deals to the removed member. The freeze + * keeps that removal from being proposed (Phase 3); if one lands anyway, the + * rotation it owes is not marked done as if the running one were it. */ @Test - fun `pinned -- a removal during a rotation leaves the removed member a live share`() = runBlocking { + fun `a removal's rotation is not taken for one already running that deals to them`() = runBlocking { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true val group = Group(4, 2) val all = devicesFor(group) val (alice, _, _, dave) = all @@ -1528,10 +1530,19 @@ class ShareRefreshRitualJvmTest { val owed = ShareRefreshManager.proposeWithout(alice.db, alice.room, alice.publicKey, alice.privateKey, dave.publicKey) assertEquals(running.id, owed.id, "the owed rotation was handed the running one") - approveAll(all, running.id) - assertEquals(1, alice.active().generation) - assertEquals(ShareStanding.LIVE, alice.active().roster.single { it.memberPublicKey == dave.publicKey }.standing) + val proposal = mobi.giza.compose.database.model.GovernanceProposal( + id = "d".repeat(64), chatRoomId = group.roomId, routingId = group.roomId, epoch = 1, frostSigningSessionId = "s", + commitEventId = "e".repeat(64), commitEventJson = "{}", priorStateHex = "", pendingStateHex = "", + stage = mobi.giza.compose.database.model.GovernanceProposalStage.APPLIED, thenRotateWithout = dave.publicKey, + ) + alice.db.governanceProposalDao().upsert(proposal) + GovernanceFollowThrough.pass(alice.db, alice.keyPair) + + assertEquals(mobi.giza.compose.database.model.GovernanceProposalStage.DONE, alice.db.governanceProposalDao().getById(proposal.id)!!.stage) + val said = alice.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).map { it.chatMessage } + .filter { it.messageType == ChatMessage.TYPE_CHANGE_NOT_APPLIED } + assertTrue(said.any { "still deals to them" in it.content }, said.map { it.content }.toString()) } /** @@ -1689,6 +1700,58 @@ class ShareRefreshRitualJvmTest { assertNull(AdminGovernance.adminChangeHold(alice.db, alice.room)) } + // ---- docs/admin-change-rotation.md, Phases 3 and 4 --------------------------------------------------------------- + + /** H3: the rotation waits out a new admin's enrollment, and then deals to them. */ + @Test + fun `a rotation after an enrollment deals to the new admin`() = runBlocking { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true + val (_, all) = rotatedOnce() + val alice = all[0] + val erinKeys = KeyPair() + val erin = stranger(alice.group, erinKeys) + bindNextId(all, erin.publicKey, ChillDkgRitualManager.deriveHostPublicKey(erinKeys.privKey!!).value.toHex()) + assertFailsWith { propose(alice) } + + PromotionManager.takeHandover(erin.db, erin.room, erin.publicKey, erin.privateKey, handoverFrom(alice, erin.publicKey)) + val everyone = all + erin + pump(everyone) + + val refresh = propose(alice) + assertTrue(3 in refresh.recipientIdList(), "the new admin was left out") + pump(everyone) + approveAll(everyone, refresh.id) + everyone.forEach { device -> assertEquals(2, device.active().generation, "device ${device.index}") } + assertNotNull(erin.active().secretShare, "the new admin holds no share of the new generation") + } + + /** + * A12: the admin floor counts admins, a rotation counts recipients against every + * id not yet retired. With one member stale and another's share left live by an + * abandoned rotation, retiring a third would leave no majority. + */ + @Test + fun `a removal is refused when the rotation it owes could not run`() = runBlocking { + val group = Group(6, 3) + val all = devicesFor(group) + val carol = all[2] + val first = propose(all[0], mapOf(group.idOf[carol.index] to ShareStanding.STALE)) + pump(all) + approveAll(all, first.id) + pump(all) + val alice = all[0] + val shares = alice.active() + assertEquals(1, shares.generation) + val (eve, dave) = all[4] to all[3] + + // Eve's share was left live when her rotation was abandoned; Dave is being removed. + val refused = ShareRefreshManager.owedRotationRefusal(alice.key(), shares, retire = setOf(eve.publicKey, dave.publicKey)) + assertNotNull(refused) + assertTrue("majority" in refused, refused) + // Dave alone would be fine. + assertNull(ShareRefreshManager.owedRotationRefusal(alice.key(), shares, retire = setOf(dave.publicKey))) + } + // ---- Phase 12: restore --------------------------------------------------------------------------------------- /**