diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt index a8bb6e9e..da43e26a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt @@ -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) -> Set) { + 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" } } \ No newline at end of file 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 9cbbda5c..86345ef1 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 @@ -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) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt new file mode 100644 index 00000000..478133b6 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt @@ -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 = 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) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt index 59c2c591..ace3766c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt @@ -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 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 } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index 83627d7a..d11b84c2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -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 diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt new file mode 100644 index 00000000..ae809dbc --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt @@ -0,0 +1,229 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.marmot.GroupEventResult +import com.vitorpamplona.marmot.appComponents.AdminPolicyV1 +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.marmot.groups.isLocalAdmin +import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent +import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import kotlin.io.encoding.Base64 +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.time.Instant +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.MarmotKeyPackage +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.repository.DatabaseNostrRepository +import mobi.giza.compose.exceptions.MarmotCommitPendingException +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.MarmotProfile +import mobi.giza.compose.nostr.Relays + +/** + * Promoting and demoting in a convenient room, which has no key to sign with and + * so is governed by one admin's commit. docs/member-admin-promotion.md, Phase 6. + * + * The app creates the room the way the room-type screen does and administers it; + * a stand-in is the other member. Every commit goes through the publish gate and + * the relay's OK is played by hand, as in GroupLifecycleJvmTest. + */ +class AdminChangesJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val scope = CoroutineScope(Dispatchers.Default) + private val chatRepository = DatabaseChatRepository(db, scope) + private val nostrRepository = DatabaseNostrRepository(db, scope) + + @AfterTest + fun closeDb() = db.close() + + private val keyPair = KeyPair() + private val user = keyPair.pubKey.toHexKey() + private val roomId = KeyPair().pubKey.toHexKey() + private val member = MarmotStandIn() + private lateinit var routingId: String + + private suspend fun seedProfile(publicKey: String, name: String) { + val eventId = publicKey.take(32).padEnd(64, 'f') + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId)) + } + + private suspend fun room() = db.chatRoomDao().findChatRoomById(roomId)!! + private suspend fun adminLines() = db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage } + .filter { it.messageType == ChatMessage.TYPE_ADMIN_ADDED || it.messageType == ChatMessage.TYPE_ADMIN_REMOVED } + private suspend fun appGroup() = db.marmotEngine.groupManager.getGroup(routingId)!! + + /** A convenient room, made as `SelectChatRoomTypeViewModel` makes one, with the stand-in in it. */ + private suspend fun convenientRoomWithMember() { + seedProfile(user, "us") + seedProfile(member.hex, "Dana") + val created = MarmotGroupFactory.create( + creator = keyPair, roomId = roomId, name = "#room", description = null, + adminPublicKeys = listOf(user), relays = Relays.DefaultDMRelayList.map { it.url }, + profile = MarmotProfile.CURRENT, + ) + routingId = created.routingId + assertNotNull( + chatRepository.getOrCreateChatRoom( + chatRoomId = roomId, activeUserPublicKey = user, relayHint = null, defaultSubject = "#room", + description = null, mlsGroupState = created.group.saveState().encodeTls().toHex(), + ) + ) + chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = routingId) + chatRepository.reconcileAdmins(roomId) + invite() + } + + /** Invites the stand-in with a fresh key package and has it join from the Welcome. */ + private suspend fun invite() { + val earlier = db.giftWrapPayloadDao().getAllGiftWrapUnsigned().map { it.id }.toSet() + member.makeBundle() + chatRepository.inviteMember( + room(), member.hex, + MarmotKeyPackage( + id = member.hex + db.giftWrapPayloadDao().getAllGiftWrapUnsigned().size, publicKey = member.hex, + tlsEncodedMarmotKeyPackage = member.bundle.keyPackage.toTlsBytes(), profile = MarmotProfile.CURRENT.wireName, + ), + ) + val welcome = db.giftWrapPayloadDao().getAllGiftWrapUnsigned().single { it.kind == WelcomeEvent.KIND && it.id !in earlier } + val welcomeEvent = WelcomeEvent(id = welcome.id, pubKey = user, createdAt = welcome.createdAt.epochSeconds, tags = welcome.tags, content = welcome.content, sig = "") + member.manager.processWelcome(Base64.decode(welcomeEvent.welcomeBase64()), member.bundle) + member.inbound.trackGroup(routingId) + } + + /** The relay's OK on the newest commit this device put on the wire, which the stand-in then applies. */ + private suspend fun okTheLatestCommit(): GroupEvent { + val event = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 50) + .filter { it.kind == GroupEvent.KIND } + .filter { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null } + .first { db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(it.id)?.status == "pending" } + val request = db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id)!! + nostrRepository.broadcastProcessed(request, "published") + val groupEvent = event.toGroupEvent(user)!! + if (member.manager.isMember(routingId)) member.inbound.processGroupEvent(groupEvent) + return groupEvent + } + + @Test + fun `an admin makes a member an admin, every device agrees, and the room says it once`() = runBlocking { + convenientRoomWithMember() + + chatRepository.promoteMember(room(), member.hex) + assertFalse(member.hex in appGroup().currentAdminIdentities(), "applied before any relay accepted it") + val commit = okTheLatestCommit() + + assertTrue(member.hex in appGroup().currentAdminIdentities()) + assertTrue(member.manager.getGroup(routingId)!!.isLocalAdmin(), "the promotion did not reach the member") + assertEquals(listOf("Dana is now an admin"), adminLines().map { it.content }) + + // The relay hands the app its own commit back: nothing more is said. + MarmotStandIn.storeInApp(db, keyPair, commit) + assertEquals(1, adminLines().size, "the echo of our own commit captioned it again") + } + + @Test + fun `a promoted member can govern, and a demoted one cannot`() = runBlocking { + convenientRoomWithMember() + chatRepository.promoteMember(room(), member.hex) + okTheLatestCommit() + + chatRepository.demoteMember(room(), member.hex) + okTheLatestCommit() + + assertEquals(setOf(user), appGroup().currentAdminIdentities()) + assertFalse(member.manager.getGroup(routingId)!!.isLocalAdmin()) + assertFailsWith("a demoted member's own library let it change the admin list") { + member.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(listOf(member.hex)).encode()) + } + assertTrue(adminLines().any { it.messageType == ChatMessage.TYPE_ADMIN_REMOVED && it.content == "Dana is no longer an admin" }) + } + + @Test + fun `the only admin cannot step down, and is told what to do instead`() = runBlocking { + convenientRoomWithMember() + + val refusal = assertFailsWith { chatRepository.demoteMember(room(), user) } + + assertEquals("You're the only admin. Make someone else an admin first", refusal.message) + assertTrue(db.marmotPublishObligationDao().getAll().isEmpty(), "a refused change still raised an obligation") + } + + @Test + fun `with another admin, an admin can step down`() = runBlocking { + convenientRoomWithMember() + chatRepository.promoteMember(room(), member.hex) + okTheLatestCommit() + + chatRepository.demoteMember(room(), user) + okTheLatestCommit() + + assertEquals(setOf(member.hex), appGroup().currentAdminIdentities()) + assertFalse(appGroup().isLocalAdmin()) + assertTrue(adminLines().any { it.content == "You are no longer an admin" }) + } + + @Test + fun `a change while another is waiting for a relay is refused in words`() = runBlocking { + convenientRoomWithMember() + chatRepository.promoteMember(room(), member.hex) + + // Asked again before the first is accepted: the gate holds one commit at a time. + assertFailsWith { chatRepository.promoteMember(room(), member.hex) } + } + + /** + * The hole this phase closes. A bare Remove left the admin's key on the list, + * so inviting them back made them an admin again with nobody having said so. + */ + @Test + fun `a removed admin who is invited back is not an admin`() = runBlocking { + convenientRoomWithMember() + chatRepository.promoteMember(room(), member.hex) + okTheLatestCommit() + + chatRepository.removeMember(room(), member.hex) + okTheLatestCommit() // the demotion; its confirmation stages the removal + assertEquals(setOf(user), appGroup().currentAdminIdentities(), "the admin list still names them") + okTheLatestCommit() // the removal + assertFalse(member.hex in appGroup().currentMemberIdentities(), "the removal did not follow the demotion") + + invite() + assertTrue(member.hex in appGroup().currentMemberIdentities()) + assertEquals(setOf(user), appGroup().currentAdminIdentities(), "re-invited, and an admin again") + } + + @Test + fun `a keyed room's admins are not changed by one admin's commit`() = runBlocking { + seedProfile(user, "us") + val keyedRoomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey()) + assertIs( + MarmotGroupCreation.create( + database = db, chatRepository = chatRepository, groupId = keyedRoomId, name = "#keyed", + purpose = "Admins.", adminPublicKeys = setOf(user), userPublicKey = user, keyPair = keyPair, + profile = MarmotProfile.CURRENT, + ) + ) + val keyedRoom = db.chatRoomDao().findChatRoomById(keyedRoomId)!! + + val refusal = assertFailsWith { chatRepository.demoteMember(keyedRoom, user) } + assertEquals(mobi.giza.compose.database.dao.MarmotOutboundDao.KEYED_ROOM_REFUSAL, refusal.message) + assertTrue(db.marmotPublishObligationDao().getAll().isEmpty()) + } +}