feat: a keyed room demotes an admin with the group's signature, then rotates them out (member-admin-promotion, Phase 9)

In a governed keyed room, with share rotation on, an admin can propose
removing another as admin -- never themselves, since the rotation that
has to follow is the remaining holders'. The demotion is a signed change
like any other, and the floor holds. A removal of a member who holds a
live share is the same.

Either one remembers who to rotate out (GovernanceProposal.thenRotateWithout,
schema v42), is marked applied when a relay accepts it, and
GovernanceFollowThrough -- a driver beside the ceremony follow-through,
with the key pair -- then proposes the rotation without them. A change
that landed while the app was closed is caught from the group's state; a
rotation that cannot start is said in the room, and offered from the
Shares section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-20 02:40:21 +02:00
1 parent 546b2a2b74
commit 51eda2d211
12 files changed
+5624 -16

No files matched your search

@@ -173,7 +173,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 41,
version = 42,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -434,6 +434,10 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// change this device proposed to a governed room, held while the group signs
// it. One new table, so Room generates it.
AutoMigration(from = 40, to = 41),
// v42 adds GovernanceProposal.thenRotateWithout and ShareRepairSession.nParticipants
// (docs/member-admin-promotion.md, Phases 8 and 9): two nullable columns, so
// Room generates it.
AutoMigration(from = 41, to = 42),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -19,4 +19,10 @@ interface GovernanceProposalDao {
@Upsert
suspend fun upsert(proposal: GovernanceProposal)
@Query("SELECT * FROM GovernanceProposal ORDER BY createdAt ASC")
fun observeAll(): kotlinx.coroutines.flow.Flow<List<GovernanceProposal>>
@Query("SELECT * FROM GovernanceProposal ORDER BY createdAt ASC")
suspend fun getAll(): List<GovernanceProposal>
}
@@ -63,6 +63,8 @@ import mobi.giza.compose.extensions.shortened
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.managers.AdminFlags
import mobi.giza.compose.managers.AdminGovernance
import mobi.giza.compose.managers.ShareRefreshManager
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.managers.GovernanceGate
import mobi.giza.compose.managers.GovernanceManager
import mobi.giza.compose.managers.GovernanceMarker
@@ -915,7 +917,11 @@ abstract class MarmotOutboundDao(
// 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))
GovernanceManager.propose(
database, localChatRoom, localChatRoom.chatRoom.userPublicKey,
thenRotateWithout = memberPublicKey.takeIf { holdsLiveShare(localChatRoom, it) },
propose = GovernanceManager.removal(leafIndex, memberPublicKey, admins),
)
return
}
@@ -965,7 +971,27 @@ abstract class MarmotOutboundDao(
open suspend fun demote(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) {
val group = governedGroup(localChatRoom)
if (adminPublicKey !in group.currentAdminIdentities()) return
check(!AdminGovernance.isKeyedRoom(group)) { KEYED_ROOM_REFUSAL }
// A keyed room: proposed for the group's signature, and their share rotated
// away once it lands (docs/member-admin-promotion.md, Phase 9).
if (AdminGovernance.isKeyedRoom(group)) {
check(AdminGovernance.keyedChangesAllowed(group)) { KEYED_ROOM_REFUSAL }
check(adminPublicKey != localChatRoom.chatRoom.userPublicKey) {
"In a group with a shared key, another admin removes you as admin, so the group can rotate your share away"
}
val floor = AdminGovernance.adminFloor(database, localChatRoom.chatRoom.id, group)
if (!AdminGovernance.keepsFloor(group, adminPublicKey, floor)) {
throw IllegalStateException("A group with a shared key needs at least $floor admins. Make someone else an admin first")
}
val admins = group.currentAdminIdentities()
GovernanceManager.propose(
database, localChatRoom, localChatRoom.chatRoom.userPublicKey,
thenRotateWithout = adminPublicKey.takeIf { holdsLiveShare(localChatRoom, it) },
) { copy ->
copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins - adminPublicKey).encode())
}
return
}
if (!AdminGovernance.canDemote(group, localChatRoom.chatRoom.userPublicKey, adminPublicKey)) {
throw IllegalStateException(
if (adminPublicKey == localChatRoom.chatRoom.userPublicKey) "You're the only admin. Make someone else an admin first"
@@ -1062,6 +1088,11 @@ abstract class MarmotOutboundDao(
}
}
/** Whether [memberPublicKey] holds a live share of the room's key, with rotation on. */
private suspend fun holdsLiveShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean =
ExperimentalFeatures.shareRefresh &&
runCatching { ShareRefreshManager.liveIdOf(database, localChatRoom, memberPublicKey) != null }.getOrDefault(false)
/** 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" }
@@ -50,6 +50,12 @@ data class GovernanceProposal(
val priorStateHex: String,
val pendingStateHex: String,
val stage: GovernanceProposalStage = GovernanceProposalStage.SIGNING,
/**
* A member whose live share has to be rotated away once this change lands: one
* it demotes or removes (docs/member-admin-promotion.md, Phase 9). Persisted,
* because the change can land long after it was proposed, across a restart.
*/
val thenRotateWithout: HexKey? = null,
override val createdAt: Instant = Clock.System.now(),
override val updatedAt: Instant = createdAt,
override val savedAt: Instant = createdAt,
@@ -64,4 +70,10 @@ enum class GovernanceProposalStage {
/** The group moved past its epoch before it was signed or sent; nothing can land it now. */
STALE,
/** A relay accepted it, so the change is the group's. */
APPLIED,
/** Applied, and what had to follow it -- a rotation without a demoted member -- has been started. */
DONE,
}
@@ -45,6 +45,13 @@ data class ShareRepairSession(
val helpApprovedAt: Instant? = null,
val approvalRequested: Boolean = false,
val failureReason: String? = null,
/**
* The `n` the reduced enrollment runs with, when it is not the key's: for an
* enrollment at a new id it is that id -- the table had n entries before the
* new member's public share was added (docs/member-admin-promotion.md, Phase 8).
* Null for a repair, which uses the current table's size.
*/
val nParticipants: Int? = null,
override val createdAt: Instant = Clock.System.now(),
override val updatedAt: Instant = createdAt,
override val savedAt: Instant = createdAt,
@@ -12,6 +12,7 @@ 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.GovernanceFollowThrough
import mobi.giza.compose.managers.GovernanceSupport
import mobi.giza.compose.managers.MarmotInboundManager
import mobi.giza.compose.managers.AdminFlags
@@ -32,6 +33,7 @@ import com.vitorpamplona.quartz.utils.TimeUtils
import kotlin.time.Clock
import kotlin.time.Instant
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -142,8 +144,14 @@ class DatabaseChatRepository(
override suspend fun reconcileAdminFlags(): Int = AdminFlags.reconcileAll(database)
override suspend fun followThroughCeremonies(keyPair: KeyPair) =
CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair)
override suspend fun followThroughCeremonies(keyPair: KeyPair) = kotlinx.coroutines.coroutineScope {
launch { CeremonyFollowThrough.observe(database = database, chatRepository = this@DatabaseChatRepository, keyPair = keyPair) }
// What a governed room's signed changes need after they land: a rotation
// without a demoted member, a promotion's next steps.
// docs/member-admin-promotion.md, Phases 8 and 9.
launch { GovernanceFollowThrough.observe(database = database, keyPair = keyPair) }
Unit
}
override suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow<List<LocalChatRoom>> {
return database.chatRoomDao().observeChatRoomListByUserPublicKey(publicKey)
@@ -4,6 +4,7 @@ import com.vitorpamplona.marmot.groups.MarmotGroupPermissions
import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.mls.group.MlsGroup
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.types.ChatRoomType
import mobi.giza.compose.database.model.types.DkgRitualStage
@@ -82,9 +83,20 @@ object AdminGovernance {
* account, which is stepping down.
*/
fun canDemote(group: MlsGroup, actor: HexKey, target: HexKey): Boolean =
!isKeyedRoom(group) &&
(!isKeyedRoom(group) || (keyedChangesAllowed(group) && actor != target)) &&
MarmotGroupPermissions.canDemote(group.currentAdminIdentities(), members(group), actor, target)
/**
* Whether a keyed room's admins can be changed at all from this build: the room
* has to need the group's signature for its changes (R2), and share rotation and
* enrollment have to be on, since every admin change moves a share (R1). Even
* then an admin does not step down on their own in a keyed room: the rotation
* that has to follow is the remaining holders', so another admin proposes it.
* docs/member-admin-promotion.md, Phases 8 and 9.
*/
fun keyedChangesAllowed(group: MlsGroup): Boolean =
isKeyedRoom(group) && GovernanceGate.isGoverned(group) && ExperimentalFeatures.shareRefresh
/**
* What [me] may do to each member of [group], for the member rows' menus. Empty
* when [me] does not govern the room. Removal stays offered in a keyed room,
@@ -99,7 +111,7 @@ object AdminGovernance {
if (canDemote(group, me, me)) add(MemberAction.STEP_DOWN)
} else {
if (canPromote(group, me, member)) add(MemberAction.MAKE_ADMIN)
if (canDemote(group, me, member)) add(MemberAction.REMOVE_AS_ADMIN)
if (canDemote(group, me, member) && keepsFloor(group, member, floor)) add(MemberAction.REMOVE_AS_ADMIN)
if (MarmotGroupPermissions.canRemove(group.currentAdminIdentities(), me, member) && keepsFloor(group, member, floor)) {
add(MemberAction.REMOVE_FROM_GROUP)
}
@@ -0,0 +1,107 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import kotlin.time.Clock
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
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
/**
* What a governed room's signed changes need after they land, taken by the device
* that proposed them, which holds the key pair those steps need.
* docs/member-admin-promotion.md, Phases 8 and 9.
*
* Runs beside `CeremonyFollowThrough`, for the same reason: it needs the active key
* pair and stops with it. Each pass reads everything again from the database, so a
* step interrupted halfway, or a change that landed while the app was closed, is
* taken on the next one.
*/
object GovernanceFollowThrough {
private val logger = Logger.withTag("GovernanceFollowThrough")
private val mutex = Mutex()
/** Follows this device's proposals until cancelled. */
suspend fun observe(database: GizaDatabase, keyPair: KeyPair) {
database.governanceProposalDao().observeAll()
.conflate()
.collect {
try {
pass(database, keyPair)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
logger.e("A governance follow-through pass failed", e)
}
}
}
/** One pass over everything owed. */
suspend fun pass(database: GizaDatabase, keyPair: KeyPair) = mutex.withLock {
rotationsOwed(database).forEach { proposal -> rotateAway(database, keyPair, proposal) }
}
/**
* This device's changes that have landed and owe a rotation without a member
* they demoted or removed (Phase 9). Landed means a relay accepted it -- marked
* [GovernanceProposalStage.APPLIED] -- or, for one confirmed while this device
* was not watching, that the group is past its epoch and no longer names the
* member an admin, or no longer holds them at all.
*/
suspend fun rotationsOwed(database: GizaDatabase): List<GovernanceProposal> =
database.governanceProposalDao().getAll().filter { proposal ->
val member = proposal.thenRotateWithout ?: return@filter false
when (proposal.stage) {
GovernanceProposalStage.APPLIED -> true
GovernanceProposalStage.PUBLISHED -> {
val group = database.marmotEngine.groupFor(proposal.routingId) ?: return@filter false
group.epoch > proposal.epoch &&
(member !in group.currentAdminIdentities() || member !in group.currentMemberIdentities())
}
else -> false
}
}
/**
* Starts the rotation without [proposal]'s member, and marks it done either way:
* a rotation that could not start -- one already running, a holder this device
* cannot reach -- is said in the room, and the Shares section offers it from
* there, as it does after any removal.
*/
private suspend fun rotateAway(database: GizaDatabase, keyPair: KeyPair, proposal: GovernanceProposal) {
val member = proposal.thenRotateWithout ?: return
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()
if (failure is CancellationException) throw failure
database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.DONE, updatedAt = Clock.System.now()))
if (failure != null) {
logger.w("Could not rotate ${member.take(8)}… away after ${proposal.id.take(8)}…: ${failure.message}")
announce(database, proposal.chatRoomId, me, "Couldn't start rotating the shares without a member who is no longer an admin: ${failure.message}. Rotate them from the Shares section")
}
}
private suspend fun announce(database: GizaDatabase, chatRoomId: String, me: HexKey, content: String) {
database.chatMessageDao().upsert(
ChatMessage(
content = content,
messageType = ChatMessage.TYPE_CHANGE_NOT_APPLIED,
chatRoomId = chatRoomId,
senderPublicKey = me,
isUserMessage = true,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
)
)
}
}
@@ -101,6 +101,7 @@ object GovernanceManager {
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
peerKeyPackageEventId: HexKey? = null,
thenRotateWithout: HexKey? = null,
propose: (MlsGroup) -> Unit,
): String {
val engine = database.marmotEngine
@@ -131,7 +132,7 @@ object GovernanceManager {
content = prepared.commitEvent.toJson(),
)
val statementId = database.frostSigningSessionDao().getItems(session.id).single().eventId
record(database, localChatRoom, userPublicKey, prepared, statementId, session.id, peerKeyPackageEventId)
record(database, localChatRoom, userPublicKey, prepared, statementId, session.id, peerKeyPackageEventId, thenRotateWithout)
return session.id
}
@@ -149,6 +150,7 @@ object GovernanceManager {
statementId: HexKey,
sessionId: String,
peerKeyPackageEventId: HexKey? = null,
thenRotateWithout: HexKey? = null,
): GovernanceProposal {
val roomId = localChatRoom.chatRoom.id
database.marmotCommitResultDao().upsert(
@@ -173,6 +175,7 @@ object GovernanceManager {
peerKeyPackageEventId = peerKeyPackageEventId,
priorStateHex = prepared.staged.priorState.encodeTls().toHex(),
pendingStateHex = prepared.staged.pendingState.encodeTls().toHex(),
thenRotateWithout = thenRotateWithout,
)
database.governanceProposalDao().upsert(proposal)
return proposal
@@ -248,7 +251,19 @@ object GovernanceManager {
val commitEvent = Event.fromJson(proposal.commitEventJson).let {
GroupEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig)
}
sendEnvelope(
// When a relay accepts it, the change is the group's: what has to follow it
// -- a rotation without a member it demoted -- reads that off the row
// (GovernanceFollowThrough). Registered before the gate is raised, so the
// acceptance cannot overtake it; a restart in between is caught there too.
engine.afterConfirmed(routingId) {
database.governanceProposalDao().getById(proposal.id)?.let { current ->
if (current.stage == GovernanceProposalStage.PUBLISHED) {
database.governanceProposalDao().upsert(current.copy(stage = GovernanceProposalStage.APPLIED, updatedAt = Clock.System.now()))
}
}
}
try {
sendEnvelope(
database = database,
chatRoomId = proposal.chatRoomId,
routingId = routingId,
@@ -258,9 +273,13 @@ object GovernanceManager {
commitRow = commitRow,
carrierKind = GovernanceCarrierEvent.KIND,
carrierContent = signed.toJson(),
carrierTags = GovernanceCarrierEvent.assembleTags(proposal.chatRoomId),
relays = relays,
)
carrierTags = GovernanceCarrierEvent.assembleTags(proposal.chatRoomId),
relays = relays,
)
} catch (e: Throwable) {
engine.cancelFollowUp(routingId)
throw e
}
database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.PUBLISHED, updatedAt = Clock.System.now()))
}