diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index bb343c97..12f1e60d 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -178,6 +178,8 @@ A rotation is in progress Waiting for the group to sign the new shares before another rotation This device is catching up with the group's latest rotation + Waiting for a change to the group's admins to finish + Waiting for %1$s to receive their share Removal sent. They still hold a share; rotate without them once the group has signed the current shares. Ask the group to sign the new shares Asked the group to sign the new shares 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 db1e7a11..883b5ce9 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 @@ -877,6 +877,8 @@ class DatabaseChatRepository( canAskForSignature = hold.signingSessionId == null, ) is RotationHold.Behind -> SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.BEHIND) + is RotationHold.AdminChangeInFlight -> SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.ADMIN_CHANGE) + is RotationHold.Enrolling -> SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.ENROLLING, who = nameOf(hold.memberPublicKey)) } }, canAskToBeRepaired = ExperimentalFeatures.shareRefresh && mine?.standing == ShareStanding.STALE && !repairing, 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 8fa62e48..0a4ecc68 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt @@ -128,6 +128,33 @@ object AdminGovernance { } } + /** + * Why no change to who is an admin -- and no removal of a member who holds a + * share -- may be proposed in [localChatRoom] now, or null when one may: a + * rotation of the room's key is still under way, until the group has signed + * the key state it ends in (docs/admin-change-rotation.md, A5). A change now + * would be fixed against a roster the rotation is about to replace: a removed + * admin dealt a fresh share, a new admin's binding failing the rotation, a + * statement failed with the shares it was being signed with. + * + * The other direction, a rotation waiting on an admin change, is + * [ShareRefreshManager.rotationHold]'s. Null in a room without a key. + */ + suspend fun adminChangeHold(database: GizaDatabase, localChatRoom: mobi.giza.compose.database.model.intermdiate.LocalChatRoom): RotationHold? { + val key = keyOf(database, localChatRoom.chatRoom.id) ?: return null + return ShareRefreshManager.rotationPending(database, localChatRoom, key) + } + + /** + * 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? = + GroupKeyStateManager.keyStateFor(database, chatRoomId)?.dkgSessionId + ?.let { database.dkgSessionDao().getSessionById(it) } + ?.takeIf { it.stage == DkgRitualStage.COMPLETE } + ?: FrostSigningManager.completedKey(database, chatRoomId) + /** * What [MemberActionPolicy] reads, from [group]'s state: its admins, its * members, whether it is keyed and needs the group's signature, and [floor]. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RoomAdmins.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RoomAdmins.kt new file mode 100644 index 00000000..8479c584 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RoomAdmins.kt @@ -0,0 +1,43 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.GizaDatabase + +/** + * Who a keyed room's live admin policy names, as far as the share work reads it + * (docs/admin-change-rotation.md): the admins, whether the group's signature + * governs the room -- so that the policy changes only by a signed commit -- and + * any founding member [FoundingAdmins.check] finds the policy missing, whose + * absence the group never signed. + */ +data class RoomAdmins( + val admins: Set, + val governed: Boolean, + val missingFounders: Set = emptySet(), +) { + /** + * Whether [member] is someone the group's signature took out of the admins: + * the room is governed, the policy does not name them, and they are not a + * founder it has been missing from the start. + */ + fun removedBySignature(member: HexKey): Boolean = governed && member !in admins && member !in missingFounders + + companion object { + /** + * Stands in for the live group in tests whose rooms have no MLS state -- + * the share rituals between in-memory devices -- as + * `ExperimentalFeatures.shareRefreshOverride` stands in for the build. + */ + var override: (suspend (chatRoomId: String) -> RoomAdmins?)? = null + + /** [chatRoomId]'s admins off its live group, or null when this device holds no group for it. */ + suspend fun of(database: GizaDatabase, chatRoomId: String): RoomAdmins? { + override?.let { return it(chatRoomId) } + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return null + val group = runCatching { database.marmotEngine.groupFor(room.routingId) }.getOrNull() ?: return null + val missing = (FoundingAdmins.check(database, chatRoomId) as? FoundingAdmins.Check.Missing)?.publicKeys.orEmpty() + return RoomAdmins(group.currentAdminIdentities().toSet(), GovernanceGate.isGoverned(group), missing) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt index f7047f3a..13e7b60c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt @@ -1,5 +1,7 @@ package mobi.giza.compose.managers +import com.vitorpamplona.quartz.nip01Core.core.HexKey + /** * Why this device must not propose a share rotation now * (docs/rotation-waits-for-key-state.md). [ShareRefreshManager.rotationHold] @@ -26,4 +28,23 @@ sealed interface RotationHold { data class Behind(val groupGeneration: Int, val localGeneration: Int) : RotationHold { override val reason get() = "the group is at generation $groupGeneration and this device at $localGeneration" } + + /** + * A change to who is an admin, or a removal of a member who holds a share, is + * being signed or has not landed yet ([signingSessionId] is its signature's + * session). A rotation proposed now is fixed against a roster that change is + * about to move (docs/admin-change-rotation.md, Phase 2). + */ + data class AdminChangeInFlight(val signingSessionId: String) : RotationHold { + override val reason get() = "a change to the group's admins is on its way" + } + + /** + * A new admin's id is bound by the key state the group signed, and has no + * share yet. A rotation now would leave them stale, and fails outright if + * the binding lands while it deals (docs/admin-change-rotation.md, H2 and H3). + */ + data class Enrolling(val memberPublicKey: HexKey) : RotationHold { + override val reason get() = "a new admin is still receiving their share" + } } 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 835f5e2b..a5c78bd6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -30,13 +30,16 @@ import mobi.giza.compose.database.model.ShareRefreshConfirmation import mobi.giza.compose.database.model.ShareRefreshMessage import mobi.giza.compose.database.model.ShareRefreshSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.GovernanceProposalStage import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.ShareRepairStage import mobi.giza.compose.database.model.types.ShareGenerationState import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep import mobi.giza.compose.database.model.types.ShareRefreshStage import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.frost.GovernanceStatementEvent import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.frost.ShareRefreshEvents @@ -283,7 +286,19 @@ object ShareRefreshManager { * Checked on the proposer's device only. A recipient a few seconds behind on * the signature would refuse out loud and end a rotation that was fine. */ - suspend fun rotationHold(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold? { + suspend fun rotationHold(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold? = + rotationPending(database, localChatRoom, key) + ?: adminChangeInFlight(database, localChatRoom, key) + ?: enrolling(database, localChatRoom, key) + + /** + * Whether a rotation of [key] is still under way: running, or done but with its + * new generation's key state not yet signed -- the moment the old shares are + * wiped -- or this device behind the group. The part of [rotationHold] that + * admin changes wait on too (docs/admin-change-rotation.md, A5): neither + * direction may start while the other has not finished. + */ + suspend fun rotationPending(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold? { running(database, key)?.let { return RotationHold.Running(it.id) } val active = ShareGenerations.active(database, key).generation @@ -297,6 +312,71 @@ object ShareRefreshManager { return null } + /** + * A signed change to the room that moves who holds a share, not yet landed + * (docs/admin-change-rotation.md, Phase 2): a governance statement of + * [key] still being signed that changes the admins or removes a holder -- + * every signer holds that session -- or one of this device's own that is + * signed and on its way to a relay, which nobody else holds a session for + * any more. One that has landed and owes a rotation is not counted: that + * rotation is the change's next step, and must not wait on the change. + */ + private suspend fun adminChangeInFlight(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold? { + val holders = ShareGenerations.active(database, key).roster + .filter { it.standing == ShareStanding.LIVE } + .map { it.memberPublicKey } + .toSet() + val dao = database.frostSigningSessionDao() + suspend fun movesShares(sessionId: String): Boolean = dao.getItems(sessionId).any { item -> + val statement = Event.fromJsonOrNull(item.unsignedEventJson)?.let(GovernanceStatementEvent::parse) ?: return@any false + statement.change.admins != null || statement.change.removes.any { it in holders } + } + + dao.getOpenSessionsForKey(key.id) + .filter { it.chatRoomId == localChatRoom.chatRoom.id && it.signDeclinedAt == null } + .firstOrNull { movesShares(it.id) } + ?.let { return RotationHold.AdminChangeInFlight(it.id) } + + database.governanceProposalDao().getAll() + .filter { it.chatRoomId == localChatRoom.chatRoom.id } + .filter { it.stage == GovernanceProposalStage.SIGNING || it.stage == GovernanceProposalStage.PUBLISHED } + .filter { proposal -> + // Landed while this device was not watching: the group is past its epoch. + val epoch = runCatching { database.marmotEngine.groupFor(proposal.routingId) }.getOrNull()?.epoch + epoch == null || epoch <= proposal.epoch + } + .firstOrNull { movesShares(it.frostSigningSessionId) } + ?.let { return RotationHold.AdminChangeInFlight(it.frostSigningSessionId) } + return null + } + + /** + * A new admin whose id the group's key state binds at the active generation + * and who holds no share of it yet (docs/admin-change-rotation.md, A8). Not + * once their enrollment has failed -- a repair brings that id back at any + * generation -- and not for someone the live group does not name an admin, + * whose promotion never landed: nothing will enroll them, and they must not + * hold every rotation for good. + */ + private suspend fun enrolling(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold? { + val active = ShareGenerations.active(database, key) + val state = GroupKeyStateManager.keyStateFor(database, localChatRoom.chatRoom.id) + ?.takeIf { it.dkgSessionId == key.id && it.generation == active.generation } + ?: return null + val bindings = GroupKeyStateEvent.MemberBinding.decodeAll(state.memberBindings) + if (bindings.isEmpty()) return null + val admins = RoomAdmins.of(database, localChatRoom.chatRoom.id)?.admins + val repairs = database.shareRepairDao().getSessionsForKey(key.id) + return bindings.firstOrNull { binding -> + val entry = active.roster.firstOrNull { it.participantId == binding.participantId } ?: return@firstOrNull false + entry.standing == ShareStanding.STALE && + (admins == null || binding.memberPublicKey in admins) && + repairs.none { + it.targetId == binding.participantId && it.generation == active.generation && it.stage == ShareRepairStage.FAILED + } + }?.let { RotationHold.Enrolling(it.memberPublicKey) } + } + /** * Asks the group to sign the key state it owes for the generation the last * rotation produced, when nobody here is asking -- the coordinator's proposal 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 794b17d1..f4f2b98e 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 @@ -157,6 +157,8 @@ import mobi.giza.compose.resources.rotation_held_running import mobi.giza.compose.resources.rotate_shares_confirm_title import mobi.giza.compose.resources.rotation_held_awaiting_signatures import mobi.giza.compose.resources.rotation_held_behind +import mobi.giza.compose.resources.rotation_held_admin_change +import mobi.giza.compose.resources.rotation_held_enrolling import mobi.giza.compose.resources.rotation_held_after_removal import mobi.giza.compose.resources.ask_the_group_to_sign_the_new_shares import mobi.giza.compose.resources.key_state_requested @@ -801,13 +803,13 @@ fun ChatRoomDetailScreen( } if (rotation is SharesSummary.Rotation.Held) { Text( - text = stringResource( - when (rotation.reason) { - SharesSummary.Rotation.Reason.ROTATION_RUNNING -> Res.string.rotation_held_running - SharesSummary.Rotation.Reason.AWAITING_SIGNATURES -> Res.string.rotation_held_awaiting_signatures - SharesSummary.Rotation.Reason.BEHIND -> Res.string.rotation_held_behind - } - ), + text = when (rotation.reason) { + SharesSummary.Rotation.Reason.ROTATION_RUNNING -> stringResource(Res.string.rotation_held_running) + SharesSummary.Rotation.Reason.AWAITING_SIGNATURES -> stringResource(Res.string.rotation_held_awaiting_signatures) + SharesSummary.Rotation.Reason.BEHIND -> stringResource(Res.string.rotation_held_behind) + SharesSummary.Rotation.Reason.ADMIN_CHANGE -> stringResource(Res.string.rotation_held_admin_change) + SharesSummary.Rotation.Reason.ENROLLING -> stringResource(Res.string.rotation_held_enrolling, rotation.who.orEmpty()) + }, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt index 06c4c1e0..e5a13e3a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt @@ -38,11 +38,12 @@ data class SharesSummary( /** * The button, disabled, and why. [canAskForSignature]: the group owes the * key state at this generation and nobody here is asking for it, so this - * device can. + * device can. [who]: the new admin an [Reason.ENROLLING] hold waits on. */ - data class Held(val reason: Reason, val canAskForSignature: Boolean = false) : Rotation + data class Held(val reason: Reason, val canAskForSignature: Boolean = false, val who: String? = null) : Rotation - enum class Reason { ROTATION_RUNNING, AWAITING_SIGNATURES, BEHIND } + /** [ADMIN_CHANGE] and [ENROLLING]: docs/admin-change-rotation.md, Phase 2. */ + enum class Reason { ROTATION_RUNNING, AWAITING_SIGNATURES, BEHIND, ADMIN_CHANGE, ENROLLING } } /** 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 04ddbc0a..1351d17b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -1592,6 +1592,103 @@ class ShareRefreshRitualJvmTest { assertEquals(FrostSigningStage.FAILED, alice.db.frostSigningSessionDao().getSessionById(statement.id)?.stage) } + // ---- docs/admin-change-rotation.md, Phase 2: what waits on what ------------------------------------------------- + + /** A governance statement for [by]'s room that changes its admins to [admins], opened for the group's signature. */ + private suspend fun statementOpened(by: Device, admins: Set) = FrostSigningManager.proposeSigning( + by.db, by.room, by.publicKey, + kind = mobi.giza.compose.nostr.frost.GovernanceStatementEvent.KIND, + tags = mobi.giza.compose.nostr.frost.GovernanceStatementEvent.assembleTags( + by.group.roomId, epoch = 1, change = mobi.giza.compose.nostr.frost.GovernanceChange(admins = admins), proposer = by.publicKey, + ), + content = "{}", + ) + + @Test + fun `a rotation waits while a change to the admins is being signed, and an admin change does not wait on itself`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val alice = all[0] + val statement = statementOpened(alice, admins = setOf(alice.publicKey, all[1].publicKey)) + + val hold = ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key()) + assertEquals(RotationHold.AdminChangeInFlight(statement.id), hold) + assertFailsWith { propose(alice) } + assertNull(AdminGovernance.adminChangeHold(alice.db, alice.room), "an admin change waited on itself") + + // The statement fails -- declined, or its epoch passed: nothing is in flight. + alice.db.frostSigningSessionDao().upsert(alice.db.frostSigningSessionDao().getSessionById(statement.id)!!.copy(stage = FrostSigningStage.FAILED)) + assertNull(ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key())) + } + + @Test + fun `this device's own change holds a rotation until it lands, and not after`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val alice = all[0] + val statement = statementOpened(alice, admins = setOf(alice.publicKey)) + // Signed and sent: the session is over, the proposal is not. + alice.db.frostSigningSessionDao().upsert(alice.db.frostSigningSessionDao().getSessionById(statement.id)!!.copy(stage = FrostSigningStage.COMPLETE)) + val proposal = mobi.giza.compose.database.model.GovernanceProposal( + id = "d".repeat(64), chatRoomId = group.roomId, routingId = group.roomId, epoch = 1, frostSigningSessionId = statement.id, + commitEventId = "e".repeat(64), commitEventJson = "{}", priorStateHex = "", pendingStateHex = "", + stage = mobi.giza.compose.database.model.GovernanceProposalStage.PUBLISHED, thenRotateWithout = all[2].publicKey, + ) + alice.db.governanceProposalDao().upsert(proposal) + assertEquals(RotationHold.AdminChangeInFlight(statement.id), ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key())) + + // Landed, owing its rotation: that rotation is the change's next step. + alice.db.governanceProposalDao().upsert(proposal.copy(stage = mobi.giza.compose.database.model.GovernanceProposalStage.APPLIED)) + assertNull(ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key())) + ShareRefreshManager.proposeWithout(alice.db, alice.room, alice.publicKey, alice.privateKey, all[2].publicKey) + } + + @Test + fun `a rotation waits for a new admin's enrollment, and not past its failure`() = 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()) + + all.forEach { device -> + assertEquals(RotationHold.Enrolling(erin.publicKey), ShareRefreshManager.rotationHold(device.db, device.room, device.key()), "device ${device.index}") + } + assertNull(AdminGovernance.adminChangeHold(alice.db, alice.room), "an admin change waited on an enrollment") + + // A failed enrollment releases it. + val bob = all[1] + bob.db.shareRepairDao().upsert( + mobi.giza.compose.database.model.ShareRepairSession( + id = "f".repeat(64), chatRoomId = bob.group.roomId, dkgSessionId = ceremonyId, generation = 1, targetId = 3, + targetPublicKey = erin.publicKey, targetHostPublicKey = "02" + "c".repeat(64), helperIds = "0,1", + userPublicKey = bob.publicKey, stage = mobi.giza.compose.database.model.types.ShareRepairStage.FAILED, + sessionRandom = "5".repeat(64), + ) + ) + assertNull(ShareRefreshManager.rotationHold(bob.db, bob.room, bob.key())) + + // A completed one too. + PromotionManager.takeHandover(erin.db, erin.room, erin.publicKey, erin.privateKey, handoverFrom(alice, erin.publicKey)) + pump(all + erin) + assertNull(ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key())) + } + + @Test + fun `an admin change waits on a rotation until its key state is signed`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val alice = all[0] + val refresh = propose(alice) + assertEquals(RotationHold.Running(refresh.id), AdminGovernance.adminChangeHold(alice.db, alice.room)) + pump(all) + approveAll(all, refresh.id) + // The key state signs itself as the rotation completes; then nothing is pending. + pump(all) + assertNull(AdminGovernance.adminChangeHold(alice.db, alice.room)) + } + // ---- Phase 12: restore --------------------------------------------------------------------------------------- /**