feat: an admin makes a member an admin, or not, in a convenient room (member-admin-promotion, Phase 6)

MarmotOutboundDao.promote and demote commit the room's admin list through
the publish gate, built from the list the group holds when the commit is
staged. AdminGovernance holds the rules once: the library's permissions,
plus that a promoted account holds a leaf, and that a keyed room's admins
are changed by none of this -- they need the group's signature and a
share of its key, which are not built.

Removing an admin now takes them off the admin list first and removes
them when that commit is confirmed, chained by MarmotEngine.afterConfirmed.
A bare Remove left their key on the list, so inviting them back made them
an admin again with nobody having said so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-20 01:19:34 +02:00
1 parent 19f0fc0f1e
commit d95412ffda
6 files changed
+432 -1

No files matched your search

@@ -4,6 +4,7 @@ import androidx.room3.Dao
import androidx.room3.Transaction
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.foundation.appEvents.MarmotAppEvent
import com.vitorpamplona.marmot.groups.MlsGroupManager
@@ -57,6 +58,7 @@ import mobi.giza.compose.exceptions.MarmotMissingChatGroupException
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.ChronicleManager
import mobi.giza.compose.managers.MarmotGroupFactory
import mobi.giza.compose.managers.MarmotInboundManager
@@ -852,20 +854,106 @@ abstract class MarmotOutboundDao(
* every other from the commit -- so every device says the same thing at the
* same point. The library's admin-depletion guard refuses a commit that would
* leave no admin in the tree.
*
* An admin is taken off the admin list first, by a commit of its own, and
* removed once that one is confirmed. A bare `Remove` left their key on the
* list, so inviting them back made them an admin again with nobody having
* said so -- and `AdminPolicyV1` says a commit removing an account's last leaf
* must drop its key. Two commits until the library can stage both proposals
* in one (docs/member-admin-promotion.md, Phase 0, step 5); if the second is
* lost to a restart, the member is left demoted, and removing them again is
* one commit.
*/
@Transaction
open suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room can remove a member" }
val group = database.marmotEngine.groupFor(localChatRoom.routingId)
val engine = database.marmotEngine
val group = engine.groupFor(localChatRoom.routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
val leafIndex = group.members()
.firstOrNull { (_, leaf) -> (leaf.credential as? Credential.Basic)?.identity?.toHexKey() == memberPublicKey }
?.first
?: throw IllegalArgumentException("$memberPublicKey is not in the group")
if (memberPublicKey in group.currentAdminIdentities()) {
publishAdmins(localChatRoom) { admins -> admins - memberPublicKey }
engine.afterConfirmed(localChatRoom.routingId) {
database.chatRoomDao().findChatRoomById(localChatRoom.chatRoom.id)
?.let { removeMember(it, memberPublicKey) }
}
return
}
publishGatedCommit(localChatRoom) { manager, id -> manager.stageRemoveMember(id, leafIndex) }
}
/**
* Makes [memberPublicKey] an admin of a room this device administers, by one
* commit through the publish gate. Nothing happens for someone who already is.
*
* Refused in a keyed room, whose admins change only with the group's signature
* and a share of its key (docs/member-admin-promotion.md, R1 and R2), and for
* someone who is not in the tree: an admin with no leaf is not valid state.
* The line saying so is written when the commit is applied, on every device.
* docs/member-admin-promotion.md, Phase 6.
*/
@Transaction
open suspend fun promote(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
val group = governedGroup(localChatRoom)
if (memberPublicKey in group.currentAdminIdentities()) return
check(!AdminGovernance.isKeyedRoom(group)) { KEYED_ROOM_REFUSAL }
if (memberPublicKey !in AdminGovernance.members(group)) {
throw IllegalArgumentException("${memberName(memberPublicKey)} is not in the group any more")
}
publishAdmins(localChatRoom) { admins -> admins + memberPublicKey }
}
/**
* Makes [adminPublicKey] stop being an admin of a room this device administers,
* by one commit through the publish gate. Nothing happens for someone who is not
* one. [adminPublicKey] may be this device's own account, which is stepping down.
*
* Refused in a keyed room, as [promote] is, and where it would leave no admin
* among the members -- the commit every peer refuses as admin depletion, said
* here in words that name the fix. docs/member-admin-promotion.md, Phase 6.
*/
@Transaction
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 }
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"
else "${memberName(adminPublicKey)} is the only admin. Make someone else an admin first"
)
}
publishAdmins(localChatRoom) { admins -> admins - adminPublicKey }
}
/** 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" }
val group = database.marmotEngine.groupFor(localChatRoom.routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
check(group.isLocalAdmin()) { "Only an admin can change who the admins are" }
return group
}
/**
* Commits the room's admin list as [change] makes it from the list the group
* holds at the moment the commit is staged -- after any convergence pass has
* settled -- rather than from one read before the wait.
*/
private suspend fun publishAdmins(localChatRoom: LocalChatRoom, change: (Set<HexKey>) -> Set<HexKey>) {
publishGatedCommit(localChatRoom) { manager, id ->
val live = manager.getGroup(id) ?: throw MarmotMissingChatGroupException("No live group for $id")
manager.stageAppDataUpdate(id, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(change(live.currentAdminIdentities())).encode())
}
}
/**
* Disbands a current-profile room, as an admin.
*
@@ -1339,5 +1427,9 @@ abstract class MarmotOutboundDao(
companion object {
const val TAG = "MarmotOutboundDao"
/** Why a keyed room's admins cannot be changed by one admin's commit yet. */
const val KEYED_ROOM_REFUSAL =
"This group's admins hold shares of its key, so changing them needs the group's signature. That isn't built yet"
}
}
@@ -651,6 +651,14 @@ class DatabaseChatRepository(
return MarmotInboundManager.reconcileAdmins(database, chatRoomId, group)
}
override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
database.marmotOutboundDao().promote(localChatRoom, memberPublicKey)
}
override suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) {
database.marmotOutboundDao().demote(localChatRoom, adminPublicKey)
}
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey)
}
@@ -0,0 +1,56 @@
package mobi.giza.compose.managers
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
/**
* Who may change who governs a room, in one place, so the screen that offers an
* action and the code that commits it cannot disagree. See
* docs/member-admin-promotion.md.
*
* Every answer is read off the group's state -- its admin set and its tree --
* never off `Participant.adminAt`, which is a cache of it (D1). The permission
* itself is the library's, [MarmotGroupPermissions], which is what every peer
* enforces on a commit; this adds the two things it leaves to the application.
*/
object AdminGovernance {
/**
* A room around a group's threshold key: the admin room a robust group opens,
* or a subgroup's. Its description records the path the key was walked to
* ([SharedKeyDerivation.parsePath]), which a convenient room or a direct
* message never has.
*
* Such a room's admins change only with the group's signature on the change,
* and only alongside a share of the key (R1, R2), neither of which is built.
* Until it is, a keyed room's admin list is changed by nothing here.
*/
fun isKeyedRoom(group: MlsGroup): Boolean = SharedKeyDerivation.parsePath(group.roomDescription()) != null
/** The accounts holding a leaf in [group] now. */
fun members(group: MlsGroup): Set<HexKey> = group.currentMemberIdentities()
/**
* Whether [actor] may make [target] an admin of [group] by a single commit.
*
* The library's rule, plus that [target] holds a leaf: `canPromote` does not
* ask, and an admin entry for an account with no leaf is the state
* `AdminPolicyV1` says is never valid.
*/
fun canPromote(group: MlsGroup, actor: HexKey, target: HexKey): Boolean =
!isKeyedRoom(group) &&
target in members(group) &&
MarmotGroupPermissions.canPromote(group.currentAdminIdentities(), actor, target)
/**
* Whether [actor] may make [target] stop being an admin of [group] by a single
* commit. The library's rule, which already refuses a demotion that would
* leave no admin among the members; [actor] and [target] may be the same
* account, which is stepping down.
*/
fun canDemote(group: MlsGroup, actor: HexKey, target: HexKey): Boolean =
!isKeyedRoom(group) &&
MarmotGroupPermissions.canDemote(group.currentAdminIdentities(), members(group), actor, target)
}
@@ -90,6 +90,29 @@ class MarmotEngine(
val gate = MarmotPublishGate(groupManager, RoomPublishObligationStore(database))
private val restoreMutex = Mutex()
/**
* The next step of a two-commit change, by the group whose commit it waits on:
* removing an admin is a demotion and then the removal, and leaving as an admin
* is a step-down and then the leave. Run when that group's commit is confirmed,
* dropped when every relay refuses it.
*
* Keyed by group because the gate allows one commit in flight per group, so the
* next confirmation for it is the one this waits on. In memory on purpose: a
* restart between the two leaves a demoted member who has not been removed, or
* an ex-admin who has not left, and either can be finished with one tap.
* docs/member-admin-promotion.md, Phases 6 and 10.
*/
private val followUps = mutableMapOf<HexKey, suspend () -> Unit>()
private val followUpsMutex = Mutex()
/** Runs [step] once [routingId]'s commit now in flight is confirmed. */
suspend fun afterConfirmed(routingId: HexKey, step: suspend () -> Unit) {
followUpsMutex.withLock { followUps[routingId] = step }
}
private suspend fun takeFollowUp(routingId: HexKey): (suspend () -> Unit)? =
followUpsMutex.withLock { followUps.remove(routingId) }
private var restored = false
/**
@@ -229,6 +252,9 @@ class MarmotEngine(
priorAdmins = MarmotGroupPolicy.adminIdentitiesIn(obligation.priorState.groupContext.extensions),
)
database.marmotOutboundDao().continueDisband(localChatRoom)
takeFollowUp(obligation.groupId)?.let { step ->
runCatching { step() }.onFailure { logger.w("The step after ${obligation.groupId.take(8)}…'s commit failed: ${it.message}") }
}
}
/**
@@ -244,6 +270,7 @@ class MarmotEngine(
ensureRestored()
val obligation = gate.allPending().firstOrNull { it.obligationId == obligationId } ?: return false
gate.resolve(obligationId, PublishOutcome.FAILED)
takeFollowUp(obligation.groupId)
logger.w("Commit ${obligationId.take(8)}… discarded; ${obligation.groupId.take(8)}… stays at epoch ${obligation.priorState.groupContext.epoch}")
return true
}
@@ -274,6 +274,21 @@ interface ChatRepository {
*/
suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey)
/**
* Makes [memberPublicKey] an admin of a convenient room this device
* administers: one commit through the publish gate, captioned when it is
* applied. Throws with words a person can act on when it cannot be done. See
* docs/member-admin-promotion.md, Phase 6.
*/
suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey)
/**
* Makes [adminPublicKey] stop being an admin of a convenient room this device
* administers -- this device's own account included, which is stepping down.
* Throws with words a person can act on when it cannot be done.
*/
suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey)
/**
* Whether [memberPublicKey] holds a live share of the room's key, and so
* whether a removal leaves them able to help sign until the shares are
@@ -492,6 +507,10 @@ interface ChatRepository {
override suspend fun reconcileAdmins(chatRoomId: String): Boolean = false
override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit
override suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) = Unit
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit
override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = false