diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEvent.kt new file mode 100644 index 00000000..f2fa44f5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEvent.kt @@ -0,0 +1,176 @@ +package mobi.giza.compose.nostr.frost + +import com.vitorpamplona.crypto.sha2.sha256 +import com.vitorpamplona.marmot.appComponents.AdminPolicyV1 +import com.vitorpamplona.mls.group.GroupView +import com.vitorpamplona.mls.group.PendingProposal +import com.vitorpamplona.mls.messages.Proposal +import com.vitorpamplona.mls.tree.Credential +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag +import mobi.giza.compose.extensions.toHex + +/** + * What a keyed room's quorum signs before anything about the room may change: one + * statement, naming one epoch, saying exactly what the commit made at that epoch + * will do. docs/member-admin-promotion.md, R2 and Phase 3. + * + * ``` + * ["d", ] + * ["epoch", ] -- the epoch the commit is built at + * ["add", , ] -- one per member added + * ["remove", ] -- one per member removed + * ["admins", , ...] -- the whole admin list after, when it changes + * ["component", , | "remove"] -- any other GroupContext component + * ["proposer", ] + * ``` + * + * Readable on its face, because a member approving it is approving those lines: + * "make Bob an admin", not a hash of a commit. Bound to one epoch, because a + * statement good at any epoch could be replayed -- a demotion signed once and + * applied could be applied again after the member was promoted back. And the + * whole change, not a summary of it: [authorises] holds a commit to *exactly* + * these lines, so an extra Add folded in beside a signed promotion is refused. + * + * Signed by the room itself. A keyed room's id is the group's key walked to the + * room's path, so the key that must have signed is the room's id and nothing has + * to be looked up -- [GroupKeyStateEvent.isSignedByRoom]. + * + * Kind 30370: past the last of the wallet kinds Giza retired (30350-30366, + * `RetiredKinds`). Like every kind in the signing family it only ever travels + * inside an encryption a relay cannot open. + */ +object GovernanceStatementEvent { + val KIND: Kind = 30370 + + const val EPOCH_TAG = "epoch" + const val ADD_TAG = "add" + const val REMOVE_TAG = "remove" + const val ADMINS_TAG = "admins" + const val COMPONENT_TAG = "component" + const val PROPOSER_TAG = "proposer" + const val REMOVED = "remove" + + fun isGovernanceStatementKind(kind: Kind): Boolean = kind == KIND + + /** The tags of a statement that [change] be made to [chatRoomId] at [epoch]. */ + fun assembleTags(chatRoomId: HexKey, epoch: Long, change: GovernanceChange, proposer: HexKey): Array> = + arrayOf(DTag.assemble(chatRoomId), arrayOf(EPOCH_TAG, epoch.toString())) + + change.adds.sortedBy { it.account }.map { arrayOf(ADD_TAG, it.account, it.keyPackageRef) } + + change.removes.sorted().map { arrayOf(REMOVE_TAG, it) } + + listOfNotNull(change.admins?.let { arrayOf(ADMINS_TAG, *it.sorted().toTypedArray()) }) + + change.components.toSortedMap().map { (id, digest) -> arrayOf(COMPONENT_TAG, id.toString(), digest) } + + arrayOf(arrayOf(PROPOSER_TAG, proposer)) + + /** A statement as its tags say it, or null when they do not make one. */ + fun parse(event: Event): GovernanceStatement? = runCatching { + if (event.kind != KIND) return null + val tags = event.tags + val room = tags.firstOrNull { it.size >= 2 && it[0] == "d" }?.get(1) ?: return null + val epoch = tags.single { it.size == 2 && it[0] == EPOCH_TAG }[1].toLong() + val adminTags = tags.filter { it.isNotEmpty() && it[0] == ADMINS_TAG } + if (adminTags.size > 1) return null + GovernanceStatement( + chatRoomId = room, + epoch = epoch, + proposer = tags.firstOrNull { it.size >= 2 && it[0] == PROPOSER_TAG }?.get(1), + change = GovernanceChange( + adds = tags.filter { it.isNotEmpty() && it[0] == ADD_TAG }.map { AddedMember(it[1], it[2]) }.toSet(), + removes = tags.filter { it.isNotEmpty() && it[0] == REMOVE_TAG }.map { it[1] }.toSet(), + admins = adminTags.singleOrNull()?.drop(1)?.toSet(), + components = tags.filter { it.isNotEmpty() && it[0] == COMPONENT_TAG }.associate { it[1].toInt() to it[2] }, + ), + ) + }.getOrNull() + + /** + * Whether [event] is the room's own signature on [change] at [epoch]: its kind, + * the room's signature on it, the room and epoch it names, and a change equal to + * [change] -- nothing more and nothing less. Every input is off the wire, so + * anything malformed is a no. + */ + fun authorises(event: Event, chatRoomId: HexKey, epoch: Long, change: GovernanceChange): Boolean { + val statement = parse(event) ?: return false + return statement.chatRoomId.equals(chatRoomId, ignoreCase = true) && + statement.epoch == epoch && + statement.change == change && + GroupKeyStateEvent.isSignedByRoom(event, chatRoomId) + } +} + +/** A member a commit adds: their account, and the exact KeyPackage that adds them. */ +data class AddedMember(val account: HexKey, val keyPackageRef: HexKey) + +/** A signed statement, read. */ +data class GovernanceStatement( + val chatRoomId: HexKey, + val epoch: Long, + val proposer: HexKey?, + val change: GovernanceChange, +) + +/** + * What a commit does to a room, in a statement's terms: who it adds and removes, + * the admin list it leaves (null when it leaves it alone), and every other + * component it changes, by id and the hash of the new value (or [GovernanceStatementEvent.REMOVED]). + * + * A member's own leave rides along without appearing here; it needs nobody's + * signature (D6), so [of] leaves it out rather than refusing it. + */ +data class GovernanceChange( + val adds: Set = emptySet(), + val removes: Set = emptySet(), + val admins: Set? = null, + val components: Map = emptyMap(), +) { + companion object { + /** + * What [proposals] would do to [group], or null when they do something a + * statement cannot describe -- another member's Update, a GroupContext + * rewrite, a pre-shared key, a re-init -- which is therefore never + * authorised. [proposals] is the commit's whole list, exempt ones included. + */ + fun of(group: GroupView, proposals: List): GovernanceChange? { + val adds = mutableSetOf() + val removes = mutableSetOf() + var admins: Set? = null + val components = mutableMapOf() + for (pending in proposals) { + when (val proposal = pending.proposal) { + is Proposal.SelfRemove -> Unit + is Proposal.Add -> { + val account = (proposal.keyPackage.leafNode.credential as? Credential.Basic)?.identity?.toHexKey() ?: return null + adds += AddedMember(account, proposal.keyPackage.reference().toHex()) + } + is Proposal.Remove -> removes += group.memberIdentityHex(proposal.removedLeafIndex) ?: return null + is Proposal.AppDataUpdate -> { + val operation = proposal.operation + if (proposal.componentId == AdminPolicyV1.COMPONENT_ID) { + if (operation !is Proposal.AppDataUpdate.Operation.Update) return null + admins = AdminPolicyV1.decode(operation.data).adminHexKeys.toSet() + } else { + components[proposal.componentId] = when (operation) { + is Proposal.AppDataUpdate.Operation.Update -> sha256(operation.data).toHex() + Proposal.AppDataUpdate.Operation.Remove -> GovernanceStatementEvent.REMOVED + } + } + } + else -> return null + } + } + return GovernanceChange(adds, removes, admins, components) + } + + /** + * Whether a commit needs nobody's signature (D6): one made only of members' + * own SelfRemoves, or a committer's own key update with no proposals at all. + * MIP-03 lets any member make exactly these, and neither changes who governs + * the room or who is in it beyond the leaver. + */ + fun isExempt(proposals: List): Boolean = + proposals.all { it.proposal is Proposal.SelfRemove } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt index 8e8c39de..7b668a88 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -5,6 +5,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.WalletRefusal import mobi.giza.compose.nostr.RetiredKinds +import mobi.giza.compose.nostr.frost.GovernanceStatementEvent import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent @@ -69,6 +70,24 @@ object ProposedEvent { ).joinToString(" · ") ) + // A change to the room itself, which no single admin may make: who is in + // it and who governs it, said in names, because a member approving it is + // approving those lines and not a hash. docs/member-admin-promotion.md, + // Phase 3. + GovernanceStatementEvent.KIND -> GovernanceStatementEvent.parse(event)?.let { statement -> + val name = { key: HexKey -> nameOf(key) ?: key.take(8) } + val change = statement.change + Summary( + label = "A change to who is in this group", + detail = listOfNotNull( + change.adds.takeIf { it.isNotEmpty() }?.joinToString(prefix = "Adds ") { name(it.account) }, + change.removes.takeIf { it.isNotEmpty() }?.joinToString(prefix = "Removes ") { name(it) }, + change.admins?.joinToString(prefix = "Admins afterwards: ") { name(it) }, + "Changes its settings".takeIf { change.components.isNotEmpty() }, + ).joinToString(" · ") + ) + } ?: Summary(label = "A change to this group that cannot be read", detail = "") + // A Bennu wallet's: declined on arrival, and said as what it is rather than // as a number. docs/giza-wallet-removal.md. in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> WALLET diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEventTest.kt new file mode 100644 index 00000000..4bcbcb0c --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEventTest.kt @@ -0,0 +1,160 @@ +package mobi.giza.compose.nostr.frost + +import com.vitorpamplona.marmot.appComponents.AdminPolicyV1 +import com.vitorpamplona.marmot.appComponents.CurrentProfileGroupFactory +import com.vitorpamplona.mls.group.GroupView +import com.vitorpamplona.mls.group.PendingProposal +import com.vitorpamplona.mls.messages.Proposal +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest +import mobi.giza.compose.extensions.toHex + +/** + * The statement a keyed room's quorum signs before its commit, and the one + * function that holds a commit to it. docs/member-admin-promotion.md, Phase 3. + */ +class GovernanceStatementEventTest { + + private val room = KeyPair() + private val roomId = room.pubKey.toHexKey() + private val alice = "a1".repeat(32) + private val bob = "b2".repeat(32) + private val carol = "c3".repeat(32) + private val epoch = 7L + + /** A tree of Alice, Bob and Carol at leaves 0, 1 and 2. */ + private val group = GroupView( + extensions = emptyList(), + leafCount = 3, + myLeafIndex = 0, + identityAt = { listOf(alice, bob, carol).getOrNull(it) }, + capabilitiesAt = { null }, + ) + + private fun pending(proposal: Proposal, from: Int = 0) = PendingProposal(proposal, senderLeafIndex = from) + + private fun adminsUpdate(vararg admins: String) = Proposal.AppDataUpdate( + AdminPolicyV1.COMPONENT_ID, + Proposal.AppDataUpdate.Operation.Update(AdminPolicyV1.ofHex(admins.toList()).encode()), + ) + + private fun statement(change: GovernanceChange, at: Long = epoch, signer: KeyPair = room, about: String = roomId): Event = + NostrSignerSync(signer).signNormal( + createdAt = 1_700_000_000, + kind = GovernanceStatementEvent.KIND, + tags = GovernanceStatementEvent.assembleTags(about, at, change, proposer = alice), + content = "", + ) + + @Test + fun `a statement reads back as the change it was written from`() { + val change = GovernanceChange( + adds = setOf(AddedMember(carol, "ff".repeat(32))), + removes = setOf(bob), + admins = setOf(alice, carol), + components = mapOf(0x800c to "ee".repeat(32)), + ) + + val read = assertNotNull(GovernanceStatementEvent.parse(statement(change))) + + assertEquals(GovernanceStatement(roomId, epoch, alice, change), read) + } + + @Test + fun `a promotion commit is exactly what its statement says`() { + val proposals = listOf(pending(adminsUpdate(alice, bob, carol))) + val change = assertNotNull(GovernanceChange.of(group, proposals)) + + assertEquals(GovernanceChange(admins = setOf(alice, bob, carol)), change) + assertTrue(GovernanceStatementEvent.authorises(statement(change), roomId, epoch, change)) + } + + @Test + fun `a removal names the account, not the leaf`() { + val change = assertNotNull(GovernanceChange.of(group, listOf(pending(Proposal.Remove(2)), pending(adminsUpdate(alice, bob))))) + + assertEquals(GovernanceChange(removes = setOf(carol), admins = setOf(alice, bob)), change) + } + + @Test + fun `an add is pinned to the exact key package`() = runTest { + val dave = KeyPair() + val keyPackage = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(dave)).keyPackage + val change = assertNotNull(GovernanceChange.of(group, listOf(pending(Proposal.Add(keyPackage))))) + + assertEquals(setOf(AddedMember(dave.pubKey.toHexKey(), keyPackage.reference().toHex())), change.adds) + + // Another of Dave's packages is another add, and the statement does not cover it. + val other = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(dave)).keyPackage + val otherChange = assertNotNull(GovernanceChange.of(group, listOf(pending(Proposal.Add(other))))) + assertFalse(GovernanceStatementEvent.authorises(statement(change), roomId, epoch, otherChange)) + } + + @Test + fun `nothing more and nothing less`() { + val signed = GovernanceChange(admins = setOf(alice, bob, carol)) + val event = statement(signed) + + // An extra removal folded in beside the signed promotion. + assertFalse(GovernanceStatementEvent.authorises(event, roomId, epoch, signed.copy(removes = setOf(bob)))) + // The admin list off by one. + assertFalse(GovernanceStatementEvent.authorises(event, roomId, epoch, signed.copy(admins = setOf(alice, bob)))) + } + + @Test + fun `a statement is good at its own epoch only`() { + val change = GovernanceChange(admins = setOf(alice, bob)) + + assertFalse(GovernanceStatementEvent.authorises(statement(change, at = epoch), roomId, epoch + 1, change)) + } + + @Test + fun `only the room itself can sign for the room`() { + val change = GovernanceChange(admins = setOf(alice, bob)) + + // Signed by one member's own key. + assertFalse(GovernanceStatementEvent.authorises(statement(change, signer = KeyPair()), roomId, epoch, change)) + // Signed by another room, about this one. + val otherRoom = KeyPair() + assertFalse(GovernanceStatementEvent.authorises(statement(change, signer = otherRoom), roomId, epoch, change)) + // This room's signature, about another room. + assertFalse(GovernanceStatementEvent.authorises(statement(change, about = otherRoom.pubKey.toHexKey()), roomId, epoch, change)) + } + + @Test + fun `a member's own leave needs no signature, and rides along with one that does`() { + val leave = pending(Proposal.SelfRemove(), from = 1) + + assertTrue(GovernanceChange.isExempt(listOf(leave))) + assertTrue(GovernanceChange.isExempt(emptyList()), "a committer's own key update needed a signature") + assertFalse(GovernanceChange.isExempt(listOf(leave, pending(adminsUpdate(alice))))) + assertEquals(GovernanceChange(admins = setOf(alice)), GovernanceChange.of(group, listOf(leave, pending(adminsUpdate(alice))))) + } + + @Test + fun `a change a statement cannot describe is never authorised`() { + assertNull(GovernanceChange.of(group, listOf(pending(Proposal.GroupContextExtensions(emptyList()))))) + } + + @Test + fun `malformed tags make no statement`() { + val event = NostrSignerSync(room).signNormal( + createdAt = 1_700_000_000, + kind = GovernanceStatementEvent.KIND, + tags = arrayOf(arrayOf("d", roomId), arrayOf("epoch", "seven")), + content = "", + ) + + assertNull(GovernanceStatementEvent.parse(event)) + } +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt index 24920847..ab6ff389 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt @@ -2,6 +2,8 @@ package mobi.giza.compose.text import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.ByteVector32 +import mobi.giza.compose.nostr.frost.GovernanceChange +import mobi.giza.compose.nostr.frost.GovernanceStatementEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent @@ -51,6 +53,25 @@ class ProposedEventTest { ) } + /** docs/member-admin-promotion.md, Phase 3: a member approves names, not a hash. */ + @Test + fun `a change to the group says who, in names`() { + val bob = "b".repeat(64) + val carol = "c".repeat(64) + val tags = GovernanceStatementEvent.assembleTags( + chatRoomId = "1".repeat(64), + epoch = 4, + change = GovernanceChange(removes = setOf(carol), admins = setOf(bob)), + proposer = bob, + ) + val names = mapOf(bob to "Bob", carol to "Carol") + + val summary = ProposedEvent.summarize(event(GovernanceStatementEvent.KIND, tags = tags), nameOf = names::get) + + assertEquals("A change to who is in this group", summary.label) + assertEquals("Removes Carol · Admins afterwards: Bob", summary.detail) + } + @Test fun `a wallet's kind is said as one, not as a number`() { listOf(30331, 30334, 30337, 30355, 30363).forEach { kind ->