diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 80a643f1..d8054d99 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -60,6 +60,7 @@ import mobi.giza.compose.exceptions.MarmotMissingKeyPackageBundleException import mobi.giza.compose.exceptions.MarmotMissingNostrGroupDataExtension import mobi.giza.compose.exceptions.MarmotNotMemberOfChatGroupException import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.AdminFlags import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.managers.ShareRepairManager @@ -899,6 +900,17 @@ abstract class NostrDao( participants ) + // The admins, from the group context this device + // was welcomed into. Without it a joiner's rows + // flagged nobody until some later commit arrived, + // which in a robust group's admin room may be + // never -- docs/robust-group-admins.md, Phase 2. + AdminFlags.reconcile( + database = database, + chatRoomId = nostrGroupId, + mlsGroup = group, + ) + // Save ChatRoom Relays... participants.filter { it.participantPublicKey != userPublicKey }.forEach { participant -> val publicKey = participant.participantPublicKey diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt new file mode 100644 index 00000000..cb121030 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt @@ -0,0 +1,59 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.mls.group.MlsGroup +import kotlin.time.Clock +import mobi.giza.compose.database.GizaDatabase + +/** + * `Participant.adminAt`, kept in line with the group's own admin policy. + * + * The policy is the truth -- `AdminPolicyV1` on the current profile, + * `MarmotGroupData.admin_pubkeys` on the legacy one -- and it is what the library + * enforces and what `isLocalAdmin()` reads. The column is this device's cache of + * it, for the screens that label members. A cache with three writers drifted: + * the creator caught its rows up by hand, a commit reconciled them, and the + * Welcome wrote none at all, so on every device but the creator's a robust + * group's admin room showed no admins until some later commit happened to + * arrive. docs/robust-group-admins.md, G2 and D2. + * + * So there is one writer, and every path that changes what the policy says or + * which rows exist calls it: the room's creation, the Welcome, and every commit. + * + * Flags only, never membership. Removing the rows of members the tree no longer + * holds is `MarmotInboundManager.processGroupMembershipChanges`'s job, on a + * commit; doing it here would turn a best-effort step -- a partly failed invite + * at creation, say -- into a partial membership. + */ +object AdminFlags { + private val logger = Logger.withTag("AdminFlags") + + /** + * Flags the rows of [chatRoomId] that [mlsGroup]'s admin policy names and + * clears the rest. Reads the rows fresh, so it can run straight after an + * upsert that added some. + * + * @return how many rows changed. + */ + suspend fun reconcile(database: GizaDatabase, chatRoomId: String, mlsGroup: MlsGroup): Int { + val admins = mlsGroup.currentAdminIdentities() + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return 0 + val now = Clock.System.now() + + val changed = room.localParticipants.map { it.participant }.mapNotNull { participant -> + val named = participant.participantPublicKey in admins + when { + named && participant.adminAt == null -> participant.copy(adminAt = now) + !named && participant.adminAt != null -> participant.copy(adminAt = null) + else -> null + } + } + + if (changed.isNotEmpty()) { + logger.d("$chatRoomId: ${changed.size} admin flag(s) brought in line with the group") + database.participantDao().upsert(changed) + } + return changed.size + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt index 66ced0bf..e3623067 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt @@ -9,7 +9,6 @@ import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first -import kotlin.time.Clock import kotlinx.coroutines.withTimeoutOrNull import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.DkgSession @@ -188,7 +187,7 @@ object MarmotGroupCreation { logger.w("$groupId created without ${notAdded.size} member(s): $notAdded") } - stampAdmins(database, groupId, adminPublicKeys) + flagAdmins(database, groupId) return Outcome.Created( room = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom, @@ -262,45 +261,25 @@ object MarmotGroupCreation { * Writes `adminAt` on the rows of the members this room was created with as * admins. * - * The creating device never learns this any other way, which is a bug older - * than subgroups and easy to miss. `Participant.adminAt` is written in exactly - * one place -- `MarmotInboundManager.processGroupMembershipChanges`, on an - * arriving commit -- while the rows a creator makes come from - * `getOrCreateChatRoom` and `addMembers`, neither of which sets it. So on the - * device that made the room, every participant reads as a non-admin until some - * *other* member sends a commit it processes: a room whose epoch-0 context - * names three admins had none of them flagged, on the one device certain to be - * one. + * The creating device never learns this any other way: its rows come from + * `getOrCreateChatRoom` and `addMembers`, neither of which sets the flag, and + * no commit arrives to reconcile them -- a room whose epoch-0 context named + * three admins had none of them flagged on the one device certain to be one. * - * This is the same list already baked into `MarmotGroupData` a few lines - * above, so nothing new is being asserted -- the row is being caught up with - * the group context it was created from. `processGroupMembershipChanges` - * reconciles it against the MLS tree from then on and will agree. - * - * Only flags are written. That function also *removes* participants missing - * from the tree, and running the whole reconciliation here would soft-delete + * Through [AdminFlags.reconcile], off the group this device just made, rather + * than off [create]'s own list: the policy is what every other device reads, + * and one writer is how the two cannot disagree (docs/robust-group-admins.md, + * D2). Only flags are written. A membership reconciliation here would remove * the rows of anyone `addMembers` could not reach -- turning a partial invite - * into a partial membership. Widening a flag is safe; narrowing membership on - * a best-effort step is not. + * into a partial membership. * * Swallowed on failure, like `adopt` above it: the room is made and usable, - * and what a missing flag costs is a button not being offered rather than - * anything being wrong. + * and what a missing flag costs is a label rather than anything being wrong. */ - private suspend fun stampAdmins( - database: GizaDatabase, - groupId: String, - adminPublicKeys: Set - ) { + private suspend fun flagAdmins(database: GizaDatabase, groupId: String) { runCatching { - val room = database.chatRoomDao().findChatRoomById(groupId) ?: return - - val stamped = room.localParticipants - .map { it.participant } - .filter { it.participantPublicKey in adminPublicKeys && it.adminAt == null } - .map { it.copy(adminAt = Clock.System.now()) } - - if (stamped.isNotEmpty()) database.participantDao().upsert(stamped) + val group = database.chatRoomDao().findChatRoomById(groupId)?.chatRoom?.toMlsGroup() ?: return + AdminFlags.reconcile(database, groupId, group) }.onFailure { logger.e("Created $groupId but could not flag its admins", it) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt index af9fac92..e10d30d6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt @@ -3,7 +3,6 @@ package mobi.giza.compose.managers import co.touchlab.kermit.Logger import com.vitorpamplona.marmot.GroupEventResult import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent -import com.vitorpamplona.marmot.groups.currentAdminIdentities import com.vitorpamplona.marmot.groups.currentGroupState import com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption import com.vitorpamplona.mls.codec.TlsReader @@ -136,7 +135,6 @@ object MarmotInboundManager { announceAdditions: Boolean = true, ) { logger.d("processGroupMembershipChanges") - val adminPublicKeys = mlsGroup.currentAdminIdentities() val commitedGroupMembers = Participant.fromMlsGroup( mlsGroup = mlsGroup, @@ -153,35 +151,13 @@ object MarmotInboundManager { } logger.d("excludedParticipants: $excludedParticipants") val existingParticipantPublicKeys = localChatRoom.localParticipants.map { it.participant.participantPublicKey } + // Admin flags are not written here: `AdminFlags.reconcile` below reads the + // rows this function leaves and flags them from the group's policy, the + // same call the Welcome and the room's creation make. val newParticipants = commitedGroupMembers.filter { committedGroupMember -> existingParticipantPublicKeys.contains(committedGroupMember.participantPublicKey).not() - }.map { newParticipant -> - newParticipant.copy( - adminAt = if (adminPublicKeys.contains(newParticipant.participantPublicKey)) { - Clock.System.now() - } else { - null - } - ) } logger.d("newParticipants: $newParticipants") - val removedAdmins = localChatRoom.localParticipants.filter { localParticipant -> - localParticipant.participant.adminAt != null && !adminPublicKeys.contains(localParticipant.participant.participantPublicKey) - }.map { localParticipant -> - localParticipant.participant.copy( - adminAt = null - ) - } - logger.d("removedAdmins: $removedAdmins") - - val graduatedAdmins = localChatRoom.localParticipants.filter { localParticipant -> - localParticipant.participant.adminAt == null && adminPublicKeys.contains(localParticipant.participant.participantPublicKey) - }.map { localParticipant -> - localParticipant.participant.copy( - adminAt = Clock.System.now() - ) - } - logger.d("graduatedAdmins: $graduatedAdmins") // Placeholder profiles for new participants... newParticipants.forEach { newParticipant -> @@ -246,10 +222,9 @@ object MarmotInboundManager { ) } // Handle membership changes... - database.participantDao().upsert(removedAdmins) database.participantDao().delete(excludedParticipants) database.participantDao().upsert(newParticipants) - database.participantDao().upsert(graduatedAdmins) + AdminFlags.reconcile(database, localChatRoom.chatRoom.id, mlsGroup) val userPublicKey = localChatRoom.chatRoom.userPublicKey val disbanded = mlsGroup.currentGroupState().isDisbanded diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt index d66d4ced..1285b919 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt @@ -30,6 +30,7 @@ import mobi.giza.compose.database.model.MarmotKeyPackage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Participant import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.extensions.toHex @@ -160,6 +161,47 @@ class MarmotGroupCreationJvmTest { assertEquals("#Ekklesia", data.name) } + /** + * One writer for the flags, from the group's policy, both ways: a row the + * policy names is flagged, and a row it does not name loses a flag it had. + * docs/robust-group-admins.md, Phase 2. + */ + @Test + fun `admin flags follow the group's policy, both ways`(): Unit = runBlocking { + seedProfile(user) + MarmotGroupCreation.create( + database = db, + chatRepository = repository, + groupId = groupId, + name = "#Ekklesia", + purpose = "Admins of Ekklesia.", + adminPublicKeys = setOf(user), + userPublicKey = user, + keyPair = keyPair, + ) + + val stranger = KeyPair().pubKey.toHexKey() + seedProfile(stranger) + val creatorRow = db.chatRoomDao().findChatRoomById(groupId)!!.localParticipants + .single { it.participant.participantPublicKey == user }.participant + db.participantDao().upsert( + listOf( + creatorRow.copy(adminAt = null), + Participant(participantPublicKey = stranger, chatRoomId = groupId, relayHint = null, adminAt = Clock.System.now()), + ) + ) + + val group = assertNotNull(db.chatRoomDao().findChatRoomById(groupId)!!.chatRoom.toMlsGroup()) + assertEquals(2, AdminFlags.reconcile(db, groupId, group)) + + val rows = db.chatRoomDao().findChatRoomById(groupId)!!.localParticipants.associate { + it.participant.participantPublicKey to it.participant.adminAt + } + assertNotNull(rows[user], "the policy names the creator") + assertNull(rows[stranger], "the policy does not name the stranger") + assertEquals(0, AdminFlags.reconcile(db, groupId, group), "and a second pass changes nothing") + } + // ---- From a ceremony: docs/robust-group-admins.md, Phase 1 ---------------- private val alice = KeyPair() diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt index 91283b7a..7d7e1774 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -13,7 +13,6 @@ import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent -import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertEquals @@ -179,9 +178,8 @@ class RobustGroupAdminsJvmTest { /** * The rows, which are what the screens label members with. The creator's are * caught up by `MarmotGroupCreation`; a joiner's come from the Welcome, which - * writes none of them. + * wrote none of them until Phase 2 put `AdminFlags.reconcile` on that path. */ - @Ignore("Phase 2: the Welcome writes no admin flags") @Test fun `every device flags every founding member as an admin`() = onEveryProfile { profile, phones -> val founders = phones.map { it.publicKey }.toSet()