diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 86a0f19a..09c2bf4c 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -781,4 +781,5 @@
Not yet on a relay
Send again
Sent again
+ The group's admins have changed since this key was made. It changes on its own once an admin's device starts a new ceremony, or you can rotate it now.
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt
index d4bc3727..28a6fb70 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt
@@ -22,6 +22,7 @@ import mobi.giza.compose.managers.GroupInboxManager
import mobi.giza.compose.managers.InboxAnnouncements
import mobi.giza.compose.managers.InboxKeyRitualManager
import mobi.giza.compose.managers.InboxReplies
+import mobi.giza.compose.managers.InboxRotation
import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents
import mobi.giza.compose.repository.GroupInboxRepository
@@ -83,6 +84,7 @@ class DatabaseGroupInboxRepository(
relays = InboxAnnouncements.relaysOf(database, roomId),
setUpRefusal = InboxKeyRitualManager.refusal(database, localChatRoom, userPublicKey),
waitingOn = ceremony?.takeIf { it.isRunning }?.let { waitingOn(it) }.orEmpty(),
+ rotationOwed = InboxRotation.isOwed(database, localChatRoom, userPublicKey),
)
}
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt
index 16f3416a..60c1ddcf 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt
@@ -62,6 +62,7 @@ import mobi.giza.compose.managers.ChillDkgRitualManager
import mobi.giza.compose.managers.FrostSigningManager
import mobi.giza.compose.managers.ShareRefreshManager
import mobi.giza.compose.managers.InboxKeyRitualManager
+import mobi.giza.compose.managers.InboxRotation
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import mobi.giza.compose.identity.Identity
@@ -163,6 +164,10 @@ class DatabaseNostrRepository(
database = database,
userPublicKey = userPublicKey,
nostrPrivateKey = privateKey
+ ) + InboxRotation.pass(
+ database = database,
+ userPublicKey = userPublicKey,
+ nostrPrivateKey = privateKey
)
}
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt
index 6e9bcbc3..63438c11 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt
@@ -58,6 +58,12 @@ object GovernanceFollowThrough {
/** One pass over everything owed. */
suspend fun pass(database: GizaDatabase, keyPair: KeyPair) = mutex.withLock {
rotationsOwed(database).forEach { proposal -> rotateAway(database, keyPair, proposal) }
+ // The group's inbox key, made over admins the room no longer has (docs/group-inbox.md,
+ // D14). After the share rotation above, which its refusal waits on.
+ keyPair.privKey?.let { secret ->
+ runCatching { InboxRotation.pass(database, keyPair.pubKey.toHexKey(), secret) }
+ .onFailure { if (it is CancellationException) throw it; logger.w("An inbox rotation pass failed: ${it.message}") }
+ }
if (!ExperimentalFeatures.shareRefresh) return@withLock
val me = keyPair.pubKey.toHexKey()
val privateKey = keyPair.privKey ?: return@withLock
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt
index d6d94a55..f2e05904 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt
@@ -67,6 +67,9 @@ object InboxKeyRitualManager {
const val ABANDONED = "Abandoned by an admin"
+ /** Why one of two crossing ceremonies ends: the other went on. */
+ const val CROSSED = "Another admin started the same ceremony at the same time, and that one went on"
+
fun deriveHostSecretKey(nostrPrivateKey: ByteArray, chatRoomId: String): PrivateKey =
PrivateKey(Crypto.sha256(HOST_KEY_TAG.encodeToByteArray() + nostrPrivateKey + chatRoomId.hexToByteArray()))
@@ -225,6 +228,13 @@ object InboxKeyRitualManager {
}
val participants = (named + innerEvent.pubKey).distinct().sorted()
+ // A generation this device already finished is not made twice: a late or replayed
+ // proposal for it opens nothing.
+ if (database.inboxKeyDao().getCompletedCeremonies(roomId, userPublicKey).any { it.generation >= generation }) {
+ logger.w("Inbox key proposal ${sessionId.take(8)} is for generation $generation, which this device has; dropping")
+ return null
+ }
+
val base = InboxKeyCeremony(
id = sessionId,
chatRoomId = roomId,
@@ -264,6 +274,19 @@ object InboxKeyRitualManager {
return database.inboxKeyDao().getCeremony(sessionId)
}
+ // Two admins who each started a rotation before hearing the other's: every device keeps
+ // the one whose session id sorts first and ends the other out loud, so all of them end
+ // up in the same ceremony and nobody holds a key the others do not.
+ val crossing = database.inboxKeyDao().getRunningCeremoniesIn(roomId)
+ .filter { it.userPublicKey == userPublicKey && it.id != sessionId }
+ crossing.forEach { other ->
+ val loser = if (other.id < sessionId) mine else other
+ val reason = CROSSED
+ fail(database, loser, reason, loser.coordinatorPublicKey)
+ if (loser.isParticipant()) broadcast(database, localChatRoom, loser, InboxKeyRitualEvents.FAILURE, reason)
+ }
+ if (database.inboxKeyDao().getCeremony(sessionId)?.isRunning != true) return database.inboxKeyDao().getCeremony(sessionId)
+
replayStored(database, localChatRoom, mine)
return database.inboxKeyDao().getCeremony(sessionId)
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRotation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRotation.kt
new file mode 100644
index 00000000..348a44ca
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRotation.kt
@@ -0,0 +1,70 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlinx.coroutines.CancellationException
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.InboxKeyState
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+
+/**
+ * When the group's inbox key has to change because its admins have (docs/group-inbox.md, D14).
+ *
+ * The rule is read off what every admin's device already holds, rather than off the change that
+ * caused it: the key was made by a ceremony over some set of admins, and the room's admin policy
+ * now names another. That covers a removal, a demotion, a step-down and a promotion the same way,
+ * and a change that landed while the app was closed.
+ *
+ * One admin starts it, so the devices do not race: the one whose key sorts first among the
+ * admins now. Nobody is asked -- the group's signature on the admin change was the decision --
+ * and if that admin's device is away, any admin can rotate by hand from the inbox's settings.
+ * It waits for whatever share rotation the same change owes ([InboxKeyRitualManager.refusal]
+ * reads the same hold), so the two run in turn.
+ */
+object InboxRotation {
+ private val logger = Logger.withTag("InboxRotation")
+
+ /**
+ * Whether [localChatRoom]'s inbox key was made over admins the room no longer has, as
+ * [userPublicKey]'s device sees it. False where there is no key, or the admins cannot be read.
+ */
+ suspend fun isOwed(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey): Boolean {
+ val roomId = localChatRoom.chatRoom.id
+ val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey).filter { it.state != InboxKeyState.WIPED }
+ if (keys.isEmpty()) return false
+ val newest = database.inboxKeyDao().getCompletedCeremonies(roomId, userPublicKey).firstOrNull() ?: return false
+ val admins = RoomAdmins.of(database, roomId)?.admins ?: return false
+ return admins != newest.participants().toSet()
+ }
+
+ /** Whether [userPublicKey] is the admin whose device starts an owed rotation in [chatRoomId]. */
+ suspend fun startsIt(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Boolean =
+ RoomAdmins.of(database, chatRoomId)?.admins?.minOrNull() == userPublicKey
+
+ /**
+ * Starts every rotation [userPublicKey]'s device owes. Run by the governance follow-through and
+ * the sweep; repeats nothing, since a running ceremony is not started twice. Returns how many it
+ * started.
+ */
+ suspend fun pass(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int {
+ if (!ExperimentalFeatures.groupInbox) return 0
+ var started = 0
+ database.inboxKeyDao().getHeldKeys(userPublicKey).map { it.chatRoomId }.distinct().forEach { roomId ->
+ val room = database.chatRoomDao().findChatRoomById(roomId) ?: return@forEach
+ if (!isOwed(database, room, userPublicKey) || !startsIt(database, roomId, userPublicKey)) return@forEach
+ if (database.inboxKeyDao().getRunningCeremoniesIn(roomId).any { it.userPublicKey == userPublicKey }) return@forEach
+ if (InboxKeyRitualManager.refusal(database, room, userPublicKey) != null) return@forEach
+ try {
+ InboxKeyRitualManager.propose(database, room, userPublicKey, nostrPrivateKey)
+ started += 1
+ logger.i("The admins of ${roomId.take(8)} changed; rotating its inbox key")
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ logger.w("Could not rotate the inbox key of ${roomId.take(8)}: ${e.message}")
+ }
+ }
+ return started
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt
index 14aac74c..58973034 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt
@@ -56,6 +56,8 @@ interface GroupInboxRepository {
val setUpRefusal: String?,
/** The admins a running ceremony waits on, by name. */
val waitingOn: List,
+ /** The key was made over admins the room no longer has (D14). */
+ val rotationOwed: Boolean = false,
) {
val heldKey: InboxKey? get() = keys.firstOrNull { it.secretKey != null }
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt
index 064c573f..c9dea7fd 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt
@@ -65,6 +65,7 @@ import mobi.giza.compose.resources.rotate_the_inbox_key
import mobi.giza.compose.resources.set_up_an_inbox
import mobi.giza.compose.resources.the_admins_are_making_the_inbox_key
import mobi.giza.compose.resources.the_ceremony_ended
+import mobi.giza.compose.resources.the_admins_have_changed_since_this_key_was_made
import mobi.giza.compose.resources.the_inbox_key_ceremony_started
import mobi.giza.compose.resources.try_again
import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_announcement
@@ -222,6 +223,13 @@ fun GroupInboxSettingsScreen(
if (visibleKeys.isNotEmpty() && !running) {
Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) {
+ if (status.rotationOwed) {
+ Text(
+ stringResource(Res.string.the_admins_have_changed_since_this_key_was_made),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.error,
+ )
+ }
Text(stringResource(Res.string.rotate_explainer), style = MaterialTheme.typography.bodyMedium)
status.setUpRefusal?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxRotationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxRotationJvmTest.kt
new file mode 100644
index 00000000..3c491fd0
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxRotationJvmTest.kt
@@ -0,0 +1,163 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+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.EventTemplate
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
+import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import fr.acinq.bitcoin.Crypto
+import kotlin.test.AfterTest
+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.runBlocking
+import mobi.giza.compose.database.model.InboxKeyCeremonyStage
+import mobi.giza.compose.database.model.InboxKeyState
+import mobi.giza.compose.database.model.types.FrostSigningStage
+import mobi.giza.compose.nostr.inbox.InboxSeal
+import mobi.giza.compose.nostr.inbox.InboxWire
+import mobi.giza.compose.nostr.inbox.InboxWrap
+
+/**
+ * The inbox key changing with the group's admins (docs/group-inbox.md, Phase 9): nobody is asked,
+ * one admin's device starts it, a removed admin cannot open what is sent to the new key, a promoted
+ * one holds only the new key, and a reply proposed before the change still goes out after it.
+ */
+class InboxRotationJvmTest {
+ private val harness = GroupInboxHarness()
+ private val zola = KeyPair(Crypto.sha256("zola, who writes to the group".encodeToByteArray()))
+ private val now get() = kotlin.time.Clock.System.now().epochSeconds
+
+ @AfterTest
+ fun close() = harness.close()
+
+ private lateinit var devices: Map
+ private fun device(name: String) = devices.getValue(name)
+
+ private suspend fun open(names: List = listOf("alice", "bob", "carol")) {
+ devices = names.associateWith { harness.device(it) }
+ }
+
+ /** Makes and announces the first key among whoever the harness has as admins. */
+ private suspend fun announced(by: String = "alice", approver: String = "bob") {
+ val proposer = device(by)
+ InboxKeyRitualManager.propose(proposer.db, proposer.room(), proposer.publicKey, proposer.secret)
+ harness.pump()
+ val session = proposer.db.frostSigningSessionDao().getSessionsForChatRoom(harness.roomId).single()
+ FrostSigningManager.approve(device(approver).db, device(approver).room(), session.id)
+ harness.pump()
+ assertEquals(InboxKeyState.ANNOUNCED, proposer.keys().single().state)
+ }
+
+ /** Every device takes its rotation pass, then everything is delivered. */
+ private suspend fun passAndPump() {
+ devices.values.forEach { InboxRotation.pass(it.db, it.publicKey, it.secret) }
+ harness.pump()
+ }
+
+ private fun mailTo(key: HexKey, text: String): Event {
+ val message = RumorAssembler.assembleRumor(zola.pubKey.toHexKey(), EventTemplate(now, 14, arrayOf(arrayOf("p", harness.roomId)), text))
+ val seal = NostrSignerSync(zola).sign(now, 13, emptyArray(),
+ InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(zola.privKey!!, key)))
+ return InboxWrap.wrap(seal, harness.roomId, key)
+ }
+
+ @Test
+ fun `removing an admin rotates the key with nobody asked, and the removed admin cannot read the new one`() = runBlocking {
+ open()
+ announced()
+ val alice = device("alice"); val bob = device("bob"); val carol = device("carol")
+
+ // Carol stops being an admin. Her device lets go of the inbox; the others owe a rotation.
+ harness.admins = setOf(alice.publicKey, bob.publicKey)
+ GroupInboxManager.forgetIfNotAdmin(carol.db, harness.roomId, carol.publicKey, stillAdmin = false)
+ assertTrue(InboxRotation.isOwed(alice.db, alice.room(), alice.publicKey))
+ assertEquals(1, listOf(alice, bob).count { InboxRotation.startsIt(it.db, harness.roomId, it.publicKey) }, "one admin starts it")
+
+ passAndPump()
+
+ listOf(alice, bob).forEach { admin ->
+ val keys = admin.keys()
+ assertEquals(listOf(1, 0), keys.map { it.generation }, "${admin.name} holds both")
+ assertEquals(InboxKeyState.ANNOUNCED, keys[0].state, "${admin.name}'s device signed the new announcement unasked")
+ assertEquals(InboxKeyState.RETIRED, keys[1].state)
+ assertFalse(InboxRotation.isOwed(admin.db, admin.room(), admin.publicKey))
+ }
+ assertTrue(carol.keys().all { it.secretKey == null }, "Carol's device kept nothing")
+
+ val newKey = alice.keys()[0].publicKey
+ val oldKey = alice.keys()[1].publicKey
+ assertNotNull(GroupInboxManager.receive(bob.db, mailTo(newKey, "To the new key"), bob.publicKey))
+ assertNotNull(GroupInboxManager.receive(bob.db, mailTo(oldKey, "To the old key"), bob.publicKey), "old mail still opens")
+ assertNull(GroupInboxManager.receive(carol.db, mailTo(newKey, "Not for Carol"), carol.publicKey))
+ }
+
+ @Test
+ fun `a promoted admin holds only the new key`() = runBlocking {
+ open()
+ val alice = device("alice"); val bob = device("bob"); val carol = device("carol")
+ harness.admins = setOf(alice.publicKey, bob.publicKey)
+ announced()
+ assertEquals(emptyList(), carol.keys())
+
+ harness.admins = setOf(alice.publicKey, bob.publicKey, carol.publicKey)
+ passAndPump()
+
+ assertEquals(listOf(1), carol.keys().map { it.generation }, "nothing from before")
+ assertEquals(alice.keys().first().publicKey, carol.keys().single().publicKey)
+ assertEquals(InboxKeyState.ANNOUNCED, carol.keys().single().state)
+ }
+
+ @Test
+ fun `a reply proposed before a rotation still goes out after it`() = runBlocking {
+ open()
+ announced()
+ val alice = device("alice"); val bob = device("bob")
+ val firstKey = alice.keys().single().publicKey
+ assertNotNull(GroupInboxManager.receive(alice.db, mailTo(firstKey, "Hello"), alice.publicKey))
+ val conversation = alice.db.groupInboxDao().getMessages(harness.roomId).single().conversationId
+ val reply = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversation, "Sealed before the change").id
+ harness.pump()
+
+ InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret)
+ harness.pump()
+ assertEquals(InboxKeyState.ANNOUNCED, alice.keys().first { it.generation == 1 }.state)
+
+ FrostSigningManager.approve(bob.db, bob.room(), reply)
+ harness.pump()
+ assertEquals(FrostSigningStage.COMPLETE, alice.db.frostSigningSessionDao().getSessionById(reply)?.stage)
+ assertEquals(2, alice.db.groupInboxDao().getPublicationsFor(reply).size, "Zola's wrap and the group's copy")
+ }
+
+ @Test
+ fun `two rotations started at once end as one, on every device`() = runBlocking {
+ open()
+ announced()
+ val alice = device("alice"); val bob = device("bob"); val carol = device("carol")
+ val first = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret)
+ val second = InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret)
+ harness.pump()
+
+ val (winner, loser) = if (first.id < second.id) first to second else second to first
+ listOf(alice, bob, carol).forEach { admin ->
+ assertEquals(InboxKeyCeremonyStage.COMPLETE, admin.ceremony(winner.id)?.stage, "${admin.name} finished one")
+ assertEquals(InboxKeyCeremonyStage.FAILED, admin.ceremony(loser.id)?.stage, "${admin.name} ended the other")
+ assertEquals(listOf(1, 0), admin.keys().map { it.generation })
+ }
+ assertEquals(1, listOf(alice, bob, carol).map { it.keys().first().publicKey }.distinct().size, "one key for everyone")
+ }
+
+ @Test
+ fun `nothing is owed while the admins are the ones who made the key`() = runBlocking {
+ open()
+ announced()
+ devices.values.forEach { assertFalse(InboxRotation.isOwed(it.db, it.room(), it.publicKey)) }
+ devices.values.forEach { assertEquals(0, InboxRotation.pass(it.db, it.publicKey, it.secret)) }
+ }
+}