refactor: the founding-admins check and its repair go (remove-founding-admins-card, Phase 4)

FoundingAdmins.check, announceIfMissing, ChatRepository.foundingAdmins and
addAdmins, MarmotOutboundDao.addAdmins and FoundingAdminsJvmTest are deleted:
nothing calls them any more. ceremonyOf, the one piece still used, moves to
MarmotGroupCreation beside uninvitedFounders and finishFoundingInvite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-20 10:43:09 +02:00
1 parent b5c1d9ebf3
commit d21483ef29
6 files changed
+14 -425

No files matched your search

@@ -1088,42 +1088,6 @@ abstract class MarmotOutboundDao(
}
}
/**
* Adds [publicKeys] to a current-profile room's admin policy, as an admin.
*
* Additions only. The policy committed is the one the group holds now plus
* these -- never a list built somewhere else -- so an admin already there is
* never dropped by it. One commit for all of them, through the publish gate
* like every other governance change. Nothing to do when every one is already
* listed. docs/robust-group-admins.md, Phase 3.
*/
@Transaction
open suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set<HexKey>) {
require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room can change its admins" }
val group = database.marmotEngine.groupFor(localChatRoom.routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
val current = group.currentAdminIdentities()
val added = publicKeys - current
if (added.isEmpty()) return
// A governed room's admins change only with the group's signature, so the
// repair is proposed rather than committed. The founders it adds took part
// in the ceremony and hold shares of the key, as R1 asks of every admin.
// docs/member-admin-promotion.md, Phase 5.
if (GovernanceGate.isGoverned(group)) {
GovernanceManager.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey) { copy ->
copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(current + added).encode())
}
return
}
val policy = AdminPolicyV1.ofHex(current + added).encode()
publishGatedCommit(localChatRoom) { manager, id ->
manager.stageAppDataUpdate(id, AdminPolicyV1.COMPONENT_ID, policy)
}
}
/**
* Disbands a current-profile room, as an admin.
*
@@ -19,7 +19,6 @@ import mobi.giza.compose.managers.MemberActionPolicy
import mobi.giza.compose.managers.MemberActionRoom
import mobi.giza.compose.managers.MarmotInboundManager
import mobi.giza.compose.managers.AdminFlags
import mobi.giza.compose.managers.FoundingAdmins
import mobi.giza.compose.managers.SharedKeyDerivation
import mobi.giza.compose.managers.CeremonyFollowThrough
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
@@ -117,13 +116,13 @@ class DatabaseChatRepository(
)
override suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite {
val (ceremony, ceremonyRoom) = FoundingAdmins.ceremonyOf(database, chatRoomId)
val (ceremony, ceremonyRoom) = MarmotGroupCreation.ceremonyOf(database, chatRoomId)
?: return MarmotGroupCreation.FoundingInvite.NothingToDo
return finishFoundingInvite(ceremony, ceremonyRoom)
}
override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set<HexKey> = try {
FoundingAdmins.ceremonyOf(database, localChatRoom.chatRoom.id)
MarmotGroupCreation.ceremonyOf(database, localChatRoom.chatRoom.id)
?.let { (ceremony, ceremonyRoom) ->
MarmotGroupCreation.uninvitedFounders(database, localChatRoom, ceremony, ceremonyRoom)
}
@@ -788,19 +787,6 @@ class DatabaseChatRepository(
database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey)
}
override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set<HexKey>) {
database.marmotOutboundDao().addAdmins(localChatRoom, publicKeys)
}
override suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check = try {
FoundingAdmins.check(database, chatRoomId)
} catch (e: Throwable) {
// A room whose check threw is shown without the warning rather than not
// at all; the check is a label on the room, not a gate in front of it.
logger.e("Error checking the founding admins of $chatRoomId", e)
FoundingAdmins.Check.CannotCheck
}
override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean =
ExperimentalFeatures.shareRefresh &&
runCatching { ShareRefreshManager.liveIdOf(database, localChatRoom, memberPublicKey) != null }.getOrDefault(false)
@@ -1,131 +0,0 @@
package mobi.giza.compose.managers
import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
/**
* Whether a key-backed room's admin policy names every one of its founding
* members. docs/robust-group-admins.md, Phase 3.
*
* The founding members are the participants of the ceremony that made the room's
* key (D1). Every one of their devices built that set from the proposal it agreed
* to, so each can check the room it was welcomed into against its own record
* rather than trusting the device that happened to create it -- a bug, an older
* build, or a Bennu peer could all have listed fewer. A subgroup has a second
* record of the same set: the birth certificate its parent's quorum signed, which
* names its admins.
*
* Nothing is refused on a mismatch. The room's address is the key, and there is
* no second room to go to; a warning that names who is missing is what can be
* acted on, by any admin, with [missingFrom]'s answer.
*/
object FoundingAdmins {
/** Enough of a key to tell two members apart when no profile is stored. */
private const val SHORTENED_PUBLIC_KEY_LENGTH = 12
sealed interface Check {
/**
* No key behind the room: a one-to-one chat, a group made before every
* group was robust, or one a Bennu peer made. Run by its creator.
*/
data object NotKeyBacked : Check
/**
* A key-backed room this device holds no ceremony for: a member added
* after the founding, or a reinstall. It is not one of the founders, and
* has nothing of its own to check the room against.
*/
data object CannotCheck : Check
data object Matches : Check
/** Founding members the room's admin policy does not name. */
data class Missing(val publicKeys: Set<HexKey>) : Check
}
suspend fun check(database: GizaDatabase, chatRoomId: String): Check {
val state = database.groupKeyStateDao().getByChatRoomId(chatRoomId) ?: return Check.NotKeyBacked
val group = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.toMlsGroup()
?: return Check.CannotCheck
val ceremony = database.dkgSessionDao().getSessionById(state.dkgSessionId)
val founders = foundersOf(database, ceremony).orEmpty() + certifiedAdmins(state.birthCertificateJson)
if (founders.isEmpty()) return Check.CannotCheck
val missing = founders - group.currentAdminIdentities()
return if (missing.isEmpty()) Check.Matches else Check.Missing(missing)
}
/**
* Checks the room this device was just welcomed into, and says so in its
* transcript when founding members are missing from its admins. Once, at the
* Welcome: the detail screen repeats the check on every visit, and a line per
* visit would be the same news told again.
*
* A whole sentence naming who is missing, like the membership lines it sits
* among, so nothing prefixes a sender's name to it.
*/
suspend fun announceIfMissing(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Check {
val check = check(database, chatRoomId)
if (check !is Check.Missing) return check
val names = check.publicKeys.map { publicKey ->
database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey()
?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH)
}.sorted()
database.chatMessageDao().upsert(
ChatMessage(
content = "This room was created without ${names.joinToString(", ")} as " +
(if (names.size == 1) "an admin" else "admins") +
", though they took part in the key ceremony. An admin can add them back from the room's details.",
messageType = ChatMessage.TYPE_FOUNDING_ADMINS_MISSING,
chatRoomId = chatRoomId,
senderPublicKey = userPublicKey,
isUserMessage = true,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
)
)
return check
}
/**
* The ceremony that made [chatRoomId]'s key, as this device holds it, and the
* room it ran in -- or null where this device holds no key state for the room,
* no record of that ceremony, or no longer the room it ran in.
*/
suspend fun ceremonyOf(database: GizaDatabase, chatRoomId: String): Pair<DkgSession, LocalChatRoom>? {
val state = database.groupKeyStateDao().getByChatRoomId(chatRoomId) ?: return null
val ceremony = database.dkgSessionDao().getSessionById(state.dkgSessionId) ?: return null
val ceremonyRoom = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return null
return ceremony to ceremonyRoom
}
/** The ceremony's participants, or null when this device holds no record of them. */
private suspend fun foundersOf(database: GizaDatabase, ceremony: DkgSession?): Set<HexKey>? {
ceremony ?: return null
ceremony.participantPublicKeySet()?.let { return it }
val ceremonyRoom = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return null
return ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom)
}
/**
* The admins a subgroup's parent certified it with, or nothing for a group
* with no parent. Only read off a state that `GroupKeyStateManager.stateFrom`
* kept, which it does only for a certificate that checked out.
*/
private fun certifiedAdmins(birthCertificateJson: String?): Set<HexKey> =
birthCertificateJson
?.let { Event.fromJsonOrNull(it) }
?.let { SubgroupBirthCertificateEvent.parseAdminPublicKeys(it.tags).toSet() }
.orEmpty()
}
@@ -322,6 +322,18 @@ object MarmotGroupCreation {
return ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) - holdingLeaves
}
/**
* The ceremony that made [chatRoomId]'s key, as this device holds it, and the
* room it ran in -- or null where this device holds no key state for the room,
* no record of that ceremony, or no longer the room it ran in.
*/
suspend fun ceremonyOf(database: GizaDatabase, chatRoomId: String): Pair<DkgSession, LocalChatRoom>? {
val state = database.groupKeyStateDao().getByChatRoomId(chatRoomId) ?: return null
val ceremony = database.dkgSessionDao().getSessionById(state.dkgSessionId) ?: return null
val ceremonyRoom = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return null
return ceremony to ceremonyRoom
}
/**
* Invites the founding members [room]'s founding invite never reached -- see
* [uninvitedFounders] -- in one commit, as [create] would have.
@@ -19,7 +19,6 @@ import mobi.giza.compose.database.model.Participant
import mobi.giza.compose.database.model.intermdiate.LocalChatMessage
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.types.MarmotReindexReport
import mobi.giza.compose.managers.FoundingAdmins
import mobi.giza.compose.managers.MarmotGroupCreation
import mobi.giza.compose.managers.SubgroupManager
import mobi.giza.compose.nostr.MarmotProfile
@@ -369,21 +368,6 @@ interface ChatRepository {
/** Accepts [offerId]. Returns null when the acceptance went out, or why it could not. */
suspend fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey): String?
/**
* Adds [publicKeys] to a current-profile room's admin policy, as an admin of
* it: one commit through the publish gate, additions only. The repair for a
* room missing founding members from its admins -- see [foundingAdmins] and
* docs/robust-group-admins.md, Phase 3.
*/
suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set<HexKey>)
/**
* Whether [chatRoomId]'s admin policy names every member of the ceremony that
* made its key, as this device's own record of that ceremony has them. See
* `FoundingAdmins`.
*/
suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check
/**
* 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
@@ -650,11 +634,6 @@ interface ChatRepository {
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit
override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set<HexKey>) = Unit
override suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check =
FoundingAdmins.Check.NotKeyBacked
override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = false
override suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? = null
@@ -1,221 +0,0 @@
package mobi.giza.compose.managers
import androidx.room3.Room
import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.time.Clock
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.ChatRoom
import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.GroupKeyState
import mobi.giza.compose.database.model.Participant
import mobi.giza.compose.database.model.types.DkgRitualStage
import mobi.giza.compose.database.repository.DatabaseChatRepository
import mobi.giza.compose.database.repository.DatabaseNostrRepository
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.MarmotProfile
import mobi.giza.compose.nostr.Relays
/**
* A device checking the room it holds against the ceremony it took part in.
* docs/robust-group-admins.md, Phase 3.
*
* The rooms here are made with [MarmotGroupCreation.create] and a list of admins
* on purpose: that is the one way to stand in for a room some other device made
* with fewer admins than the ceremony had, which is what the check is for.
*/
class FoundingAdminsJvmTest {
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
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 alice = KeyPair().pubKey.toHexKey()
private val bob = KeyPair().pubKey.toHexKey()
private val founders = setOf(user, alice, bob)
private val thresholdPublicKey = "02" + KeyPair().pubKey.toHexKey()
private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
private val ceremonyRoomId = "ce1e".repeat(16)
private val sessionId = "the-ceremony"
/**
* A room at [roomId] whose epoch-0 admins are [admins] -- whatever the ceremony
* said -- holding only its creator. Built from the steps `MarmotGroupCreation`
* takes, minus the invites: the check is about the policy, and listing an admin
* needs no key package of theirs.
*/
private suspend fun roomWithAdmins(admins: Set<HexKey>, profile: MarmotProfile = MarmotProfile.LEGACY) {
(founders + admins).forEach { MarmotStandIn.seedProfile(db, it) }
val created = MarmotGroupFactory.create(
creator = keyPair,
roomId = roomId,
name = "#Ekklesia",
description = SharedKeyDerivation.describe("Admins of Ekklesia."),
adminPublicKeys = admins,
relays = Relays.DefaultDMRelayList.map { it.url },
profile = profile,
)
assertNotNull(
chatRepository.getOrCreateChatRoom(
chatRoomId = roomId,
activeUserPublicKey = user,
relayHint = null,
defaultSubject = "#Ekklesia",
description = null,
mlsGroupState = created.group.saveState().encodeTls().toHex(),
)
)
chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = created.routingId)
}
private suspend fun ceremony(participants: Set<HexKey>? = founders) {
db.chatRoomDao().upsert(ChatRoom(id = ceremonyRoomId, userPublicKey = user, subject = "Ekklesia", description = null, mlsGroupState = null))
db.dkgSessionDao().upsert(
DkgSession(
id = sessionId,
chatRoomId = ceremonyRoomId,
coordinatorPublicKey = user,
userPublicKey = user,
threshold = 2,
participantCount = 3,
participantPublicKeys = participants?.let { DkgSession.formatParticipants(it) },
subject = "Ekklesia",
stage = DkgRitualStage.COMPLETE,
hostPublicKey = user,
round1Random = "aa".repeat(32),
round2AuxRandom = "bb".repeat(32),
thresholdPublicKey = thresholdPublicKey,
secretShare = "cc".repeat(32),
)
)
}
private suspend fun keyState() {
db.groupKeyStateDao().replace(
GroupKeyState(
chatRoomId = roomId,
dkgSessionId = sessionId,
thresholdPublicKey = thresholdPublicKey,
derivationPath = SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH),
announcedBy = roomId,
announcedAt = Clock.System.now(),
)
)
}
@Test
fun `a room with no key behind it has no founders to check`(): Unit = runBlocking {
roomWithAdmins(setOf(user))
assertEquals(FoundingAdmins.Check.NotKeyBacked, FoundingAdmins.check(db, roomId))
}
@Test
fun `a device that holds no ceremony for the room cannot check it`(): Unit = runBlocking {
roomWithAdmins(setOf(user))
keyState()
assertEquals(FoundingAdmins.Check.CannotCheck, FoundingAdmins.check(db, roomId))
}
@Test
fun `a room made with every founder as an admin matches`(): Unit = runBlocking {
roomWithAdmins(founders)
ceremony()
keyState()
assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.check(db, roomId))
}
@Test
fun `a room made by a device that listed only itself is missing the others`(): Unit = runBlocking {
roomWithAdmins(setOf(user))
ceremony()
keyState()
assertEquals(FoundingAdmins.Check.Missing(setOf(alice, bob)), FoundingAdmins.check(db, roomId))
}
@Test
fun `a ceremony from before its participant list falls back to its room's members`(): Unit = runBlocking {
roomWithAdmins(setOf(user))
ceremony(participants = null)
db.participantDao().upsert(founders.map { Participant(participantPublicKey = it, chatRoomId = ceremonyRoomId, relayHint = null) })
keyState()
assertEquals(FoundingAdmins.Check.Missing(setOf(alice, bob)), FoundingAdmins.check(db, roomId))
}
/** What the Welcome path writes: one line naming who is missing, and none when nobody is. */
@Test
fun `the room says who it is missing, once, and only when someone is`(): Unit = runBlocking {
roomWithAdmins(setOf(user))
ceremony()
keyState()
FoundingAdmins.announceIfMissing(db, roomId, user)
val lines = db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }
.filter { it.messageType == ChatMessage.TYPE_FOUNDING_ADMINS_MISSING }
val line = lines.single()
assertTrue(alice.take(8) in line.content && bob.take(8) in line.content, line.content)
assertTrue(ChatMessage.TYPE_FOUNDING_ADMINS_MISSING in ChatMessage.MEMBERSHIP_TYPES, "it would render as a chat bubble")
}
@Test
fun `a room that names every founder says nothing`(): Unit = runBlocking {
roomWithAdmins(founders)
ceremony()
keyState()
assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.announceIfMissing(db, roomId, user))
assertTrue(db.chatMessageDao().getChatMessagesByChatRoomId(roomId).none {
it.chatMessage.messageType == ChatMessage.TYPE_FOUNDING_ADMINS_MISSING
})
}
/**
* The repair: one commit that adds the missing founders to the policy and
* leaves every admin already there in place. On the current profile, where
* the app governs a room; the relay's OK is played by hand.
*/
@Test
fun `an admin puts the missing founders back into the policy`(): Unit = runBlocking {
roomWithAdmins(setOf(user), MarmotProfile.CURRENT)
ceremony()
keyState()
val missing = assertIs<FoundingAdmins.Check.Missing>(FoundingAdmins.check(db, roomId)).publicKeys
chatRepository.addAdmins(db.chatRoomDao().findChatRoomById(roomId)!!, missing)
okTheLatestCommit()
val room = db.chatRoomDao().findChatRoomById(roomId)!!
val group = assertNotNull(db.marmotEngine.groupFor(room.routingId))
assertEquals(founders, group.currentAdminIdentities())
assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.check(db, roomId))
}
private suspend fun okTheLatestCommit() {
val event = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 20)
.filter { it.kind == GroupEvent.KIND }
.last { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null }
val request = assertNotNull(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id))
nostrRepository.broadcastProcessed(request, "published")
}
}