From f2b0aa91d476b8924cc34f29b4decdd2bcb0bcc6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:50:34 +0200 Subject: [PATCH 1/9] docs: every founding member of a robust group is its admin, phased Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/robust-group-admins.md | 269 ++++++++++++++++++++++++++++++++++++ 2 files changed, 270 insertions(+) create mode 100644 docs/robust-group-admins.md diff --git a/docs/README.md b/docs/README.md index 5208a9ba..a3f287de 100644 --- a/docs/README.md +++ b/docs/README.md @@ -36,6 +36,7 @@ the [retired](./retired/) notes now. | [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, how often this app persists a group once a sent message no longer rewrites it, and the schema change that followed, opened from the version the app ships | | [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase | | [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu | +| [robust-group-admins.md](./robust-group-admins.md) | making every founding member of a robust group an admin of its room, on every device -- phased and not built. Covers why the ceremony's participants are the founding set, the Welcome that flags no admins, the joiner's check against the ceremony it took part in, and finishing an invite that partly failed | Start with the ceremony if you are new to this area; the Marmot notes all assume it. Read the skipped-keys note before debugging any "the other device never got it" diff --git a/docs/robust-group-admins.md b/docs/robust-group-admins.md new file mode 100644 index 00000000..3abb6483 --- /dev/null +++ b/docs/robust-group-admins.md @@ -0,0 +1,269 @@ +# Every founding member of a robust group is its admin + +A robust group promises, on the screen that makes it, that "everyone administers the +group together". This note is the plan that makes the promise true on every device from +the moment the group exists: what "founding member" means, the four places the promise +breaks today, and seven phases that close them. + +**Planned, not built.** Written against `fc437d05`. + +Read [shared-key-ceremony.md](./shared-key-ceremony.md) and +[ceremony-creation.md](./ceremony-creation.md) first. + +## What a robust group is, in the code + +A robust group is two rooms and a key. + +``` +SelectChatRoomTypeViewModel.createNip17ChatRoom + │ + ├─ the NIP-17 room members = picked + creator; no admins, no MLS + │ └─ proposeRitual ceremony participants = room members + creator + │ + ├─ the ChillDKG key t-of-n over those participants + │ + └─ the admin room (Marmot) id = marmotGroupId(threshold key) + created by CeremonyFollowThrough (step 3) or DkgRitualViewModel, + both through MarmotGroupCreation.create(adminPublicKeys = participantsOf(session)) +``` + +The NIP-17 room has no admin concept, and that is correct: membership is the p-tag set +and nothing in it can be governed. **Admin means admin of the Marmot room**, whose +epoch-0 admin policy (`AdminPolicyV1` on the current profile, `MarmotGroupData.admin_pubkeys` +on the legacy one) is what the library enforces and what `isLocalAdmin()` reads. +`Participant.adminAt` is a local cache of it. + +A subgroup is the same shape with a different participant set, and everything below +applies to it unchanged. + +`ChatRoomType` is not persisted. Nothing on a device records that a room was made robust; +what marks one is a `GroupKeyState` -- a room whose id is derived from a threshold key. + +## What "founding member" means + +**D1. The founding members of a key-backed room are the participants of the ceremony that +made its key** -- `DkgSession.participantPublicKeySet()` on the row +`GroupKeyState.dkgSessionId` names. For a top-level robust group that is the picked members +plus the creator; for a subgroup, the picked admins plus the coordinator. + +Not the NIP-17 room's rows, which `ChillDkgRitualManager.memberPublicKeys` already warns +can drift. Not the admin list a Welcome arrives with, which is one device's claim. The +session row is the one record every founding member's device built independently from the +proposal it agreed to, and the ceremony would not have completed if they disagreed about `n`. + +A member added to the admin room later is not a founding member and is not made an admin by +anything here. + +## Where the promise breaks today + +| | gap | effect | phase | +|---|---|---|---| +| G1 | The founding set is computed at three call sites -- `SelectChatRoomTypeViewModel.adminCount`, `CeremonyFollowThrough.takeNextStep` step 3, `DkgRitualViewModel` -- and passed into `MarmotGroupCreation.create` as a free parameter. `participantsOf` falls back to the room's rows when the session carries no set | nothing stops a caller passing a different set; a room's admin list is fixed at a derived address forever, so one wrong call is permanent | 1 | +| G2 | The Welcome path in `NostrDao` writes `Participant.fromMlsGroup(...)` rows with no `adminAt`. Only the creator (`stampAdmins`) and a later commit (`processGroupMembershipChanges`) ever set it | on every device but the creator's, the admin room shows no admins until some other commit arrives -- which may be never | 2 | +| G3 | A joiner never checks the admin list it was welcomed into against the ceremony it took part in | a device that created the room with a different list (a bug, an older build, a Bennu peer) goes unnoticed | 3 | +| G4 | `MarmotGroupCreation.create` returns `notAdded` when `addMembers` partly fails. Those founding members are listed as admins but hold no leaf, so the policy treats them as inactive, and nothing invites them again | a founding admin who is not in the room | 4 | + +G2 has a smaller blast radius than it sounds: `canGovern` reads `isLocalAdmin()`, and +`SubgroupManager` reads `currentAdminIdentities()`, so permissions are right. What is wrong +is every reader of `adminAt` -- today the subgroup picker's "Admin of this group" line -- +and the fact that two devices disagree about the same room. + +## Decisions + +**D2. The admin policy is the truth; `adminAt` is derived from it on every path.** One +function writes the flags, from `mlsGroup.currentAdminIdentities()`, and the creation, +Welcome and commit paths all call it. `stampAdmins` stops taking a list of its own. + +**D3. No wire change.** Putting the founding set on the signed `GroupKeyStateEvent` (so a +quorum signs it) was considered and left out: every founding member already holds the set +on its own session row, a later joiner is by definition not one of them, and the 30326 event +is shared with Bennu. Revisit if a device ever needs to check the founding set without +having taken part. + +**D4. No schema change.** Every check below is derived on demand from rows that already +exist -- the session, the key state, the stored MLS group, the participant rows -- so no +Room migration and no new column. + +## Phases + +One commit per phase. Each phase ends with: + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +and phases that touch UI also with: + +```bash +./gradlew :composeApp:m3Audit +``` + +### Phase 0: pin the invariant in a failing test + +Before changing anything, a test that states the promise and shows where it fails. + +**Add** `composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt`, +on the `CeremonyNetwork` harness `RobustRoomKeyCeremonyTest` uses, with three devices: + +- `every founding member is an admin of the room the key makes, on every device` -- run the + ceremony and follow-through, deliver the Welcomes, then on each device assert + `currentAdminIdentities() == participants`, `isLocalAdmin()` and `adminAt != null` on + exactly the founding rows. **Expected to fail on `adminAt` for the two joiners (G2).** +- `the founding set is the same set at every step` -- picked + creator, the NIP-17 room's + members, the session's participants and the admin policy are one set. +- `a member added after the founding is not an admin` -- the boundary D1 draws. +- The same three for a subgroup, on the `SubgroupCeremonyInParentRoomTest` fixtures. + +Mark the failing assertions `@Ignore("Phase 2")` and the like, so the build stays green and +each phase un-ignores what it fixes. + +**Done when** the test exists, the passing parts pass, and each ignored part names its phase. + +### Phase 1: one derivation of the founding set (G1) + +**Change** `ChatRepository.createMarmotGroup` / `MarmotGroupCreation.create` to take the +`DkgSession` instead of `adminPublicKeys`, and derive the set inside, through a new +`ChillDkgRitualManager.foundingMembersOf(session, room)`: + +- returns `session.participantPublicKeySet()` when present; +- falls back to the room's members only for a row that predates the column (logged), as + `participantsOf` does today; +- requires the creating device to be in the set -- a device outside the ceremony holds no + key state for the room and should never get here, so reaching it is a bug, not an outcome. + +The two call sites (`CeremonyFollowThrough.takeNextStep` step 3 and +`DkgRitualViewModel`'s admin-room action) stop computing a set. `SelectChatRoomTypeViewModel` +keeps `adminCount` -- the session does not exist yet on that screen -- but computes it with +the same `(members + creator).distinct()` rule `proposeRitual` uses, and a comment points at +the other. + +**Tests.** `MarmotGroupCreationJvmTest`: `the room's admins are the ceremony's participants, +whoever creates it` -- the coordinator's path and a non-coordinator's manual path produce +the same admin policy. `CeremonyFollowThroughJvmTest` keeps passing unchanged. + +**Done when** no caller can name a room's admins. + +### Phase 2: the Welcome writes admin flags (G2) + +**Add** `AdminFlags.reconcile(database, localChatRoom, mlsGroup)` in `managers/` -- flags +only, never membership: sets `adminAt` on rows the policy names and clears it on rows it +does not. It is `processGroupMembershipChanges`'s `graduatedAdmins` / `removedAdmins` / +new-participant logic, lifted out. + +**Call it** from: + +- the Welcome path in `NostrDao` (after the participant upsert, before + `GroupKeyStateManager.adopt`); +- `MarmotGroupCreation`, replacing `stampAdmins`. Its reasoning -- flags are safe, a + membership reconciliation on a best-effort step is not -- moves to the new function's KDoc; +- `processGroupMembershipChanges`, replacing its three inline admin computations. + +Having `Participant.fromMlsGroup` set `adminAt` itself would fix the Welcome alone, but it +only ever builds new rows: it cannot clear a flag on a stored one, so half the logic would +still live somewhere else. One function that does both is the point of D2. + +**Tests.** Un-ignore Phase 0's joiner assertions. Add to `WelcomeBundleMatchJvmTest`: +`a member welcomed into a room sees its admins at once`. + +**Done when** every device shows the same admins the moment it holds the room. + +### Phase 3: a joiner checks what it was welcomed into (G3) + +**Add** `FoundingAdmins.check(database, localChatRoom): Check` in `managers/`, returning one +of: + +- `NotKeyBacked` -- no key state; a convenient room, nothing to check; +- `CannotCheck` -- key state, but this device holds no session for it (a later joiner); +- `Matches` -- every founding member is in the admin policy; +- `Missing(publicKeys: Set)` -- founding members the policy does not name, against + `foundingMembersOf`. For a subgroup, also against the birth certificate's + `SubgroupBirthCertificateEvent.parseAdminPublicKeys`, which the parent's quorum signed. + +**Call it** once at the Welcome, after `adopt`, and write a transcript line on `Missing` +(a new `ChatMessage.TYPE_FOUNDING_ADMINS_MISSING`, derived like the membership captions). +And on every load of `ChatRoomDetailViewModel`, into a new +`ChatRoomDetailUIState.Loaded.foundingAdmins` field. + +The room is not left or refused. Its 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. + +**Repair**, where this device is an active admin: an "Make founding members admins" action +adds the missing ones to the policy in one admin-policy update commit. Additions only -- the +commit is built from the current policy plus `Missing`, never as a replacement list. + +**Tests.** `FoundingAdminsJvmTest`: one case per `Check`, including a Welcome built by a +device that listed only itself, and the repair commit leaving every existing admin in place. + +**Done when** a founding member left out of the admin policy is said, on the device that +can see it, and can be put back by any admin. + +### Phase 4: every founding admin is invited (G4) + +**Add step 4 to `CeremonyFollowThrough.takeNextStep`**, after the room exists: founding +members who have never had a row in the room -- not even a soft-deleted one -- are invited +with `addMembers`, one commit for all of them. "Never had a row" keeps this step to +finishing the founding invite: it never re-invites anybody who was in the room and left it. +Read-then-act like the other steps, so a repeat does nothing. + +Who acts: the coordinator, as for step 3, so two devices do not race the same epoch. Any +other active admin gets an "Invite again" action on the detail screen for the same set, for +the case the coordinator's phone is in a drawer. + +A founding member with no key package is reported as `BlockedOn`, exactly as creation does, +and the step is retried the next time the follow-through runs. + +**Tests.** `CeremonyFollowThroughJvmTest`: `a founding member the first invite missed is +invited again`, `a founding member who was in the room is not`, and `a second run invites +nobody`. + +**Done when** `Outcome.Created.notAdded` is something the follow-through finishes, not +something a screen reports and forgets. + +### Phase 5: show it + +- The admin room's member list shows "Admin" as supporting text on rows with `adminAt`. +- Phase 3's warning card and repair action, and Phase 4's "Invite again", on the detail + screen. +- The NIP-17 room's detail says its members administer the group through the admin room, + with a link to it, rather than showing no admins. + +Strings in `strings.xml`, sentence case; every new button a 48dp target; the card's states +through `ScreenStateTransition`. The m3 audit is the check. + +**Done when** a person can tell who administers the group, and whether that is everybody who +made it, without reading a transcript. + +### Phase 6: rooms that already exist + +No migration is needed (D4), but the rooms made before Phase 2 still carry unflagged +joiner rows and possibly uninvited founding admins. + +- `AdminFlags.reconcile` runs once per Marmot room at startup, behind a stored + "reconciled" preference, so G2 is repaired without waiting for a commit. +- Phase 4's step already runs over every completed session; it covers G4 for old rooms. +- Phase 3's check runs on every detail load; it covers G3 for old rooms. + +**Tests.** A fixture room with joiner rows missing `adminAt` is reconciled on start, once. + +### Phase 7: docs + +- This note: mark it built, with a table of where the build chose differently. +- [ceremony-creation.md](./ceremony-creation.md) and [subgroups.md](./subgroups.md): link + here from the admin-room creation sections. +- [README.md](./README.md): the table row is added with this note. + +## Out of scope + +- **Removing or demoting an admin**, founding or not. This plan makes the founding members + admins; what happens to them afterwards is left as it is. +- **Making a later member an admin.** A separate feature, being planned separately. +- **Convenient groups.** Their only admin is the creator, by design. +- **The NIP-17 room.** It has no state to govern; see *What a robust group is*. + +## Risks + +- **Bennu peers.** One can create the admin room with a different list; Phase 3 can say so + and repair it, but not prevent it. +- **Racing invites.** Phase 4 is coordinator-first to avoid two commits on one epoch; the + manual "Invite again" can still race, and convergence already resolves that fork + (`ConvergenceForkJvmTest`). From 3efa1af554af8a6d13e527512567407e153501eb Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:57:18 +0200 Subject: [PATCH 2/9] test: every founding member of a robust group is its admin (robust-group-admins, Phase 0) RobustGroupAdminsJvmTest states the promise and shows where it breaks. Three app phones: one creates the admin room through MarmotGroupCreation with all three as admins, the others join by a real Welcome, gift wrapped and stored through the sync funnel. On every device the admin policy names the founders and isLocalAdmin is true, on both profiles. The rows do not: a joiner's Welcome writes no adminAt, so its own rows flag nobody -- ignored until Phase 2. A member invited later is not an admin. The ceremony half checks that every device that took part agrees on the founding set, for a group and a subgroup. The later-member case runs on the legacy profile only: on the current profile MarmotGroupCreation invites the founders through a room read before its routing id is recorded, so a later invite skips its commit. Phase 4 fixes that. Co-Authored-By: Claude Opus 5.5 --- .../managers/RobustGroupAdminsJvmTest.kt | 262 ++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt new file mode 100644 index 00000000..91283b7a --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -0,0 +1,262 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +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.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +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 +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.MarmotKeyPackage +import mobi.giza.compose.database.model.types.DkgApprovalStep +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.repository.DatabaseMarmotRepository +import mobi.giza.compose.database.repository.DatabaseNostrRepository +import mobi.giza.compose.nostr.MarmotProfile + +/** + * The promise a robust group makes -- "everyone administers the group together" -- + * held on every device of every founding member. docs/robust-group-admins.md. + * + * Two halves. The ceremony half runs real ChillDKG on [CeremonyNetwork] and checks + * that every device agrees who the founding members are. The room half has one app + * device create the admin room and the others join it by a real Welcome, gift + * wrapped and stored through the same funnel a relay's copy goes through, because + * the Welcome is where a joiner first learns -- or fails to learn -- who its + * admins are. + */ +class RobustGroupAdminsJvmTest { + + /** One phone: its own database, as in the app, and nothing shared with the others. */ + private class Phone(profile: MarmotProfile) : AutoCloseable { + val keyPair = KeyPair() + val publicKey: HexKey = keyPair.pubKey.toHexKey() + val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default)) + private val nostrRepository = DatabaseNostrRepository(db, CoroutineScope(Dispatchers.Default)) + private val marmotRepository = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default)) + + /** This phone's key package, as another phone would have synced it. */ + lateinit var keyPackage: MarmotKeyPackage + + val ready: suspend () -> Unit = { + marmotRepository.publishMarmotKeyPackageBundle(keyPair, setOf(profile)) + val bundle = db.marmotKeyPackageBundleDao().getAllMarmotKeyPackageBundles(publicKey).single() + keyPackage = MarmotKeyPackage( + id = bundle.id, + publicKey = publicKey, + tlsEncodedMarmotKeyPackage = bundle.tlsEncodedMarmotKeyPackage, + profile = profile.wireName, + ) + } + + /** + * A relay's OK on the newest commit this phone put on the wire. An invite + * into a room that already has members holds its Welcome back until then. + */ + 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") + } + + override fun close() = db.close() + override fun toString() = publicKey.take(8) + } + + private val roomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey()) + + /** + * Three phones; the first creates the admin room with all three as its admins, + * as `CeremonyFollowThrough` does after a ceremony, and the other two join it. + */ + private suspend fun foundedRoom(profile: MarmotProfile, size: Int = 3): List { + val phones = List(size) { Phone(profile) } + phones.forEach { it.ready() } + phones.forEach { phone -> phones.forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } } + + val creator = phones.first() + phones.drop(1).forEach { creator.db.marmotKeyPackageDao().upsert(it.keyPackage) } + + val outcome = MarmotGroupCreation.create( + database = creator.db, + chatRepository = creator.chatRepository, + groupId = roomId, + name = "Ekklesia", + purpose = "Admins of Ekklesia.", + adminPublicKeys = phones.map { it.publicKey }.toSet(), + userPublicKey = creator.publicKey, + keyPair = creator.keyPair, + keyPackageLookupTimeout = 2_000L, + profile = profile, + ) + val created = assertIs(outcome) + assertTrue(created.notAdded.isEmpty(), "the creator could not invite ${created.notAdded}") + + phones.drop(1).forEach { welcome(from = creator, to = it) } + return phones + } + + /** Hands [to] the Welcome [from] queued for it, wrapped as a relay would carry it. */ + private suspend fun welcome(from: Phone, to: Phone) { + val payload = from.db.giftWrapPayloadDao().getAllGiftWrapUnsigned() + .filter { it.kind == WelcomeEvent.KIND } + .single { payload -> payload.tags.any { it.size > 1 && it[1] == to.keyPackage.id } } + + val rumor = RumorAssembler.assembleRumor( + pubKey = from.publicKey, + ev = EventTemplate(payload.createdAt.epochSeconds, payload.kind, payload.tags, payload.content), + ) + val signer = NostrSignerSync(from.keyPair) + val seal = signer.signNormal( + createdAt = rumor.createdAt, kind = SealEvent.KIND, tags = emptyArray(), + content = signer.nip44Encrypt(rumor.toJson(), to.publicKey), + ) + val wrap = GiftWrapEvent.create(event = seal, recipientPubKey = to.publicKey, createdAt = rumor.createdAt) + + MarmotStandIn.storeInApp(to.db, to.keyPair, wrap) + assertNotNull(to.db.chatRoomDao().findChatRoomById(roomId), "$to did not join from the Welcome") + } + + // ---- The room ---------------------------------------------------------------- + + /** [block] on a freshly founded room, once on each profile a room can be made on. */ + private fun onEveryProfile( + profiles: List = listOf(MarmotProfile.LEGACY, MarmotProfile.CURRENT), + block: suspend (MarmotProfile, List) -> Unit, + ) = runBlocking { + profiles.forEach { profile -> + val phones = foundedRoom(profile) + try { + block(profile, phones) + } finally { + phones.forEach { it.close() } + } + } + } + + private suspend fun Phone.room() = assertNotNull(db.chatRoomDao().findChatRoomById(roomId), "$this has no room") + + /** Whom this phone's own rows call an admin. */ + private suspend fun Phone.flaggedAdmins(): Set = room().localParticipants + .map { it.participant } + .filter { it.deletedAt == null && it.adminAt != null } + .map { it.participantPublicKey } + .toSet() + + @Test + fun `every founding member is in the room's admin policy, on every device`() = onEveryProfile { profile, phones -> + val founders = phones.map { it.publicKey }.toSet() + + phones.forEach { phone -> + val group = assertNotNull(phone.room().chatRoom.toMlsGroup(), "$phone holds no group ($profile)") + assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)") + assertTrue(group.isLocalAdmin(), "$phone is not an admin of its own room ($profile)") + } + } + + /** + * 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. + */ + @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() + + phones.forEach { phone -> + assertEquals(founders, phone.flaggedAdmins(), "$phone's rows say a different set are admins ($profile)") + } + } + + /** + * The boundary docs/robust-group-admins.md, D1 draws: founding, not present. + * + * Legacy only until Phase 4. On the current profile `MarmotGroupCreation` invites + * the founders through a room read before its routing id was recorded, so the + * engine's group at the real address still holds only the creator, and a later + * invite takes the founding path -- no commit, and nobody else told. + */ + @Test + fun `a member added after the founding is not an admin`() = onEveryProfile(listOf(MarmotProfile.LEGACY)) { profile, phones -> + val founders = phones.map { it.publicKey }.toSet() + val creator = phones.first() + + Phone(profile).use { later -> + later.ready() + (phones + later).forEach { phone -> (phones + later).forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } } + + creator.chatRepository.inviteMember(creator.room(), later.publicKey, later.keyPackage) + creator.okTheLatestCommit() + welcome(from = creator, to = later) + + listOf(creator, later).forEach { phone -> + val group = assertNotNull(phone.room().chatRoom.toMlsGroup(), "$phone holds no group ($profile)") + assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)") + assertTrue(later.publicKey !in phone.flaggedAdmins(), "$phone flags the later member ($profile)") + } + assertFalse(assertNotNull(later.room().chatRoom.toMlsGroup()).isLocalAdmin(), "the later member governs ($profile)") + } + } + + // ---- The ceremony ------------------------------------------------------------ + + @Test + fun `the founding set is the same set on every device that took part`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3).use { network -> + val everyone = network.devices.map { it.publicKey }.toSet() + val session = network.propose(threshold = 2) + network.deliverUntilQuiet() + network.devices.drop(1).forEach { network.approve(it, session.id, DkgApprovalStep.HOST_KEY) } + network.deliverUntilQuiet() + + network.devices.forEach { device -> + val theirs = assertNotNull(network.session(device, session.id), "$device has no ceremony") + assertEquals(everyone, ChillDkgRitualManager.memberPublicKeys(network.room(device)), "$device's room") + assertEquals(everyone, theirs.participantPublicKeySet(), "$device's ceremony") + assertEquals( + everyone, + ChillDkgRitualManager.participantsOf(theirs, network.room(device)), + "$device's founding set", + ) + } + } + } + + @Test + fun `a subgroup's founding set is its ceremony's participants on every device in it`(): Unit = runBlocking { + val parentId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey()) + CeremonyNetwork.marmot(size = 4, roomId = parentId).use { network -> + val picked = network.devices.take(3).map { it.publicKey }.toSet() + val session = network.propose(threshold = 2, participants = picked, parentChatRoomId = parentId, subject = "Translation") + network.deliverUntilQuiet() + + network.devices.take(3).forEach { device -> + val theirs = assertNotNull(network.session(device, session.id), "$device has no ceremony") + assertEquals(picked, ChillDkgRitualManager.participantsOf(theirs, network.room(device)), "$device") + } + } + } +} From d7fb71036f5eec39f2504ae9b2693a871e96f1e0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:02:08 +0200 Subject: [PATCH 3/9] feat: a robust group's admin room takes its admins from the ceremony (robust-group-admins, Phase 1) ChatRepository.createMarmotGroup now takes the ceremony and the room it ran in instead of a list of admins, and MarmotGroupCreation.createFor derives the room's id, name, description and admins from it. The two callers -- CeremonyFollowThrough's step 3 and the ritual screen's button -- stop computing a set of their own. A room's epoch-0 admin list is fixed for good at an address the key derives, so the one place the founding set is read is now the one place a room is made. A device that was not in the ceremony is refused rather than listed as the room's creator. MarmotGroupCreationJvmTest: the coordinator's device and a member's make a room with the same admins, the ceremony's participants; an outsider makes none. jvmTest 1236/1236 (1 skipped, Phase 2's), compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../repository/DatabaseChatRepository.kt | 22 ++-- .../compose/managers/CeremonyFollowThrough.kt | 11 +- .../compose/managers/MarmotGroupCreation.kt | 63 ++++++++++ .../giza/compose/repository/ChatRepository.kt | 30 ++--- .../ui/view/model/DkgRitualViewModel.kt | 38 ++---- .../view/model/SelectChatRoomTypeViewModel.kt | 6 + .../managers/CeremonyFollowThroughJvmTest.kt | 11 +- .../managers/KeyStateSignsItselfJvmTest.kt | 12 +- .../managers/MarmotGroupCreationJvmTest.kt | 108 +++++++++++++++++- 9 files changed, 221 insertions(+), 80 deletions(-) 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 1a119258..f76a9b99 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 @@ -29,6 +29,7 @@ import mobi.giza.compose.database.GENESIS_AT import mobi.giza.compose.database.GizaDatabase 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.GiftWrapPayload import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.database.model.GroupSignedEvent @@ -48,7 +49,6 @@ import mobi.giza.compose.database.model.types.ShareRepairStage import mobi.giza.compose.database.model.types.ShareRefreshStage import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep import mobi.giza.compose.database.model.types.DkgRitualStage -import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.managers.ShareGenerations import mobi.giza.compose.managers.ShareRepairManager import mobi.giza.compose.ExperimentalFeatures @@ -73,24 +73,16 @@ class DatabaseChatRepository( val logger = Logger.withTag(TAG) override suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List, parentChatRoomId: HexKey?, - ): MarmotGroupCreation.Outcome = MarmotGroupCreation.create( + ): MarmotGroupCreation.Outcome = MarmotGroupCreation.createFor( database = database, chatRepository = this, - groupId = groupId, - name = name, - purpose = purpose, - adminPublicKeys = adminPublicKeys, - userPublicKey = userPublicKey, + ceremony = ceremony, + ceremonyRoom = ceremonyRoom, keyPair = keyPair, - path = path, parentChatRoomId = parentChatRoomId, ) @@ -778,4 +770,4 @@ class DatabaseChatRepository( companion object { const val TAG = "DatabaseChatRepository" } -} \ No newline at end of file +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt index 85846d44..0f0fb013 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt @@ -240,14 +240,13 @@ object CeremonyFollowThrough { } } - // 3. The room, with everyone the ceremony was run with as its admins. + // 3. The room, with everyone the ceremony was run with as its admins -- + // which `MarmotGroupCreation.createFor` reads off the ceremony itself, so + // there is no list here to get wrong (docs/robust-group-admins.md, Phase 1). when ( val outcome = chatRepository.createMarmotGroup( - groupId = roomId, - name = roomName(current), - purpose = roomPurpose(current), - adminPublicKeys = participants, - userPublicKey = current.userPublicKey, + ceremony = current, + ceremonyRoom = ceremonyRoom, keyPair = keyPair, // Verified by the time it is written: the key state this room was // gated on carries the certificate, and `stateFrom` refused it 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 0875dc3c..66ced0bf 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt @@ -12,6 +12,7 @@ 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 import mobi.giza.compose.database.model.MarmotKeyPackage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex @@ -195,6 +196,68 @@ object MarmotGroupCreation { ) } + /** + * Creates the room [ceremony]'s key derives, with the ceremony's participants + * as its admins. + * + * The only way the app makes such a room, and the reason [create] takes a list + * of admins nobody outside this file supplies. The founding members of a + * robust group are the participants of the ceremony that made its key -- + * every one of their devices built that set from the proposal it agreed to -- + * and a room's epoch-0 admin list is fixed for good at an address derived from + * the key. Two callers computing it was two chances to compute it differently. + * See docs/robust-group-admins.md, D1 and Phase 1. + * + * The room's id, name and description come off the ceremony too, so the + * coordinator's device creating it on its own and a member pressing the + * button make the same room. + * + * [ceremonyRoom] is the room the ceremony ran in: the participant set falls + * back to its members for a ceremony that predates its own participant list, + * as [ChillDkgRitualManager.participantsOf] does everywhere. + * + * A device that was not in the ceremony is refused. It holds no key state for + * the room and no share of the key, and listing itself as the room's + * creator would put an admin into the room the group never chose. + */ + suspend fun createFor( + database: GizaDatabase, + chatRepository: ChatRepository, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + keyPair: KeyPair, + parentChatRoomId: HexKey? = null, + keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT, + profile: MarmotProfile = MarmotProfile.DEFAULT_FOR_NEW_ROOMS, + ): Outcome { + val thresholdPublicKey = ceremony.thresholdPublicKey + ?: return Outcome.Failed("This ceremony has no key yet.") + + val founders = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) + if (ceremony.participantPublicKeySet() == null) { + logger.w("Ceremony ${ceremony.id} predates its participant list; its room's members are its founders") + } + + if (ceremony.userPublicKey !in founders) { + logger.e("Not creating the room for ${ceremony.id}: ${ceremony.userPublicKey} was not in it") + return Outcome.Failed("Only someone who took part in the key ceremony can create its room.") + } + + return create( + database = database, + chatRepository = chatRepository, + groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey), + name = CeremonyFollowThrough.roomName(ceremony), + purpose = CeremonyFollowThrough.roomPurpose(ceremony), + adminPublicKeys = founders, + userPublicKey = ceremony.userPublicKey, + keyPair = keyPair, + parentChatRoomId = parentChatRoomId, + keyPackageLookupTimeout = keyPackageLookupTimeout, + profile = profile, + ) + } + /** * Writes `adminAt` on the rows of the members this room was created with as * admins. 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 f8a61f1f..8284ded8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -9,6 +9,7 @@ import com.vitorpamplona.quartz.nip17Dm.settings.DmRelayListEvent import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.GiftWrapPayload import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.database.model.GroupSignedEvent @@ -18,7 +19,6 @@ 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.MarmotGroupCreation -import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.ui.view.state.SharesSummary @@ -196,26 +196,30 @@ interface ChatRepository { ): List /** - * Creates a Marmot room at an id the group's key derives, with - * [adminPublicKeys] as its admins, and welcomes them into it. + * Creates the Marmot room [ceremony]'s key derives, with everyone the ceremony + * was run with as its admins, and welcomes them into it. * * Two flows want exactly this: the admin room a group opens after its * ceremony, and a subgroup. See `MarmotGroupCreation`, which holds the rules * -- every key package before anything exists, the admins baked into epoch 0, * and the key state filed before the members are added. * + * Takes the ceremony rather than a list of admins on purpose. The room's id + * is derived, so its epoch-0 admin list is fixed at that address for good, and + * the founding members of a robust group are exactly the ceremony's + * participants -- so the one place that set is read is the one place a room is + * made. [ceremonyRoom] is the room the ceremony ran in, read only for a + * ceremony that predates its own participant list. See + * docs/robust-group-admins.md, Phase 1. + * * Refuses rather than half-creates: the id is derived, so a partly created * room occupies that address permanently and there is no second id to retry * with. */ suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH, parentChatRoomId: HexKey? = null, ): MarmotGroupCreation.Outcome @@ -439,13 +443,9 @@ interface ChatRepository { ): List = peers.map { it.first } override suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List, parentChatRoomId: HexKey?, ): MarmotGroupCreation.Outcome = MarmotGroupCreation.Outcome.Failed("No database") diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt index 4bca2b1a..115dd582 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt @@ -53,7 +53,6 @@ import mobi.giza.compose.database.model.intermdiate.LocalFrostSigningSession import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlin.time.Instant -import mobi.giza.compose.managers.CeremonyFollowThrough /** * Watches one ChillDKG ritual, and the steps that follow it. @@ -522,7 +521,7 @@ class DkgRitualViewModel( val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return val session = loaded.session - val thresholdPublicKey = session.thresholdPublicKey ?: return + if (session.thresholdPublicKey == null) return // The screen offers nothing until the group has signed, so this is a // guard rather than a path anybody takes. @@ -535,43 +534,24 @@ class DkgRitualViewModel( } val keyPair = KeyPair(privKey = nostrPrivateKey.value.toByteArray()) - val groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - - // Everyone the ceremony was run with, this device included. These are the - // admins: the whole point of the room is that the members who hold shares of - // the key can all act in it. - // - // Off the ceremony rather than off the room, because for a subgroup the - // room is the parent's and its roster is the wrong set entirely. - val members = ChillDkgRitualManager.participantsOf(session, loaded.localChatRoom) - - // A subgroup is called what the coordinator called it; an admin room is - // called after the group it administers, because it has no name of its - // own to be given. Either way the bare name goes down and - // `MarmotGroupCreation` puts it under `MarmotGroupName`, so a NIP-17 room - // called `Ekklesia` stands up a Marmot room called `#Ekklesia`. - // The same name and description the coordinator's device uses when it - // creates the room on its own -- see `CeremonyFollowThrough` -- so the two - // ways of making it cannot make two different rooms. - val subgroupParent = loaded.parentChatRoomId - - val name = CeremonyFollowThrough.roomName(session) isActionPending.value = true adminGroupBlockedOn.value = emptyList() viewModelScope.launch(Dispatchers.IO) { + // The room, its name and its admins all come off the ceremony, inside + // `MarmotGroupCreation.createFor` -- the same call the coordinator's + // device makes on its own in `CeremonyFollowThrough`, so the two ways of + // making it cannot make two different rooms. Nothing here names an + // admin: docs/robust-group-admins.md, Phase 1. val outcome = chatRepository.createMarmotGroup( - groupId = groupId, - name = name, - purpose = CeremonyFollowThrough.roomPurpose(session), - adminPublicKeys = members, - userPublicKey = activeUserPublicKey, + ceremony = session, + ceremonyRoom = loaded.localChatRoom, keyPair = keyPair, // Verified by the time it is written: the key state this room was // gated on carries the certificate, and `stateFrom` refused it // otherwise. - parentChatRoomId = subgroupParent + parentChatRoomId = loaded.parentChatRoomId ) isActionPending.value = false diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt index 0d4c290f..3a884bed 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt @@ -94,6 +94,12 @@ class SelectChatRoomTypeViewModel( /** * Everyone who administers the group under [ChatRoomType.ROBUST]: the picked * members plus the creator. + * + * Counted here only to offer a quorum. The admins themselves are read off + * the ceremony this screen opens -- `ChillDkgRitualManager.proposeRitual` + * builds its participants by the same rule, the room's members plus the + * creator -- and `MarmotGroupCreation.createFor` makes the admin room from + * those. See docs/robust-group-admins.md, Phase 1. */ val adminCount: Int = (memberPublicKeys + activeUserPublicKey).distinct().size diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt index 5ff9d1fc..19003418 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.model.types.DkgRitualStage @@ -52,15 +53,13 @@ class CeremonyFollowThroughJvmTest { private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { override suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List, parentChatRoomId: HexKey?, ): MarmotGroupCreation.Outcome { + val groupId = SharedKeyDerivation.marmotGroupId(ceremony.thresholdPublicKey!!) + val adminPublicKeys = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) created += groupId to adminPublicKeys return outcome(groupId) } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt index ce886ee3..c5c15336 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt @@ -9,8 +9,10 @@ import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.FrostSigningItem import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.nostr.frost.GroupKeyStateEvent @@ -32,15 +34,13 @@ class KeyStateSignsItselfJvmTest { private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { override suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List, parentChatRoomId: HexKey?, ): MarmotGroupCreation.Outcome { + val groupId = SharedKeyDerivation.marmotGroupId(ceremony.thresholdPublicKey!!) + val adminPublicKeys = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) created += groupId to adminPublicKeys return MarmotGroupCreation.Outcome.Failed("the room is MarmotGroupCreation's to test") } 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 3b7f1528..d66d4ced 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt @@ -22,6 +22,13 @@ import kotlinx.coroutines.IO import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase +import com.vitorpamplona.marmot.appComponents.CurrentProfileGroupFactory +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession +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.Profile import mobi.giza.compose.database.repository.DatabaseChatRepository @@ -153,9 +160,104 @@ class MarmotGroupCreationJvmTest { assertEquals("#Ekklesia", data.name) } - private suspend fun seedProfile(publicKey: String) { + // ---- From a ceremony: docs/robust-group-admins.md, Phase 1 ---------------- + + private val alice = KeyPair() + private val bob = KeyPair() + private val ceremonyRoomId = "ce1e".repeat(16) + + /** A finished ceremony over [user], alice and bob, as [owner]'s device holds it. */ + private suspend fun ceremonyOn(database: GizaDatabase, owner: KeyPair): Pair { + val everyone = listOf(keyPair, alice, bob) + everyone.forEach { seedProfile(it.pubKey.toHexKey(), database) } + + // Everybody but the device's own owner, as that device would have synced them. + everyone.filter { it !== owner }.forEach { peer -> + val bundle = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(peer)) + database.marmotKeyPackageDao().upsert( + MarmotKeyPackage( + id = peer.pubKey.toHexKey().take(60) + "0000", + publicKey = peer.pubKey.toHexKey(), + tlsEncodedMarmotKeyPackage = bundle.keyPackage.toTlsBytes(), + profile = MarmotProfile.CURRENT.wireName, + ) + ) + } + + database.chatRoomDao().upsert( + ChatRoom(id = ceremonyRoomId, userPublicKey = owner.pubKey.toHexKey(), subject = "Ekklesia", description = null, mlsGroupState = null) + ) + val session = DkgSession( + id = "the-ceremony", + chatRoomId = ceremonyRoomId, + coordinatorPublicKey = user, + userPublicKey = owner.pubKey.toHexKey(), + threshold = 2, + participantCount = 3, + participantPublicKeys = DkgSession.formatParticipants(everyone.map { it.pubKey.toHexKey() }.toSet()), + subject = "Ekklesia", + stage = DkgRitualStage.COMPLETE, + hostPublicKey = owner.pubKey.toHexKey(), + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = "02" + "ab".repeat(32), + secretShare = "cc".repeat(32), + ) + database.dkgSessionDao().upsert(session) + return session to assertNotNull(database.chatRoomDao().findChatRoomById(ceremonyRoomId)) + } + + @Test + fun `the room's admins are the ceremony's participants, whoever creates it`(): Unit = runBlocking { + val founders = setOf(user, alice.pubKey.toHexKey(), bob.pubKey.toHexKey()) + val alicesDb = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + try { + // The coordinator's device, and a member's -- the two ways the room gets made. + listOf(db to keyPair, alicesDb to alice).forEach { (database, owner) -> + val (session, ceremonyRoom) = ceremonyOn(database, owner) + + val outcome = MarmotGroupCreation.createFor( + database = database, + chatRepository = DatabaseChatRepository(database, CoroutineScope(Dispatchers.IO)), + ceremony = session, + ceremonyRoom = ceremonyRoom, + keyPair = owner, + keyPackageLookupTimeout = 2_000L, + ) + val created = assertIs(outcome) + assertEquals(groupId, created.room.chatRoom.id, "the room is not the one the key derives") + assertEquals("#Ekklesia", created.room.chatRoom.subject) + + val group = assertNotNull(created.room.chatRoom.toMlsGroup()) + assertEquals(founders, group.currentAdminIdentities(), "${owner.pubKey.toHexKey().take(8)}'s room") + } + } finally { + alicesDb.close() + } + } + + @Test + fun `a device that was not in the ceremony cannot create its room`(): Unit = runBlocking { + val (session, ceremonyRoom) = ceremonyOn(db, keyPair) + val outsider = session.copy(userPublicKey = KeyPair().pubKey.toHexKey()) + + val outcome = MarmotGroupCreation.createFor( + database = db, + chatRepository = repository, + ceremony = outsider, + ceremonyRoom = ceremonyRoom, + keyPair = KeyPair(), + ) + + assertIs(outcome) + assertNull(db.chatRoomDao().findChatRoomById(groupId), "a room was made anyway") + } + + private suspend fun seedProfile(publicKey: String, database: GizaDatabase = db) { + if (database.profileDao().getProfileByPublicKey(publicKey) != null) return val nostrEventId = publicKey.take(63) + "f" - db.nostrEventDao().upsert( + database.nostrEventDao().upsert( NostrEvent( id = nostrEventId, pubKey = publicKey, @@ -165,7 +267,7 @@ class MarmotGroupCreationJvmTest { sig = "0".repeat(128), ) ) - db.profileDao().upsert( + database.profileDao().upsert( Profile(publicKey = publicKey, userName = "member", nostrEventId = nostrEventId) ) } From 83711419ef0d299b40ceda45ea5ec32250131de0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:05:42 +0200 Subject: [PATCH 4/9] fix: a member welcomed into a room sees its admins at once (robust-group-admins, Phase 2) Participant.adminAt had three writers and the Welcome was not one of them: a joiner's rows came from Participant.fromMlsGroup with no flag, so on every device but the creator's a robust group's admin room showed no admins until some later commit happened to arrive. AdminFlags.reconcile is now the one writer. It reads the room's rows fresh and flags them from the group's own admin policy, both ways, and writes nothing about membership. The Welcome path calls it after the participant upsert; MarmotGroupCreation calls it in place of stampAdmins, off the group it just made rather than its own list; and processGroupMembershipChanges calls it in place of its three inline computations. Phase 0's ignored test passes. MarmotGroupCreationJvmTest: flags follow the policy both ways, and a second pass changes nothing. jvmTest 1237/1237, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../giza/compose/database/dao/NostrDao.kt | 12 ++++ .../mobi/giza/compose/managers/AdminFlags.kt | 59 +++++++++++++++++++ .../compose/managers/MarmotGroupCreation.kt | 49 +++++---------- .../compose/managers/MarmotInboundManager.kt | 33 ++--------- .../managers/MarmotGroupCreationJvmTest.kt | 42 +++++++++++++ .../managers/RobustGroupAdminsJvmTest.kt | 4 +- 6 files changed, 132 insertions(+), 67 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt 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() From 4671a86a6de121497871ae6b9279dfc7b942df30 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:10:01 +0200 Subject: [PATCH 5/9] feat: a device checks its admin room against the ceremony it took part in (robust-group-admins, Phase 3) FoundingAdmins.check compares a key-backed room's admin policy with the participants of the ceremony that made its key, as this device's own DkgSession row has them -- and, for a subgroup, with the admins its parent's birth certificate names. NotKeyBacked, CannotCheck (a later joiner, who holds no ceremony), Matches, or Missing with who. At the Welcome, after the key state is adopted, a room missing founders gets one transcript line naming them (TYPE_FOUNDING_ADMINS_MISSING, a membership line). The detail screen reads the check on every load into ChatRoomDetailUIState.missingFoundingAdmins. The repair is MarmotOutboundDao.addAdmins: one gated commit on the current profile that writes the policy the group holds now plus the missing founders -- additions only, never a list built elsewhere. The legacy profile has no governance commits in this app, so a legacy room gets the warning without the repair. FoundingAdminsJvmTest: each Check, the pre-column fallback, the line written once and only when someone is missing, and the repair on the current profile through a relay's OK. jvmTest 1245/1245, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../compose/database/dao/MarmotOutboundDao.kt | 26 +++ .../giza/compose/database/dao/NostrDao.kt | 12 + .../compose/database/model/ChatMessage.kt | 9 + .../repository/DatabaseChatRepository.kt | 14 ++ .../giza/compose/managers/FoundingAdmins.kt | 115 +++++++++ .../giza/compose/repository/ChatRepository.kt | 21 ++ .../ui/view/model/ChatRoomDetailViewModel.kt | 17 ++ .../ui/view/state/ChatRoomDetailUIState.kt | 7 + .../compose/managers/FoundingAdminsJvmTest.kt | 221 ++++++++++++++++++ 9 files changed, 442 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt 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 e0d28947..9f98ea80 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 @@ -7,6 +7,7 @@ import com.vitorpamplona.crypto.random.RandomInstance import com.vitorpamplona.marmot.appComponents.AppComponentIds import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent import com.vitorpamplona.marmot.groups.MlsGroupManager +import com.vitorpamplona.marmot.appComponents.AdminPolicyV1 import com.vitorpamplona.marmot.groups.currentAdminIdentities import com.vitorpamplona.marmot.groups.currentGroupState import com.vitorpamplona.marmot.groups.isLocalAdmin @@ -862,6 +863,31 @@ abstract class MarmotOutboundDao( publishGatedCommit(localChatRoom) { manager, id -> manager.stageRemoveMember(id, leafIndex) } } + /** + * 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) { + 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 + + 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. * 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 d8054d99..7facdce2 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 @@ -61,6 +61,7 @@ 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.FoundingAdmins import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.managers.ShareRepairManager @@ -972,6 +973,17 @@ abstract class NostrDao( chatRoomId = nostrGroupId ) + // And with the state on file, whether the room + // names every member of that ceremony as an + // admin -- this device's own record against the + // creator's list. docs/robust-group-admins.md, + // Phase 3. + FoundingAdmins.announceIfMissing( + database = database, + chatRoomId = nostrGroupId, + userPublicKey = userPublicKey, + ) + // Where is the decoded welcome message... // TODO: Sync GroupEvents/Messages... // database.chatMessageDao().upsert( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index a0907524..ef1c736b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -577,6 +577,14 @@ data class ChatMessage( */ const val TYPE_CHANGE_REJECTED = "changeRejected" + /** + * The admin room this device was welcomed into does not name every member + * of the ceremony that made its key as an admin. Derived at the Welcome + * from this device's own record of the ceremony, never received, and + * written once. docs/robust-group-admins.md, Phase 3. + */ + const val TYPE_FOUNDING_ADMINS_MISSING = "foundingAdminsMissing" + /** * Every membership line, for the one check the transcript dispatches on. * @@ -591,6 +599,7 @@ data class ChatMessage( TYPE_MEMBER_LEFT, TYPE_GROUP_DISBANDED, TYPE_CHANGE_REJECTED, + TYPE_FOUNDING_ADMINS_MISSING, ) const val TYPE_UNDECRYPTABLE_OUTER_LAYER = "undecryptableOuterLayer" 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 f76a9b99..e713b2bb 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 @@ -7,6 +7,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import mobi.giza.compose.managers.FoundingAdmins import mobi.giza.compose.managers.CeremonyFollowThrough import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate @@ -639,6 +640,19 @@ class DatabaseChatRepository( database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey) } + override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) { + 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) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt new file mode 100644 index 00000000..bd5b78b6 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt @@ -0,0 +1,115 @@ +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.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 convenient group, 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) : 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's participants, or null when this device holds no record of them. */ + private suspend fun foundersOf(database: GizaDatabase, ceremony: DkgSession?): Set? { + 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 = + birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?.let { SubgroupBirthCertificateEvent.parseAdminPublicKeys(it.tags).toSet() } + .orEmpty() +} 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 8284ded8..bdb80a06 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -18,6 +18,7 @@ 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 @@ -272,6 +273,21 @@ interface ChatRepository { */ suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) + /** + * 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) + + /** + * 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 @@ -486,6 +502,11 @@ interface ChatRepository { override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit + override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) = 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 diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 3cb13a0e..83a7739b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -18,6 +18,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch +import mobi.giza.compose.managers.FoundingAdmins import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.managers.WalletRefusal @@ -108,6 +109,9 @@ class ChatRoomDetailViewModel( canGovern = canGovern, isDisbanded = isDisbanded, shares = chatRepository.sharesSummary(localChatRoom), + missingFoundingAdmins = (chatRepository.foundingAdmins(chatRoomId) as? FoundingAdmins.Check.Missing) + ?.publicKeys + .orEmpty(), ) } } @@ -136,6 +140,19 @@ class ChatRoomDetailViewModel( } } + /** + * Adds the founding members the room's admin policy is missing, as an admin, + * and reloads the screen. One commit, applied when a relay accepts it, so the + * warning stays until then. docs/robust-group-admins.md, Phase 3. + */ + fun addMissingFoundingAdmins(localChatRoom: LocalChatRoom, missing: Set, onDone: (String?) -> Unit = {}) { + viewModelScope.launch(Dispatchers.IO) { + val failure = runCatching { chatRepository.addAdmins(localChatRoom, missing) }.exceptionOrNull() + initiateChatRoomDetail() + viewModelScope.launch(Dispatchers.Main) { onDone(failure?.message) } + } + } + /** * Runs one Shares section action, reloads the screen, and reports: null for * done, or why not. Every one of them is a proposal or an answer the group diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 5b7b8511..20b85009 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -84,6 +84,13 @@ sealed interface ChatRoomDetailUIState { * room has no key (docs/frost-share-refresh.md, Phase 11). */ val shares: SharesSummary? = null, + /** + * Members of the ceremony that made this room's key whom its admin policy + * does not name -- empty when it names them all, and when this device has + * no record of the ceremony to check against. Read through + * `FoundingAdmins.check`; docs/robust-group-admins.md, Phase 3. + */ + val missingFoundingAdmins: Set = emptySet(), ): ChatRoomDetailUIState data class Error( diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt new file mode 100644 index 00000000..adb93818 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt @@ -0,0 +1,221 @@ +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()) + 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, 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? = 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(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") + } +} From 1dc94ad423692da8d3f8d3d8d1ba2f9bc1e1d04a Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:14:19 +0200 Subject: [PATCH 6/9] feat: a founding invite that never went out is finished (robust-group-admins, Phase 4) MarmotGroupCreation.finishFoundingInvite invites the founders a room's founding invite never reached, in one commit, every key package first as at creation. It acts only on a room still at epoch 0: the founding invite is the commit that ends epoch 0, and leaving is a commit too, so a founder without a leaf there is one nobody ever invited -- never one who left. CeremonyFollowThrough takes it as step 4 once the room exists, on the coordinator's device; the repository exposes it by room for the detail screen, with the set it would invite. Also fixes what Phase 0 found. MarmotGroupCreation invited the founders through a room read before its routing id was recorded, so on the current profile the engine adopted a second copy of the group under the room id, and the copy at the real address still held only its creator: every later invite took the founding path, with no commit and nobody already in the room told. It now reads the room again first. RobustGroupAdminsJvmTest: a room left without its invite is finished and every founder joins as an admin, on both profiles; a room past its founding invites nobody; a later member on the current profile now gets a real commit. CeremonyFollowThroughJvmTest: step 4's outcomes. jvmTest 1249/1249, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../repository/DatabaseChatRepository.kt | 27 ++++ .../compose/managers/CeremonyFollowThrough.kt | 29 +++- .../giza/compose/managers/FoundingAdmins.kt | 13 ++ .../compose/managers/MarmotGroupCreation.kt | 102 ++++++++++++- .../giza/compose/repository/ChatRepository.kt | 21 +++ .../managers/CeremonyFollowThroughJvmTest.kt | 25 ++++ .../managers/RobustGroupAdminsJvmTest.kt | 135 +++++++++++++++++- 7 files changed, 340 insertions(+), 12 deletions(-) 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 e713b2bb..75987d93 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 @@ -87,6 +87,33 @@ class DatabaseChatRepository( parentChatRoomId = parentChatRoomId, ) + override suspend fun finishFoundingInvite( + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + ): MarmotGroupCreation.FoundingInvite = MarmotGroupCreation.finishFoundingInvite( + database = database, + chatRepository = this, + ceremony = ceremony, + ceremonyRoom = ceremonyRoom, + ) + + override suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite { + val (ceremony, ceremonyRoom) = FoundingAdmins.ceremonyOf(database, chatRoomId) + ?: return MarmotGroupCreation.FoundingInvite.NothingToDo + return finishFoundingInvite(ceremony, ceremonyRoom) + } + + override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = try { + FoundingAdmins.ceremonyOf(database, localChatRoom.chatRoom.id) + ?.let { (ceremony, ceremonyRoom) -> + MarmotGroupCreation.uninvitedFounders(database, localChatRoom, ceremony, ceremonyRoom) + } + .orEmpty() + } catch (e: Throwable) { + logger.e("Error reading who ${localChatRoom.chatRoom.id}'s founding invite missed", e) + emptySet() + } + override suspend fun followThroughCeremonies(keyPair: KeyPair) = CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt index 0f0fb013..430c9e06 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt @@ -30,7 +30,9 @@ import mobi.giza.compose.repository.ChatRepository * 1. a subgroup's parent certifies the room the key derives -- proposed here, and * signed by the parent's own quorum, which stays their decision; * 2. the group signs what that room will sign with, its key state; - * 3. the room is created and the members welcomed into it. + * 3. the room is created and the members welcomed into it; + * 4. a room whose founding invite never went out has it finished + * (docs/robust-group-admins.md, Phase 4). * * None of the three proposals asks anybody anything: each is a request to the * group, and the coordinator agreed to make it when they opened the ceremony. So @@ -62,7 +64,7 @@ object CeremonyFollowThrough { /** What one call to [takeNextStep] did. */ sealed interface Step { - /** Not this device's to do, or nothing left: not the coordinator, not finished, or the room exists. */ + /** Not this device's to do, or nothing left: not the coordinator, not finished, or the room exists with its founders. */ data object NothingToDo : Step /** Waiting on signatures somebody else gives. */ @@ -74,6 +76,12 @@ object CeremonyFollowThrough { /** The room exists now. */ data class Created(val chatRoomId: String) : Step + /** + * The room existed without its founders, whose invite never went out, and + * now they have been invited; [notAdded] could not be. + */ + data class Invited(val chatRoomId: String, val notAdded: List) : Step + /** The room cannot be created until these members' devices publish a key package. */ data class BlockedOn(val missing: List) : Step @@ -166,11 +174,24 @@ object CeremonyFollowThrough { val thresholdPublicKey = current.thresholdPublicKey ?: return@withLock Step.NothingToDo val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - if (database.chatRoomDao().findChatRoomById(roomId) != null) return@withLock Step.NothingToDo - val ceremonyRoom = database.chatRoomDao().findChatRoomById(current.chatRoomId) ?: return@withLock Step.Stuck("The room ceremony ${current.id} ran in is gone") + // 4. The room exists: finish its founding invite if it never went out. + // Only a room still at epoch 0 has anything to finish, so nobody who + // left is ever invited back -- see `MarmotGroupCreation.uninvitedFounders`. + if (database.chatRoomDao().findChatRoomById(roomId) != null) { + return@withLock when (val invite = chatRepository.finishFoundingInvite(current, ceremonyRoom)) { + MarmotGroupCreation.FoundingInvite.NothingToDo -> Step.NothingToDo + is MarmotGroupCreation.FoundingInvite.Sent -> { + logger.i("Ceremony ${current.id}: invited ${invite.invited.size} founder(s) to $roomId") + Step.Invited(roomId, invite.notAdded) + } + is MarmotGroupCreation.FoundingInvite.BlockedOn -> Step.BlockedOn(invite.missing) + is MarmotGroupCreation.FoundingInvite.Failed -> Step.Stuck(invite.reason) + } + } + val participants = ChillDkgRitualManager.participantsOf(current, ceremonyRoom) val parent = current.parentChatRoomId diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt index bd5b78b6..b0b5c836 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt @@ -6,6 +6,7 @@ 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 /** @@ -94,6 +95,18 @@ object FoundingAdmins { 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? { + 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? { ceremony ?: return null 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 e3623067..2f8c4570 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt @@ -4,6 +4,7 @@ import co.touchlab.kermit.Logger import mobi.giza.compose.nostr.MarmotProfile import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.mls.group.MlsGroup import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope @@ -11,6 +12,7 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.withTimeoutOrNull import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.Participant import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.MarmotKeyPackage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom @@ -177,8 +179,16 @@ object MarmotGroupCreation { // there is a row to file it against. GroupKeyStateManager.adopt(database, groupId) + // Read again now the routing is on file. The row above predates it, and a + // room with no routing row is addressed by its own id -- so on the current + // profile the invite went to a second copy of the group the engine adopted + // under the room id, and the copy at the real address still held only its + // creator. Every later invite then took the founding path: no commit, and + // nobody already in the room told. docs/robust-group-admins.md, Phase 4. + val routedRoom = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom + val notAdded = runCatching { - chatRepository.addMembers(localChatRoom = localChatRoom, peers = addable) + chatRepository.addMembers(localChatRoom = routedRoom, peers = addable) }.onFailure { logger.e("Failed to add members to $groupId", it) }.getOrElse { addable.map { (publicKey, _) -> publicKey } } @@ -257,6 +267,96 @@ object MarmotGroupCreation { ) } + /** What [finishFoundingInvite] did. */ + sealed interface FoundingInvite { + /** Every founding member holds a leaf, or the room is past its founding. */ + data object NothingToDo : FoundingInvite + + /** The founders who were missing were invited; [notAdded] could not be. */ + data class Sent(val chatRoomId: String, val invited: List, val notAdded: List) : FoundingInvite + + /** Some founders have no published key package, so nobody was invited. */ + data class BlockedOn(val missing: List) : FoundingInvite + + data class Failed(val reason: String) : FoundingInvite + } + + /** + * The founding members of [room] its founding invite never reached: listed as + * admins, holding no leaf, in a room nothing has been committed to since it was + * made. + * + * Only at epoch 0. A room is created at epoch 0 and its founding invite is the + * commit that leaves it -- so a room still there is one whose invite failed + * outright, and nobody in it has left or been removed, because either would + * have been a commit. Past epoch 0 a founder without a leaf might be one who + * left, and inviting them back is not this function's to decide + * (docs/robust-group-admins.md, Out of scope). + * + * A device holds a room at epoch 0 only if it made it: everybody else's copy + * comes from a Welcome, which is already past the founding commit. + */ + suspend fun uninvitedFounders( + database: GizaDatabase, + room: LocalChatRoom, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + ): Set { + val group = liveGroupOf(database, room) ?: return emptySet() + if (group.epoch != 0L) return emptySet() + + val holdingLeaves = Participant.fromMlsGroup(group, room.chatRoom.id, null).map { it.participantPublicKey }.toSet() + return ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) - holdingLeaves + } + + /** + * Invites the founding members [room]'s founding invite never reached -- see + * [uninvitedFounders] -- in one commit, as [create] would have. + * + * Every key package first, as at creation: a founder who cannot be invited yet + * holds the rest back rather than leaving the room to a second, partial + * founding. docs/robust-group-admins.md, Phase 4. + */ + suspend fun finishFoundingInvite( + database: GizaDatabase, + chatRepository: ChatRepository, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT, + ): FoundingInvite { + val thresholdPublicKey = ceremony.thresholdPublicKey ?: return FoundingInvite.NothingToDo + val groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + val room = chatRepository.getChatRoomByIdentifier(groupId) ?: return FoundingInvite.NothingToDo + + val uninvited = uninvitedFounders(database, room, ceremony, ceremonyRoom) + if (uninvited.isEmpty()) return FoundingInvite.NothingToDo + + val keyPackages = keyPackagesFor(chatRepository, uninvited.toList(), keyPackageLookupTimeout, room.chatRoom.marmotProfile()) + val missing = keyPackages.filter { it.second == null }.map { it.first } + if (missing.isNotEmpty()) { + logger.w("Not finishing $groupId's founding invite: no key package for $missing") + return FoundingInvite.BlockedOn(missing) + } + val addable = keyPackages.mapNotNull { (publicKey, keyPackage) -> keyPackage?.let { publicKey to it } } + + val notAdded = runCatching { + chatRepository.addMembers(localChatRoom = room, peers = addable) + }.onFailure { + logger.e("Failed to finish $groupId's founding invite", it) + }.getOrElse { return FoundingInvite.Failed(it.message ?: "Couldn't invite them. Please try again.") } + + flagAdmins(database, groupId) + logger.i("Finished $groupId's founding invite: ${addable.size - notAdded.size} invited, ${notAdded.size} not") + return FoundingInvite.Sent(groupId, addable.map { it.first }, notAdded) + } + + /** The room's live group: the row's on the legacy profile, the engine's on the current one. */ + private suspend fun liveGroupOf(database: GizaDatabase, room: LocalChatRoom): MlsGroup? = + when (room.chatRoom.marmotProfile()) { + MarmotProfile.LEGACY -> room.chatRoom.toMlsGroup() + MarmotProfile.CURRENT -> database.marmotEngine.groupFor(room.routingId) + } + /** * Writes `adminAt` on the rows of the members this room was created with as * admins. 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 bdb80a06..20d1eee1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -224,6 +224,19 @@ interface ChatRepository { parentChatRoomId: HexKey? = null, ): MarmotGroupCreation.Outcome + /** + * Invites the founding members [ceremony]'s room never reached, when its + * founding invite never went out. See `MarmotGroupCreation.finishFoundingInvite` + * and docs/robust-group-admins.md, Phase 4. + */ + suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom): MarmotGroupCreation.FoundingInvite + + /** [finishFoundingInvite] for the room [chatRoomId], through the ceremony its key state names. */ + suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite + + /** The founders [localChatRoom]'s founding invite never reached; empty when there are none to reach. */ + suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set + /** * Takes every key ceremony [keyPair] coordinated from a key to a working room, * until cancelled: asks the group to sign its key state (a subgroup's parent to @@ -468,6 +481,14 @@ interface ChatRepository { override suspend fun followThroughCeremonies(keyPair: KeyPair) = Unit + override suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom) = + MarmotGroupCreation.FoundingInvite.NothingToDo + + override suspend fun finishFoundingInvite(chatRoomId: String) = + MarmotGroupCreation.FoundingInvite.NothingToDo + + override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = emptySet() + override suspend fun sendChatMessage( text: String, diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt index 19003418..25e9ad7c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt @@ -50,6 +50,7 @@ class CeremonyFollowThroughJvmTest { /** The room creations asked for, and what the next one answers. */ private val created = mutableListOf>>() private var outcome: (String) -> MarmotGroupCreation.Outcome = { MarmotGroupCreation.Outcome.Failed("unset") } + private var foundingInvite: MarmotGroupCreation.FoundingInvite = MarmotGroupCreation.FoundingInvite.NothingToDo private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { override suspend fun createMarmotGroup( @@ -63,6 +64,8 @@ class CeremonyFollowThroughJvmTest { created += groupId to adminPublicKeys return outcome(groupId) } + + override suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom) = foundingInvite } private val material = keyMaterial("5eed0000000000000000000000000000000000000000000000000000000000e5") @@ -203,6 +206,28 @@ class CeremonyFollowThroughJvmTest { assertTrue(created.isEmpty()) } + /** docs/robust-group-admins.md, Phase 4: a room that exists is asked whether its founding invite went out. */ + @Test + fun `a room whose founding invite never went out has it finished`(): Unit = runBlocking { + val session = finishedCeremony() + signKeyState(session) + GroupFixtures.seedRoom(db, roomOf(material)) + foundingInvite = MarmotGroupCreation.FoundingInvite.Sent(roomOf(material), invited = listOf(alice, bob), notAdded = listOf(bob)) + + assertEquals(CeremonyFollowThrough.Step.Invited(roomOf(material), listOf(bob)), next(session)) + assertTrue(created.isEmpty(), "and no second room") + } + + @Test + fun `a founding invite waiting on key packages says on whom`(): Unit = runBlocking { + val session = finishedCeremony() + signKeyState(session) + GroupFixtures.seedRoom(db, roomOf(material)) + foundingInvite = MarmotGroupCreation.FoundingInvite.BlockedOn(listOf(alice)) + + assertEquals(CeremonyFollowThrough.Step.BlockedOn(listOf(alice)), next(session)) + } + /** * A subgroup's room needs its parent's certificate before its key state can * even be proposed, so that is asked for first -- and then the parent's 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 7d7e1774..cd660d8c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -26,6 +26,12 @@ import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase import mobi.giza.compose.database.model.MarmotKeyPackage +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.database.repository.DatabaseMarmotRepository @@ -84,7 +90,8 @@ class RobustGroupAdminsJvmTest { override fun toString() = publicKey.take(8) } - private val roomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey()) + private val foundingThresholdPublicKey = "02" + KeyPair().pubKey.toHexKey() + private val roomId = SharedKeyDerivation.marmotGroupId(foundingThresholdPublicKey) /** * Three phones; the first creates the admin room with all three as its admins, @@ -118,7 +125,7 @@ class RobustGroupAdminsJvmTest { } /** Hands [to] the Welcome [from] queued for it, wrapped as a relay would carry it. */ - private suspend fun welcome(from: Phone, to: Phone) { + private suspend fun welcome(from: Phone, to: Phone, roomId: String = this.roomId) { val payload = from.db.giftWrapPayloadDao().getAllGiftWrapUnsigned() .filter { it.kind == WelcomeEvent.KIND } .single { payload -> payload.tags.any { it.size > 1 && it[1] == to.keyPackage.id } } @@ -192,13 +199,14 @@ class RobustGroupAdminsJvmTest { /** * The boundary docs/robust-group-admins.md, D1 draws: founding, not present. * - * Legacy only until Phase 4. On the current profile `MarmotGroupCreation` invites - * the founders through a room read before its routing id was recorded, so the - * engine's group at the real address still holds only the creator, and a later - * invite takes the founding path -- no commit, and nobody else told. + * On both profiles since Phase 4. Before it, `MarmotGroupCreation` invited the + * founders on the current profile through a room read before its routing id was + * recorded, so the engine's group at the real address still held only the + * creator, and this later invite took the founding path -- no commit, and + * nobody else told. */ @Test - fun `a member added after the founding is not an admin`() = onEveryProfile(listOf(MarmotProfile.LEGACY)) { profile, phones -> + fun `a member added after the founding is not an admin`() = onEveryProfile { profile, phones -> val founders = phones.map { it.publicKey }.toSet() val creator = phones.first() @@ -219,6 +227,119 @@ class RobustGroupAdminsJvmTest { } } + // ---- The founding invite: docs/robust-group-admins.md, Phase 4 ------------- + + private val ceremonyRoomId = "ce1e".repeat(16) + + /** The ceremony [phones] ran, as [owner]'s device holds it: everyone in it, and its key [roomId]'s. */ + private suspend fun ceremonyOn(owner: Phone, phones: List, thresholdPublicKey: HexKey): Pair { + owner.db.chatRoomDao().upsert( + ChatRoom(id = ceremonyRoomId, userPublicKey = owner.publicKey, subject = "Ekklesia", description = null, mlsGroupState = null) + ) + val session = DkgSession( + id = "the-ceremony", + chatRoomId = ceremonyRoomId, + coordinatorPublicKey = owner.publicKey, + userPublicKey = owner.publicKey, + threshold = 2, + participantCount = phones.size, + participantPublicKeys = DkgSession.formatParticipants(phones.map { it.publicKey }.toSet()), + subject = "Ekklesia", + stage = DkgRitualStage.COMPLETE, + hostPublicKey = owner.publicKey, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = thresholdPublicKey, + secretShare = "cc".repeat(32), + ) + owner.db.dkgSessionDao().upsert(session) + return session to assertNotNull(owner.db.chatRoomDao().findChatRoomById(ceremonyRoomId)) + } + + /** + * A room whose founding invite never went out: made, with every founder in + * its policy, and nobody but its creator in its tree -- what `create` leaves + * when `addMembers` throws. + */ + private suspend fun roomWithoutItsInvite(profile: MarmotProfile, phones: List, roomId: String) { + val creator = phones.first() + val created = MarmotGroupFactory.create( + creator = creator.keyPair, + roomId = roomId, + name = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of Ekklesia."), + adminPublicKeys = phones.map { it.publicKey }, + relays = Relays.DefaultDMRelayList.map { it.url }, + profile = profile, + ) + assertNotNull( + creator.chatRepository.getOrCreateChatRoom( + chatRoomId = roomId, + activeUserPublicKey = creator.publicKey, + relayHint = null, + defaultSubject = "#Ekklesia", + description = null, + mlsGroupState = created.group.saveState().encodeTls().toHex(), + ) + ) + creator.chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = created.routingId) + } + + @Test + fun `a founding invite that never went out is finished, and every founder is an admin`(): Unit = runBlocking { + listOf(MarmotProfile.LEGACY, MarmotProfile.CURRENT).forEach { profile -> + val phones = List(3) { Phone(profile) } + try { + phones.forEach { it.ready() } + phones.forEach { phone -> phones.forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } } + val creator = phones.first() + phones.drop(1).forEach { creator.db.marmotKeyPackageDao().upsert(it.keyPackage) } + + val thresholdPublicKey = "02" + KeyPair().pubKey.toHexKey() + val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + roomWithoutItsInvite(profile, phones, roomId) + val (session, ceremonyRoom) = ceremonyOn(creator, phones, thresholdPublicKey) + + val invite = MarmotGroupCreation.finishFoundingInvite( + creator.db, creator.chatRepository, session, ceremonyRoom, keyPackageLookupTimeout = 2_000L, + ) + val sent = assertIs(invite, "($profile)") + assertEquals(phones.drop(1).map { it.publicKey }.toSet(), sent.invited.toSet(), "($profile)") + assertTrue(sent.notAdded.isEmpty(), "($profile)") + + assertEquals( + MarmotGroupCreation.FoundingInvite.NothingToDo, + MarmotGroupCreation.finishFoundingInvite(creator.db, creator.chatRepository, session, ceremonyRoom, 2_000L), + "and a second run invites nobody ($profile)", + ) + + phones.drop(1).forEach { welcome(from = creator, to = it, roomId = roomId) } + val founders = phones.map { it.publicKey }.toSet() + phones.forEach { phone -> + val room = assertNotNull(phone.db.chatRoomDao().findChatRoomById(roomId), "$phone has no room ($profile)") + val group = assertNotNull(room.chatRoom.toMlsGroup(), "$phone holds no group ($profile)") + assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)") + assertTrue(group.isLocalAdmin(), "$phone is not an admin ($profile)") + } + } finally { + phones.forEach { it.close() } + } + } + } + + /** Past epoch 0 a founder without a leaf may be one who left; that is not this step's to undo. */ + @Test + fun `a room past its founding invites nobody`() = onEveryProfile { profile, phones -> + val creator = phones.first() + val (session, ceremonyRoom) = ceremonyOn(creator, phones, foundingThresholdPublicKey) + + assertEquals( + MarmotGroupCreation.FoundingInvite.NothingToDo, + MarmotGroupCreation.finishFoundingInvite(creator.db, creator.chatRepository, session, ceremonyRoom, 2_000L), + "($profile)", + ) + } + // ---- The ceremony ------------------------------------------------------------ @Test From baf63b8d7aaa1ee075905ae13d74841e0a2ae096 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:18:00 +0200 Subject: [PATCH 7/9] feat: the room's details say who administers it, and whether the founders do (robust-group-admins, Phase 5) The member list labels admins, from the flags AdminFlags keeps. Two cards on the error container, under the signing key and the parent: founding members the room's policy does not list as admins, with "Make them admins" for an admin of a current-profile room; and founding members the founding invite never reached, with "Invite them" on the device that holds the room at epoch 0. Founders are named through their profiles, since an uninvited one is not in the room to read a row off. A robust group's NIP-17 room has no admins of its own, so its details link to the admin room its ceremony made (ChatRepository.adminRoomOf), saying every member is an admin there. Strings in the catalogue, sentence case; colours from the error container roles; spacing from the scale; the actions guard a second tap. m3Audit: all budgets met. jvmTest 1249/1249, compileDebugKotlinAndroid. Not looked at in a running app. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 12 ++ .../repository/DatabaseChatRepository.kt | 14 ++ .../giza/compose/repository/ChatRepository.kt | 10 + .../ui/composable/ChatRoomDetailScreen.kt | 184 +++++++++++++++++- .../ui/view/model/ChatRoomDetailViewModel.kt | 50 ++++- .../ui/view/state/ChatRoomDetailUIState.kt | 20 ++ 6 files changed, 281 insertions(+), 9 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 733a0b2c..79276c4a 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -479,4 +479,16 @@ Waiting on %1$s since %2$s. If they have stopped answering, any member can abandon the ceremony. No key is made, and the group can start again. Open the room + Admin + Founding members aren't admins + %1$s took part in the key ceremony that made this group, but this room doesn't list them as admins. + Make them admins + Asked the group to make them admins + Not every founding member was invited + %1$s took part in the key ceremony that made this group, but the invitation to this room never went out. + Invite them + Invited them to the room + Some of them haven't published a key package yet + Admin room + Every member of this group is an admin there. 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 75987d93..0b28ef4f 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 @@ -8,6 +8,7 @@ import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair 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 import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate @@ -114,6 +115,19 @@ class DatabaseChatRepository( emptySet() } + override suspend fun adminRoomOf(chatRoomId: String): String? = try { + // The room's own ceremony, not a subgroup's it hosted: a subgroup's key + // makes the subgroup's room, which is not this group's admin room. + database.dkgSessionDao().getLatestSessionFor(chatRoomId, parentChatRoomId = null) + ?.takeIf { it.stage == DkgRitualStage.COMPLETE } + ?.thresholdPublicKey + ?.let { SharedKeyDerivation.marmotGroupId(it) } + ?.takeIf { it != chatRoomId && database.chatRoomDao().findChatRoomById(it) != null } + } catch (e: Throwable) { + logger.e("Error finding the admin room of $chatRoomId", e) + null + } + override suspend fun followThroughCeremonies(keyPair: KeyPair) = CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair) 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 20d1eee1..894c444e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -237,6 +237,14 @@ interface ChatRepository { /** The founders [localChatRoom]'s founding invite never reached; empty when there are none to reach. */ suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set + /** + * The admin room [chatRoomId]'s own key ceremony made, if this device holds + * it: where the members of a robust group's NIP-17 room are admins. Null for + * a room with no finished ceremony of its own, and for one whose admin room + * this device does not hold. + */ + suspend fun adminRoomOf(chatRoomId: String): String? + /** * Takes every key ceremony [keyPair] coordinated from a key to a working room, * until cancelled: asks the group to sign its key state (a subgroup's parent to @@ -489,6 +497,8 @@ interface ChatRepository { override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = emptySet() + override suspend fun adminRoomOf(chatRoomId: String): String? = null + override suspend fun sendChatMessage( text: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 2b3ac801..6e7340ad 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -14,6 +14,9 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons +import mobi.giza.compose.managers.MarmotGroupCreation +import androidx.compose.material3.CardDefaults +import androidx.compose.material.icons.filled.AdminPanelSettings import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.AccountTree import androidx.compose.material.icons.filled.Autorenew @@ -81,6 +84,18 @@ import mobi.giza.compose.ui.view.model.ChatRoomDetailViewModel import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.resources.every_member_of_this_group_administers_it_there +import mobi.giza.compose.resources.admin_room +import mobi.giza.compose.resources.founding_members_have_no_key_package +import mobi.giza.compose.resources.founding_members_invited +import mobi.giza.compose.resources.invite_them +import mobi.giza.compose.resources.s_took_part_in_the_key_ceremony_but_were_not_invited +import mobi.giza.compose.resources.not_every_founding_member_was_invited +import mobi.giza.compose.resources.founding_members_made_admins_requested +import mobi.giza.compose.resources.make_them_admins +import mobi.giza.compose.resources.s_took_part_in_the_key_ceremony_but_are_not_admins +import mobi.giza.compose.resources.founding_members_are_not_admins +import mobi.giza.compose.resources.admin import mobi.giza.compose.resources.run_by_members import mobi.giza.compose.resources.parent_group import mobi.giza.compose.resources.a_subgroup @@ -185,6 +200,9 @@ fun ChatRoomDetailScreen( val removalRequested = stringResource(Res.string.member_removal_requested) val rotationRequested = stringResource(Res.string.share_rotation_requested) val sharesActionSent = stringResource(Res.string.shares_action_sent) + val madeAdminsRequested = stringResource(Res.string.founding_members_made_admins_requested) + val foundersInvited = stringResource(Res.string.founding_members_invited) + val foundersHaveNoKeyPackage = stringResource(Res.string.founding_members_have_no_key_package) // Offered after removing a member who still holds a share of the room's key: // the removal took them out of the room, not out of the key @@ -347,6 +365,94 @@ fun ChatRoomDetailScreen( } } + // The founding members, where the room is not as the + // ceremony that made its key left it: founders its + // policy does not list as admins, or founders its + // founding invite never reached. Under the key and the + // parent, because it is about the same thing -- who the + // group that made this room is. docs/robust-group-admins.md, + // Phase 5. + if (chatRoomDetailUIState.missingFoundingAdmins.isNotEmpty()) { + item { + FoundingMembersCard( + title = stringResource(Res.string.founding_members_are_not_admins), + body = stringResource( + Res.string.s_took_part_in_the_key_ceremony_but_are_not_admins, + chatRoomDetailUIState.founderNamesFor(chatRoomDetailUIState.missingFoundingAdmins), + ), + // An admin of a room the app governs: the + // repair is a commit only they can make. + actionLabel = stringResource(Res.string.make_them_admins) + .takeIf { chatRoomDetailUIState.canGovern }, + isActionPending = chatRoomDetailViewModel.isActionPending.value, + onAction = { + chatRoomDetailViewModel.addMissingFoundingAdmins( + localChatRoom = chatRoomDetailUIState.localChatRoom, + missing = chatRoomDetailUIState.missingFoundingAdmins, + ) { failure -> notify(failure ?: madeAdminsRequested) } + }, + ) + } + } + + if (chatRoomDetailUIState.uninvitedFounders.isNotEmpty()) { + item { + FoundingMembersCard( + title = stringResource(Res.string.not_every_founding_member_was_invited), + body = stringResource( + Res.string.s_took_part_in_the_key_ceremony_but_were_not_invited, + chatRoomDetailUIState.founderNamesFor(chatRoomDetailUIState.uninvitedFounders), + ), + actionLabel = stringResource(Res.string.invite_them), + isActionPending = chatRoomDetailViewModel.isActionPending.value, + onAction = { + chatRoomDetailViewModel.inviteFounders(chatRoomId) { invite -> + notify( + when (invite) { + is MarmotGroupCreation.FoundingInvite.BlockedOn -> foundersHaveNoKeyPackage + is MarmotGroupCreation.FoundingInvite.Failed -> invite.reason + else -> foundersInvited + } + ) + } + }, + ) + } + } + + // A robust group's NIP-17 room has no admins of its own; + // its members are admins of the room its key made. + chatRoomDetailUIState.adminRoomId?.let { adminRoomId -> + item { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = { + onNavigateToRoute.invoke( + ChatRoomDetailRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = adminRoomId, + relayHint = relayHint + ) + ) + } + ) { + ListItem( + leadingContent = { + Icon(Icons.Default.AdminPanelSettings, contentDescription = Decorative) + }, + trailingContent = { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + }, + headlineContent = { + Text(text = stringResource(Res.string.admin_room)) + }, + supportingContent = { + Text(text = stringResource(Res.string.every_member_of_this_group_administers_it_there)) + } + ) + } + } + } item { chatRoomDetailUIState.localChatRoom.chatRoom.description?.let { Text( @@ -729,10 +835,21 @@ fun ChatRoomDetailScreen( ) }, supportingContent = { - localParticipant.profile?.about?.let { - Text( - text = it - ) + Column { + // From the group's admin policy, through + // `AdminFlags` -- docs/robust-group-admins.md. + if (localParticipant.participant.adminAt != null) { + Text( + text = stringResource(Res.string.admin), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + localParticipant.profile?.about?.let { + Text( + text = it + ) + } } } @@ -1329,4 +1446,61 @@ private fun ChatRoomMessagingScreenPreview() { ) } } -} \ No newline at end of file +} + +/** + * Something about this room's founding members that is not as the ceremony + * left it -- founders it does not list as admins, or founders its invite never + * reached -- and, where this device can, the one action that repairs it. + * + * On the error container: the room works, but not as the group that made it + * agreed, and that is worth more than a supporting line. docs/robust-group-admins.md, + * Phase 5. + */ +@Composable +private fun FoundingMembersCard( + title: String, + body: String, + actionLabel: String?, + isActionPending: Boolean, + onAction: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + contentColor = MaterialTheme.colorScheme.onErrorContainer, + ) + ) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Icon(Icons.Default.AdminPanelSettings, contentDescription = Decorative) + Text(text = title, style = MaterialTheme.typography.titleSmall) + } + + Text(text = body, style = MaterialTheme.typography.bodyMedium) + + actionLabel?.let { label -> + TextButton( + onClick = onAction, + enabled = !isActionPending, + colors = ButtonDefaults.textButtonColors( + contentColor = MaterialTheme.colorScheme.onErrorContainer + ), + ) { + Text(label) + } + } + } + } +} + +/** The founders [publicKeys] names, as the screen calls them, in a stable order. */ +private fun ChatRoomDetailUIState.Loaded.founderNamesFor(publicKeys: Set): String = + publicKeys.map { founderNames[it] ?: it }.sorted().joinToString(", ") diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 83a7739b..a857793a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -19,6 +19,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch import mobi.giza.compose.managers.FoundingAdmins +import mobi.giza.compose.managers.MarmotGroupCreation import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.managers.WalletRefusal @@ -98,6 +99,14 @@ class ChatRoomDetailViewModel( ?.let { Event.fromJsonOrNull(it) } ?.let(WalletRefusal::isGuarded) == true + // The founding members, against what the ceremony that made the + // room's key said: who the policy leaves out, and who the founding + // invite never reached. docs/robust-group-admins.md, Phases 3 and 4. + val missingFoundingAdmins = (chatRepository.foundingAdmins(chatRoomId) as? FoundingAdmins.Check.Missing) + ?.publicKeys + .orEmpty() + val uninvitedFounders = chatRepository.uninvitedFounders(localChatRoom) + ChatRoomDetailUIState.Loaded( localChatRoom = localChatRoom, groupKeyState = groupKeyState, @@ -109,9 +118,13 @@ class ChatRoomDetailViewModel( canGovern = canGovern, isDisbanded = isDisbanded, shares = chatRepository.sharesSummary(localChatRoom), - missingFoundingAdmins = (chatRepository.foundingAdmins(chatRoomId) as? FoundingAdmins.Check.Missing) - ?.publicKeys - .orEmpty(), + missingFoundingAdmins = missingFoundingAdmins, + uninvitedFounders = uninvitedFounders, + founderNames = (missingFoundingAdmins + uninvitedFounders).associateWith { publicKey -> + nostrRepository.getProfileWithPublicKey(publicKey)?.humanReadableNameOrPubkey() + ?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH) + }, + adminRoomId = if (localChatRoom.chatRoom.mlsGroupState == null) chatRepository.adminRoomOf(chatRoomId) else null, ) } } @@ -146,10 +159,36 @@ class ChatRoomDetailViewModel( * warning stays until then. docs/robust-group-admins.md, Phase 3. */ fun addMissingFoundingAdmins(localChatRoom: LocalChatRoom, missing: Set, onDone: (String?) -> Unit = {}) { + if (isActionPending.value) return + isActionPending.value = true viewModelScope.launch(Dispatchers.IO) { val failure = runCatching { chatRepository.addAdmins(localChatRoom, missing) }.exceptionOrNull() initiateChatRoomDetail() - viewModelScope.launch(Dispatchers.Main) { onDone(failure?.message) } + viewModelScope.launch(Dispatchers.Main) { + isActionPending.value = false + onDone(failure?.message) + } + } + } + + /** + * Finishes the room's founding invite, and reloads the screen. Reports null + * when it went out, or why not -- naming the founders still without a key + * package, since only they can publish one. docs/robust-group-admins.md, + * Phase 4. + */ + fun inviteFounders(chatRoomId: String, onDone: (MarmotGroupCreation.FoundingInvite) -> Unit = {}) { + // Waits on relays for key packages, so a second tap would ask twice. + if (isActionPending.value) return + isActionPending.value = true + viewModelScope.launch(Dispatchers.IO) { + val invite = runCatching { chatRepository.finishFoundingInvite(chatRoomId) } + .getOrElse { MarmotGroupCreation.FoundingInvite.Failed(it.message ?: "Couldn't invite them. Please try again.") } + initiateChatRoomDetail() + viewModelScope.launch(Dispatchers.Main) { + isActionPending.value = false + onDone(invite) + } } } @@ -288,6 +327,9 @@ class ChatRoomDetailViewModel( companion object { private const val TAG = "ChatRoomDetailViewModel" + /** Enough of a key to tell two founders apart when no profile is stored. */ + private const val SHORTENED_PUBLIC_KEY_LENGTH = 12 + fun factory( activeUserPublicKey: HexKey, chatRoomId: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 20b85009..a7fe3b32 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -91,6 +91,26 @@ sealed interface ChatRoomDetailUIState { * `FoundingAdmins.check`; docs/robust-group-admins.md, Phase 3. */ val missingFoundingAdmins: Set = emptySet(), + /** + * Founding members this room's founding invite never reached -- only ever + * non-empty on the device that made the room, while it is still at epoch 0. + * See `MarmotGroupCreation.uninvitedFounders`; docs/robust-group-admins.md, + * Phase 4. + */ + val uninvitedFounders: Set = emptySet(), + /** + * What to call the founders the two sets above name. They need not be in + * this room -- an uninvited one is not, by definition -- so the room's own + * rows cannot be asked. + */ + val founderNames: Map = emptyMap(), + /** + * The admin room this group's ceremony made, when this is the group's + * NIP-17 room and this device holds it. A NIP-17 room has no admins of its + * own; this is where its members are admins. docs/robust-group-admins.md, + * Phase 5. + */ + val adminRoomId: String? = null, ): ChatRoomDetailUIState data class Error( From 01e33f5a6f25f523e2b128bdc1cd42488c498069 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:21:12 +0200 Subject: [PATCH 8/9] fix: rooms joined before the Welcome wrote flags are caught up at start (robust-group-admins, Phase 6) AdminFlags.reconcileAll runs AdminFlags.reconcile over every room this device holds MLS state for, and the sync start calls it once, through ChatRepository.reconcileAdminFlags, beside the ceremony resume. A room joined before Phase 2 flags nobody on the joiner's device until some commit arrives, and a robust group's admin room may never get one. No stored "done" flag: a room whose rows already agree is a read and no write, so a second start costs one decode per room. A room that will not decode is logged and passed over. RobustGroupAdminsJvmTest: a joiner's cleared flags are restored on both profiles, and a second pass changes nothing. jvmTest 1250/1250, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../repository/DatabaseChatRepository.kt | 3 +++ .../mobi/giza/compose/managers/AdminFlags.kt | 27 +++++++++++++++++++ .../giza/compose/repository/ChatRepository.kt | 9 +++++++ .../ui/view/model/SynchronizationViewModel.kt | 7 +++++ .../managers/RobustGroupAdminsJvmTest.kt | 16 +++++++++++ 5 files changed, 62 insertions(+) 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 0b28ef4f..55c42504 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 @@ -7,6 +7,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import mobi.giza.compose.managers.AdminFlags import mobi.giza.compose.managers.FoundingAdmins import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.CeremonyFollowThrough @@ -128,6 +129,8 @@ class DatabaseChatRepository( null } + override suspend fun reconcileAdminFlags(): Int = AdminFlags.reconcileAll(database) + override suspend fun followThroughCeremonies(keyPair: KeyPair) = CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt index cb121030..85a9156c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt @@ -56,4 +56,31 @@ object AdminFlags { } return changed.size } + + /** + * [reconcile] for every room this device holds MLS state for and is still in. + * + * Run once per start, for the rooms made before the Welcome wrote any flags: + * a joiner's rows there flag nobody until some commit arrives, and in a + * robust group's admin room one may never arrive. No stored "done" flag -- a + * room whose rows already agree is a read and no write, so a second run costs + * one decode per room and a preference would only be one more thing to keep + * right. docs/robust-group-admins.md, Phase 6. + * + * One room that will not decode is logged and passed over, not fatal to the + * rest. + * + * @return how many rows changed, across every room. + */ + suspend fun reconcileAll(database: GizaDatabase): Int = + database.chatRoomDao().getChatRoomIdsWithMlsState().sumOf { chatRoomId -> + runCatching { + val group = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.toMlsGroup() + ?: return@runCatching 0 + reconcile(database, chatRoomId, group) + }.getOrElse { + logger.e("Could not bring $chatRoomId's admin flags in line", it) + 0 + } + } } 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 894c444e..df13f39f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -245,6 +245,13 @@ interface ChatRepository { */ suspend fun adminRoomOf(chatRoomId: String): String? + /** + * Brings every Marmot room's admin flags in line with its group's policy, for + * the rooms joined before the Welcome wrote any. Once per start. See + * `AdminFlags.reconcileAll` and docs/robust-group-admins.md, Phase 6. + */ + suspend fun reconcileAdminFlags(): Int + /** * Takes every key ceremony [keyPair] coordinated from a key to a working room, * until cancelled: asks the group to sign its key state (a subgroup's parent to @@ -499,6 +506,8 @@ interface ChatRepository { override suspend fun adminRoomOf(chatRoomId: String): String? = null + override suspend fun reconcileAdminFlags(): Int = 0 + override suspend fun sendChatMessage( text: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index c292ec61..8b4c5ac3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -246,6 +246,13 @@ class SynchronizationViewModel( // was waiting for. docs/automatic-key-ceremony.md, Phase 3. runCatching { nostrRepository.resumeRunningCeremonies(keyPair) } .onFailure { logger.e("Could not resume running key ceremonies", it) } + // The rooms joined before the Welcome wrote admin flags + // flag nobody until some commit arrives, and a robust + // group's admin room may never get one. Caught up here, + // once a start; a room already right is read, not + // written. docs/robust-group-admins.md, Phase 6. + runCatching { chatRepository.reconcileAdminFlags() } + .onFailure { logger.e("Could not bring admin flags in line", it) } launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) } // Runs until cancelled rather than draining a queue, but it // belongs here for the same reason the pumps do: it needs the 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 cd660d8c..99d6a32b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -227,6 +227,22 @@ class RobustGroupAdminsJvmTest { } } + /** + * A room joined before Phase 2, whose joiner's rows flag nobody, is caught up + * at the next start, once. docs/robust-group-admins.md, Phase 6. + */ + @Test + fun `a room joined before the Welcome wrote flags is caught up at start`() = onEveryProfile { profile, phones -> + val founders = phones.map { it.publicKey }.toSet() + val joiner = phones.last() + joiner.db.participantDao().upsert(joiner.room().localParticipants.map { it.participant.copy(adminAt = null) }) + assertTrue(joiner.flaggedAdmins().isEmpty(), "the fixture did not clear the flags ($profile)") + + assertEquals(founders.size, AdminFlags.reconcileAll(joiner.db), "($profile)") + assertEquals(founders, joiner.flaggedAdmins(), "($profile)") + assertEquals(0, AdminFlags.reconcileAll(joiner.db), "and a second start changes nothing ($profile)") + } + // ---- The founding invite: docs/robust-group-admins.md, Phase 4 ------------- private val ceremonyRoomId = "ce1e".repeat(16) From a95d6db118e5563ac9f8c87972647c06ecc492ad Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:21:12 +0200 Subject: [PATCH 9/9] docs: every founding member of a robust group is its admin, built (robust-group-admins, Phase 7) The plan is marked built, with a table of the nine places the build chose differently -- among them that Phase 4 acts on a room at epoch 0 rather than on rows that were never written, since rows are hard-deleted, and that it also fixed the current-profile routing bug Phase 0 found. The README row says built; automatic-key-ceremony.md gains step 4 and subgroups.md the repository taking the ceremony instead of a list. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/automatic-key-ceremony.md | 5 +++++ docs/robust-group-admins.md | 22 +++++++++++++++++++--- docs/subgroups.md | 6 ++++++ 4 files changed, 31 insertions(+), 4 deletions(-) diff --git a/docs/README.md b/docs/README.md index a3f287de..b4e38d65 100644 --- a/docs/README.md +++ b/docs/README.md @@ -36,7 +36,7 @@ the [retired](./retired/) notes now. | [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, how often this app persists a group once a sent message no longer rewrites it, and the schema change that followed, opened from the version the app ships | | [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase | | [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu | -| [robust-group-admins.md](./robust-group-admins.md) | making every founding member of a robust group an admin of its room, on every device -- phased and not built. Covers why the ceremony's participants are the founding set, the Welcome that flags no admins, the joiner's check against the ceremony it took part in, and finishing an invite that partly failed | +| [robust-group-admins.md](./robust-group-admins.md) | making every founding member of a robust group an admin of its room, on every device -- phased and built. Covers why the ceremony's participants are the founding set, the Welcome that flags no admins, the joiner's check against the ceremony it took part in, and finishing an invite that partly failed | Start with the ceremony if you are new to this area; the Marmot notes all assume it. Read the skipped-keys note before debugging any "the other device never got it" diff --git a/docs/automatic-key-ceremony.md b/docs/automatic-key-ceremony.md index de05aa02..6a86e310 100644 --- a/docs/automatic-key-ceremony.md +++ b/docs/automatic-key-ceremony.md @@ -388,6 +388,11 @@ on a COMPLETE ceremony this device coordinated: room does not exist -> create it ``` +> **Since [robust-group-admins.md](./robust-group-admins.md), Phase 4:** a fifth line, after +> the room exists -- a room still at epoch 0 without its founders, whose founding invite never +> went out, has it finished. And the room's admins are no longer the caller's to pass: the +> repository takes the ceremony and reads them off it. + - **What it calls:** the code behind `DkgRitualViewModel.proposeBirthCertificate`, `proposeKeyState` and `createAdminGroup`. That code moves from the view model into the manager (and `DkgRepository`), along with each one's "already asked" diff --git a/docs/robust-group-admins.md b/docs/robust-group-admins.md index 3abb6483..0ba663cd 100644 --- a/docs/robust-group-admins.md +++ b/docs/robust-group-admins.md @@ -1,11 +1,27 @@ # Every founding member of a robust group is its admin A robust group promises, on the screen that makes it, that "everyone administers the -group together". This note is the plan that makes the promise true on every device from +group together". This note is the plan that made the promise true on every device from the moment the group exists: what "founding member" means, the four places the promise -breaks today, and seven phases that close them. +broke before, and the eight phases that closed them. -**Planned, not built.** Written against `fc437d05`. +**Built**, phases 0-7, one commit each. The phases below are kept as written, +because they are the reasoning; where the build chose differently the table says +so, and it did nine times worth reading: + +| what the plan said | what it turned out to be | +|---|---| +| a new `ChillDkgRitualManager.foundingMembersOf` | never built. `participantsOf` already was that function, fallback and all; Phase 1 made `MarmotGroupCreation.createFor` its one caller on the way to a room, and took the list off `ChatRepository.createMarmotGroup` altogether | +| Phase 2's `stampAdmins` replaced by `AdminFlags.reconcile` with the creation's list | with the group's policy instead. Reading the list back would have kept two sources for one flag, which is the drift D2 is about | +| Phase 2's Welcome test in `WelcomeBundleMatchJvmTest` | in `RobustGroupAdminsJvmTest`, where Phase 0 already delivers real gift-wrapped Welcomes between three app devices. The bundle test is about which key package a Welcome names, not what it leaves behind | +| Phase 3 reports `Differs(missing, unexpected)` and offers removing unexpected admins | `Missing` only. Removing an admin is out of scope, so an admin the ceremony did not have is not this plan's to act on | +| Phase 3's repair on every room | on the current profile only. The app makes no governance commit on a legacy room -- no removal, no disband -- so a legacy room gets the warning and the transcript line and not the button | +| Phase 4 invites founders "who have never had a row in the room, not even a soft-deleted one" | founders without a leaf in a room still at **epoch 0**. Rows are hard-deleted when a member leaves, so "never had a row" cannot be told from "left"; epoch 0 can, because leaving is a commit and the founding invite is the commit that ends epoch 0 | +| Phase 4 is about `notAdded` | it also fixed what Phase 0 found: on the current profile `MarmotGroupCreation` invited the founders through a room read before its routing id was recorded, so the engine adopted a second copy of the group under the room id, and every later invite into that room took the founding path -- no commit, and nobody already in the room told | +| Phase 4's "Invite again" for any other active admin | only on the device holding the room at epoch 0, which is its creator's: nobody else holds the room until the invite reaches them. The coordinator's device does it on its own as step 4 | +| Phase 6 reconciles behind a stored "reconciled" preference | on every start, with no flag. `AdminFlags.reconcile` writes nothing when the rows already agree, so running it again costs one decode per room and a preference would only be a second thing to keep right | + +Written against `fc437d05`. Read [shared-key-ceremony.md](./shared-key-ceremony.md) and [ceremony-creation.md](./ceremony-creation.md) first. diff --git a/docs/subgroups.md b/docs/subgroups.md index 88f129d8..6055b00c 100644 --- a/docs/subgroups.md +++ b/docs/subgroups.md @@ -671,6 +671,12 @@ re-deriving: - **`adopt` before the members are added**, because filing the key state is local and certain and adding members is neither. +> **Since [robust-group-admins.md](./robust-group-admins.md):** the repository's +> `createMarmotGroup` takes the ceremony and the room it ran in instead of +> `adminPublicKeys`, and `MarmotGroupCreation.createFor` reads the admins, the id and the name +> off the ceremony. A subgroup's founding admins are its ceremony's participants, as a +> group's are, so the same rule makes both. + `parentChatRoomId` is the one genuinely new parameter, written onto the `ChatRoom` row. The subgroup's description carries the path through `SharedKeyDerivation.describe`, exactly as the admin room's does — MIP-01 has no