diff --git a/.changeset/sender-key-index-observer.md b/.changeset/sender-key-index-observer.md new file mode 100644 index 000000000..472770753 --- /dev/null +++ b/.changeset/sender-key-index-observer.md @@ -0,0 +1,5 @@ +--- +"client-sdk-android": patch +--- + +E2EE: already-published tracks now follow key-index changes. Previously a sender's frame cryptor was stamped once when the track was published, so after `setSharedKey(key, n)` (or `setKey(key, localIdentity, n)`) existing tracks kept encrypting with the old slot and receivers hit `MISSING_KEY`. In shared-key mode, tracks published and data packets sent after a rotation also used slot 0; they now use the installed index. `E2EEManager.ratchetKey()` now ratchets the slot senders encrypt with instead of slot 0. `ratchetSharedKey(null)` ratchets the current shared slot instead of slot 0, and `ratchetKey(id, null)` ratchets that participant's current slot. Recorded key indexes now match the slot the native key ring actually writes: an index past the ring wraps (`index % keyRingSize`) and a negative index replaces the key in the current slot without moving it, so senders are never stamped with a slot that doesn't exist. Per-participant key indexes are otherwise unchanged. Custom `KeyProvider`s can implement the new `KeyIndexObservable` interface to get the same live re-stamping. diff --git a/livekit-android-sdk/detekt-baseline-release.xml b/livekit-android-sdk/detekt-baseline-release.xml index 20aff9434..92197cad7 100644 --- a/livekit-android-sdk/detekt-baseline-release.xml +++ b/livekit-android-sdk/detekt-baseline-release.xml @@ -76,6 +76,7 @@ SwallowedException:TextureViewRenderer.kt$TextureViewRenderer$e: NotFoundException TooManyFunctions:CommunicationWorkaround.kt$CommunicationWorkaroundImpl : CommunicationWorkaround TooManyFunctions:E2EEManager.kt$E2EEManager + TooManyFunctions:KeyProvider.kt$BaseKeyProvider : KeyProviderKeyIndexObservable TooManyFunctions:LKLog.kt$LKLog$Companion TooManyFunctions:LocalParticipant.kt$LocalParticipant : ParticipantOutgoingDataStreamManagerRpcManager TooManyFunctions:LocalVideoTrack.kt$LocalVideoTrack : VideoTrack diff --git a/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/E2EEManager.kt b/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/E2EEManager.kt index 40913db63..87e127bf7 100644 --- a/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/E2EEManager.kt +++ b/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/E2EEManager.kt @@ -32,6 +32,8 @@ import io.livekit.android.room.track.RemoteVideoTrack import io.livekit.android.room.track.Track import io.livekit.android.room.track.TrackPublication import io.livekit.android.util.LKLog +import io.livekit.android.webrtc.peerconnection.RTCThreadToken +import io.livekit.android.webrtc.peerconnection.executeOnRTCThread import livekit.LivekitModels.Encryption import livekit.org.webrtc.FrameCryptor import livekit.org.webrtc.FrameCryptor.FrameCryptionState @@ -40,6 +42,7 @@ import livekit.org.webrtc.FrameCryptorFactory import livekit.org.webrtc.PeerConnectionFactory import livekit.org.webrtc.RtpReceiver import livekit.org.webrtc.RtpSender +import java.util.Collections class E2EEManager @AssistedInject @@ -47,9 +50,10 @@ constructor( @Assisted val keyProvider: KeyProvider, val peerConnectionFactory: PeerConnectionFactory, dataPacketCryptorManagerFactory: DataPacketCryptorManager.Factory, + private val rtcThreadToken: RTCThreadToken, ) { private var room: Room? = null - private val frameCryptors = mutableMapOf, FrameCryptor>() + private val frameCryptors = Collections.synchronizedMap(mutableMapOf, FrameCryptor>()) private var algorithm: FrameCryptorAlgorithm = FrameCryptorAlgorithm.AES_GCM private lateinit var emitEvent: (roomEvent: RoomEvent) -> Unit? @@ -58,9 +62,11 @@ constructor( var enabled: Boolean = false set(value) { field = value - for (item in frameCryptors.entries) { - val frameCryptor = item.value - frameCryptor.isEnabled = enabled + synchronized(frameCryptors) { + for (item in frameCryptors.entries) { + val frameCryptor = item.value + frameCryptor.isEnabled = enabled + } } } @@ -96,6 +102,7 @@ constructor( this.enabled = true this.room = room this.emitEvent = emitEvent + observeKeyIndex() this.room?.localParticipant?.trackPublications?.forEach { item -> val participant = this.room!!.localParticipant val publication = item.value @@ -140,12 +147,12 @@ constructor( fun removeSubscribedTrack(track: Track, publication: TrackPublication, participant: RemoteParticipant, room: Room) { val trackId = publication.sid val participantId = participant.identity - val frameCryptor = frameCryptors.get(trackId to participantId) - if (frameCryptor != null) { - frameCryptor.isEnabled = false - frameCryptor.dispose() - frameCryptors.remove(trackId to participantId) - } + // Remove before disposing: a loop over frameCryptors (key-index re-stamp, + // enabled toggle, cleanup) must never see a disposed cryptor, and only the + // caller that removed the entry disposes it. + val frameCryptor = frameCryptors.remove(trackId to participantId) ?: return + frameCryptor.isEnabled = false + frameCryptor.dispose() } fun addPublishedTrack(track: Track, publication: TrackPublication, participant: LocalParticipant, room: Room) { @@ -175,12 +182,12 @@ constructor( fun removePublishedTrack(track: Track, publication: TrackPublication, participant: LocalParticipant, room: Room) { val trackId = publication.sid val participantId = participant.identity - val frameCryptor = frameCryptors.get(trackId to participantId) - if (frameCryptor != null) { - frameCryptor.isEnabled = false - frameCryptor.dispose() - frameCryptors.remove(trackId to participantId) - } + // Remove before disposing: a loop over frameCryptors (key-index re-stamp, + // enabled toggle, cleanup) must never see a disposed cryptor, and only the + // caller that removed the entry disposes it. + val frameCryptor = frameCryptors.remove(trackId to participantId) ?: return + frameCryptor.isEnabled = false + frameCryptor.dispose() } private fun e2eeStateFromFrameCryptoState(state: FrameCryptionState?): E2EEState { @@ -205,9 +212,13 @@ constructor( keyProvider.rtcKeyProvider, ) - frameCryptors[trackId to participantId] = frameCryptor - frameCryptor.isEnabled = enabled - frameCryptor.keyIndex = keyProvider.getLatestKeyIndex(participantId.value) + // Insert and stamp under the same monitor the key-index re-stamp holds, so a + // rotation landing mid-setup can't be overwritten by a stale index read here. + synchronized(frameCryptors) { + frameCryptors[trackId to participantId] = frameCryptor + frameCryptor.isEnabled = enabled + frameCryptor.keyIndex = keyProvider.getLatestKeyIndex(participantId.value) + } return frameCryptor } @@ -220,9 +231,13 @@ constructor( keyProvider.rtcKeyProvider, ) - frameCryptors[trackId to participantId] = frameCryptor - frameCryptor.isEnabled = enabled - frameCryptor.keyIndex = keyProvider.getLatestKeyIndex(participantId.value) + // Receivers read the key index from each frame's trailer; locked for + // consistency with addRtpSender (one insert-and-configure step per cryptor). + synchronized(frameCryptors) { + frameCryptors[trackId to participantId] = frameCryptor + frameCryptor.isEnabled = enabled + frameCryptor.keyIndex = keyProvider.getLatestKeyIndex(participantId.value) + } return frameCryptor } @@ -238,18 +253,54 @@ constructor( * Ratchet key for local participant */ fun ratchetKey() { - val newKey = keyProvider.ratchetSharedKey() + // Ratchet the slot local senders encrypt with, not the interface default (0). + val localIdentity = room?.localParticipant?.identity?.value ?: "" + val newKey = keyProvider.ratchetSharedKey(keyProvider.getLatestKeyIndex(localIdentity)) LKLog.d { "ratchetSharedKey: newKey: $newKey" } } + /** + * Re-stamps the frame cryptors of every track the local participant has + * already published, when [participantId] is the local participant or + * `null` (the shared key). Runs on the RTC thread like all other frame + * cryptor calls, and reads the index there rather than using the notified + * one, so a re-stamp queued behind a newer one can't apply a stale index. + */ + internal fun restampLocalSenders(participantId: String?) { + executeOnRTCThread(rtcThreadToken) { + val localIdentity = room?.localParticipant?.identity ?: return@executeOnRTCThread + if (participantId != null && participantId != localIdentity.value) { + return@executeOnRTCThread + } + synchronized(frameCryptors) { + val keyIndex = keyProvider.getLatestKeyIndex(localIdentity.value) + for ((key, frameCryptor) in frameCryptors) { + if (key.second == localIdentity) { + frameCryptor.keyIndex = keyIndex + } + } + } + } + } + + private fun observeKeyIndex() { + (keyProvider as? KeyIndexObservable)?.addKeyIndexObserver(this) { participantId, _ -> + restampLocalSenders(participantId) + } + } + internal fun cleanup() { - for (frameCryptor in frameCryptors.values) { - frameCryptor.dispose() + (keyProvider as? KeyIndexObservable)?.removeKeyIndexObserver(this) + synchronized(frameCryptors) { + for (frameCryptor in frameCryptors.values) { + frameCryptor.dispose() + } + frameCryptors.clear() } - frameCryptors.clear() } internal fun dispose() { + (keyProvider as? KeyIndexObservable)?.removeKeyIndexObserver(this) dataPacketCryptorManager.dispose() } diff --git a/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/E2EEOptions.kt b/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/E2EEOptions.kt index 641f18a4a..556e05155 100644 --- a/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/E2EEOptions.kt +++ b/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/E2EEOptions.kt @@ -24,6 +24,9 @@ internal const val defaultMagicBytes = "LK-ROCKS" internal const val defaultRatchetWindowSize = 16 internal const val defaultFailureTolerance = -1 internal const val defaultKeyRingSize = 16 + +// libwebrtc caps the key ring at MAX_KEYRING_SIZE; a size <= 0 falls back to the default. +internal const val maxKeyRingSize = 256 internal const val defaultDiscardFrameWhenCryptorNotReady = false internal val defaultKeyDerivationAlgorithm = FrameCryptorKeyDerivationAlgorithm.PBKDF2 internal val defaultKeySize = KeyProviderKeySize.BITS_128 diff --git a/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/KeyProvider.kt b/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/KeyProvider.kt index e76b23f2f..f20c472cc 100644 --- a/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/KeyProvider.kt +++ b/livekit-android-sdk/src/main/java/io/livekit/android/e2ee/KeyProvider.kt @@ -20,6 +20,7 @@ import io.livekit.android.util.LKLog import livekit.org.webrtc.FrameCryptorFactory import livekit.org.webrtc.FrameCryptorKeyDerivationAlgorithm import livekit.org.webrtc.FrameCryptorKeyProvider +import java.util.concurrent.ConcurrentHashMap internal class KeyInfo(var participantId: String, var keyIndex: Int, var key: String) { override fun toString(): String { @@ -54,6 +55,31 @@ interface KeyProvider { var enableSharedKey: Boolean } +/** + * Implemented by [KeyProvider]s that report when the index returned by + * [KeyProvider.getLatestKeyIndex] changes. + * + * [E2EEManager] subscribes so the frame cryptors of tracks the local + * participant has already published are re-stamped with the new index; + * without it, only senders created after the change pick it up. Receivers + * are unaffected: they read the index from each incoming frame. + */ +interface KeyIndexObservable { + + /** + * Registers [observer] under [owner]; [removeKeyIndexObserver] with the + * same owner detaches it. [observer] receives the participant whose latest + * key index was written, or `null` when the shared key index was, plus the + * index written. It may be called from any thread. + */ + fun addKeyIndexObserver(owner: Any, observer: (participantId: String?, keyIndex: Int) -> Unit) + + /** + * Detaches the observer previously registered under [owner]. + */ + fun removeKeyIndexObserver(owner: Any) +} + class BaseKeyProvider( ratchetSalt: String = defaultRatchetSalt, uncryptedMagicBytes: String = defaultMagicBytes, @@ -64,9 +90,21 @@ class BaseKeyProvider( discardFrameWhenCryptorNotReady: Boolean = defaultDiscardFrameWhenCryptorNotReady, keyDerivationAlgorithm: FrameCryptorKeyDerivationAlgorithm = defaultKeyDerivationAlgorithm, keySize: KeyProviderKeySize = defaultKeySize, -) : KeyProvider { +) : KeyProvider, KeyIndexObservable { + + // The native key ring is clamped this way (<= 0 -> default, > 256 -> 256) and wraps an + // installed index by its size. Recorded indexes must be the slot actually written: senders + // are stamped with them, and native looks the stamp up without a bounds check. + private val effectiveKeyRingSize: Int = + if (keyRingSize <= 0) defaultKeyRingSize else minOf(keyRingSize, maxKeyRingSize) + + // Written from the app's thread, read on the RTC thread by E2EEManager. + private val latestSetIndex = ConcurrentHashMap() - private val latestSetIndex = mutableMapOf() + @Volatile + private var sharedKeyIndex: Int = 0 + + private val keyIndexObservers = ConcurrentHashMap Unit>() override val rtcKeyProvider: FrameCryptorKeyProvider = FrameCryptorFactory.createFrameCryptorKeyProvider( enableSharedKey, @@ -80,14 +118,39 @@ class BaseKeyProvider( keySize.bits, ) + /** + * Installs the shared key at [keyIndex] and, on success, makes it the index + * the local participant encrypts with; already-published tracks follow. + * + * Like the native key provider, an index past the key ring wraps to + * `keyIndex % keyRingSize`. A negative [keyIndex] replaces the key in the + * current shared slot without moving it. + */ override fun setSharedKey(key: String, keyIndex: Int?): Boolean { - return rtcKeyProvider.setSharedKey(keyIndex ?: 0, key.toByteArray()) + val index = keyIndex ?: 0 + val installed = rtcKeyProvider.setSharedKey(sharedSlot(index), key.toByteArray()) + if (installed && index >= 0) { + val slot = index % effectiveKeyRingSize + sharedKeyIndex = slot + notifyKeyIndexObservers(null, slot) + } + return installed } + /** + * Ratchets the shared key at [keyIndex], or at the current shared slot when + * [keyIndex] is `null` or negative. + */ override fun ratchetSharedKey(keyIndex: Int?): ByteArray { - return rtcKeyProvider.ratchetSharedKey(keyIndex ?: 0) + return rtcKeyProvider.ratchetSharedKey(sharedSlot(keyIndex ?: -1)) } + // Native fans shared installs and ratchets out to every participant's key handler with + // the index it was given, and each handler resolves -1 to its own current slot, which + // differs per participant once a receiver has auto-ratcheted. So shared operations + // never pass a negative index to native: it resolves to the recorded shared slot. + private fun sharedSlot(index: Int): Int = if (index >= 0) index else sharedKeyIndex + override fun exportSharedKey(keyIndex: Int?): ByteArray { return rtcKeyProvider.exportSharedKey(keyIndex ?: 0) } @@ -108,14 +171,27 @@ class BaseKeyProvider( return } - val keyIndex = keyIndex ?: 0 - latestSetIndex[participantId] = keyIndex + val index = keyIndex ?: 0 + rtcKeyProvider.setKey(participantId, index, key.toByteArray()) - rtcKeyProvider.setKey(participantId, keyIndex, key.toByteArray()) + // Record only what senders are stamped with: a non-negative index wraps by the + // ring size like native. A negative one installs into native's current slot + // and doesn't move the stamped index, so there is nothing to record or re-stamp. + if (index >= 0) { + val slot = index % effectiveKeyRingSize + latestSetIndex[participantId] = slot + notifyKeyIndexObservers(participantId, slot) + } } + /** + * Ratchets [participantId]'s key at [keyIndex], or at native's current slot + * for that participant when [keyIndex] is `null`. Unlike the shared key, this + * reaches only that participant's handler, whose current slot follows the + * slot their sender encrypts with. + */ override fun ratchetKey(participantId: String, keyIndex: Int?): ByteArray { - return rtcKeyProvider.ratchetKey(participantId, keyIndex ?: 0) + return rtcKeyProvider.ratchetKey(participantId, keyIndex ?: NATIVE_CURRENT_SLOT) } override fun exportKey(participantId: String, keyIndex: Int?): ByteArray { @@ -126,7 +202,30 @@ class BaseKeyProvider( rtcKeyProvider.setSifTrailer(trailer) } + /** + * The key index [participantId] last installed with [setKey], or in shared + * key mode the index last installed with [setSharedKey]. + */ override fun getLatestKeyIndex(participantId: String): Int { - return latestSetIndex[participantId] ?: 0 + return if (enableSharedKey) sharedKeyIndex else latestSetIndex[participantId] ?: 0 + } + + override fun addKeyIndexObserver(owner: Any, observer: (participantId: String?, keyIndex: Int) -> Unit) { + keyIndexObservers[owner] = observer + } + + override fun removeKeyIndexObserver(owner: Any) { + keyIndexObservers.remove(owner) + } + + private fun notifyKeyIndexObservers(participantId: String?, keyIndex: Int) { + keyIndexObservers.values.forEach { it(participantId, keyIndex) } + } + + private companion object { + // Native ratchets a participant handler's own current slot for -1. Per-participant + // implicit ratchets defer to that pointer: it follows the slot a remote sender + // encrypts with, which this provider doesn't track. + const val NATIVE_CURRENT_SLOT = -1 } } diff --git a/livekit-android-sdk/src/main/java/io/livekit/android/room/Room.kt b/livekit-android-sdk/src/main/java/io/livekit/android/room/Room.kt index 15d4b1972..642bb4e53 100644 --- a/livekit-android-sdk/src/main/java/io/livekit/android/room/Room.kt +++ b/livekit-android-sdk/src/main/java/io/livekit/android/room/Room.kt @@ -340,6 +340,24 @@ constructor( * keyProvider.setSharedKey("my-shared-key") * room.e2eeOptions = E2EEOptions(keyProvider = keyProvider) * ``` + * + * Example — shared-key encryption with key-index rotation: + * ``` + * val keyProvider = BaseKeyProvider() + * keyProvider.setSharedKey("my-secret", keyIndex = 0) + * room.e2eeOptions = E2EEOptions(keyProvider = keyProvider) + * room.connect(url, token) + * + * // Later, after distributing the next key out-of-band. Installing it + * // switches local encryption to index 1, including tracks already published: + * keyProvider.setSharedKey("next-secret", keyIndex = 1) + * ``` + * In per-participant mode, `keyProvider.setKey(key, localIdentity, index)` + * does the same for the local participant's own tracks; keys installed for + * remote participants never change what the local participant sends with. + * + * Custom providers can implement [io.livekit.android.e2ee.KeyIndexObservable] + * to opt into the same live re-stamping. */ var e2eeOptions: E2EEOptions? = null diff --git a/livekit-android-test/src/test/java/io/livekit/android/e2ee/FrameCryptorKeyIndexTest.kt b/livekit-android-test/src/test/java/io/livekit/android/e2ee/FrameCryptorKeyIndexTest.kt new file mode 100644 index 000000000..0b3b34a1e --- /dev/null +++ b/livekit-android-test/src/test/java/io/livekit/android/e2ee/FrameCryptorKeyIndexTest.kt @@ -0,0 +1,620 @@ +/* + * Copyright 2026 LiveKit, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.livekit.android.e2ee + +import io.livekit.android.room.Room +import io.livekit.android.room.participant.LocalParticipant +import io.livekit.android.room.participant.Participant +import io.livekit.android.room.participant.RemoteParticipant +import io.livekit.android.room.track.LocalAudioTrack +import io.livekit.android.room.track.RemoteAudioTrack +import io.livekit.android.room.track.Track +import io.livekit.android.room.track.TrackPublication +import io.livekit.android.test.BaseTest +import io.livekit.android.webrtc.peerconnection.RTCThreadToken +import livekit.org.webrtc.FrameCryptor +import livekit.org.webrtc.FrameCryptorFactory +import livekit.org.webrtc.FrameCryptorKeyProvider +import livekit.org.webrtc.PeerConnectionFactory +import livekit.org.webrtc.RtpReceiver +import livekit.org.webrtc.RtpSender +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.mockito.Mockito.mockStatic +import org.mockito.Mockito.never +import org.mockito.Mockito.times +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.util.Collections +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +class FrameCryptorKeyIndexTest : BaseTest() { + + private val rtcKeyProvider = mock() + private val senderCryptor = mock() + private val secondSenderCryptor = mock() + private val receiverCryptor = mock() + private val dataPacketCryptorManager = RecordingDataPacketCryptorManager() + private val rtcThreadToken = object : RTCThreadToken { + override val isDisposed: Boolean = false + } + + private fun mockedFactory() = mockStatic(FrameCryptorFactory::class.java).apply { + `when` { + FrameCryptorFactory.createFrameCryptorKeyProvider( + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any(), + ) + }.thenReturn(rtcKeyProvider) + // First published track gets senderCryptor, the next secondSenderCryptor. + `when` { + FrameCryptorFactory.createFrameCryptorForRtpSender(any(), any(), any(), any(), any()) + }.thenReturn(senderCryptor, secondSenderCryptor) + `when` { + FrameCryptorFactory.createFrameCryptorForRtpReceiver(any(), any(), any(), any(), any()) + }.thenReturn(receiverCryptor) + } + + private fun createProvider(sharedKey: Boolean = true): BaseKeyProvider { + whenever(rtcKeyProvider.setSharedKey(any(), any())).thenReturn(true) + whenever(rtcKeyProvider.ratchetSharedKey(any())).thenReturn(ByteArray(0)) + whenever(rtcKeyProvider.ratchetKey(any(), any())).thenReturn(ByteArray(0)) + return BaseKeyProvider(enableSharedKey = sharedKey) + } + + private fun createManager(provider: KeyProvider): Triple { + val room = mock() + val localParticipant = mock() + whenever(room.localParticipant).thenReturn(localParticipant) + whenever(room.remoteParticipants).thenReturn(emptyMap()) + whenever(localParticipant.identity).thenReturn(Participant.Identity(LOCAL)) + whenever(localParticipant.trackPublications).thenReturn(emptyMap()) + + val manager = E2EEManager( + provider, + mock(), + object : DataPacketCryptorManager.Factory { + override fun create(keyProvider: KeyProvider) = dataPacketCryptorManager + }, + rtcThreadToken, + ) + manager.setup(room) { } + return Triple(manager, room, localParticipant) + } + + private fun addLocalSender( + manager: E2EEManager, + room: Room, + participant: LocalParticipant, + sid: String = "sender-sid", + ) { + val track = mock() + whenever(track.sender).thenReturn(mock()) + whenever(track.kind).thenReturn(Track.Kind.AUDIO) + val publication = mock() + whenever(publication.track).thenReturn(track) + whenever(publication.sid).thenReturn(sid) + + manager.addPublishedTrack(track, publication, participant, room) + } + + private fun addRemoteReceiver(manager: E2EEManager, room: Room) { + val participant = mock() + whenever(participant.identity).thenReturn(Participant.Identity(REMOTE)) + val track = mock() + whenever(track.receiver).thenReturn(mock()) + whenever(track.kind).thenReturn(Track.Kind.AUDIO) + val publication = mock() + whenever(publication.track).thenReturn(track) + whenever(publication.sid).thenReturn("receiver-sid") + + manager.addSubscribedTrack(track, publication, participant, room) + } + + /** Delegates to [BaseKeyProvider] and runs [onLatestRead] once, right after the + * first latest-index read: the point where a concurrent rotation can interleave + * with a new cryptor's initial stamp. */ + private class InterleavingKeyProvider(private val base: BaseKeyProvider) : + KeyProvider by base, + KeyIndexObservable by base { + @Volatile + var onLatestRead: (() -> Unit)? = null + + override fun getLatestKeyIndex(participantId: String): Int { + val index = base.getLatestKeyIndex(participantId) + onLatestRead?.let { + onLatestRead = null + it() + } + return index + } + } + + /** Mirrors the native wrapper: any call on a disposed FrameCryptor throws. + * [afterDispose] runs right after the cryptor is marked disposed: the window + * where a concurrent loop over the cryptor map can interleave with removal. */ + private fun throwWhenDisposed(cryptor: FrameCryptor, afterDispose: () -> Unit = {}): MutableList { + val callsAfterDispose = Collections.synchronizedList(mutableListOf()) + var disposed = false + doAnswer { + if (disposed) { + callsAfterDispose.add("setKeyIndex") + throw IllegalStateException("FrameCryptor has been disposed.") + } + null + }.whenever(cryptor).keyIndex = any() + doAnswer { + if (disposed) { + callsAfterDispose.add("setEnabled") + throw IllegalStateException("FrameCryptor has been disposed.") + } + null + }.whenever(cryptor).isEnabled = any() + doAnswer { + if (disposed) { + callsAfterDispose.add("dispose") + throw IllegalStateException("FrameCryptor has been disposed.") + } + disposed = true + afterDispose() + null + }.whenever(cryptor).dispose() + return callsAfterDispose + } + + // Participant.Identity is a value class; Mockito matchers can't match its + // unboxed args, so record encrypt() calls with a plain fake instead. + private class RecordingDataPacketCryptorManager : DataPacketCryptorManager { + var lastEncryptKeyIndex: Int? = null + + override fun encrypt( + participantId: Participant.Identity, + keyIndex: Int, + payload: ByteArray, + ): EncryptedPacket? { + lastEncryptKeyIndex = keyIndex + return null + } + + override fun decrypt(participantId: Participant.Identity, packet: EncryptedPacket): ByteArray? = null + + override fun dispose() {} + } + + // --- Provider: index bookkeeping and notifications --- + + @Test + fun sharedKeyInstallMovesLatestKeyIndex() { + mockedFactory().use { + val provider = createProvider() + provider.setSharedKey("key", 3) + assertEquals(3, provider.getLatestKeyIndex(LOCAL)) + assertEquals(3, provider.getLatestKeyIndex("anyone")) + } + } + + @Test + fun failedSharedKeyInstallDoesNotMoveIndexOrNotify() { + mockedFactory().use { + val provider = createProvider() + whenever(rtcKeyProvider.setSharedKey(eq(4), any())).thenReturn(false) + val seen = mutableListOf>() + provider.addKeyIndexObserver(this) { id, index -> seen.add(id to index) } + + assertFalse(provider.setSharedKey("key", 4)) + assertEquals(0, provider.getLatestKeyIndex(LOCAL)) + assertTrue("no notification for a failed install: $seen", seen.isEmpty()) + } + } + + @Test + fun negativeSharedKeyIndexInstallsWithoutMovingIndexOrNotifying() { + mockedFactory().use { + val provider = createProvider() + provider.setSharedKey("key-a", 5) + val seen = mutableListOf>() + provider.addKeyIndexObserver(this) { id, index -> seen.add(id to index) } + + // Native fans shared installs out to every participant handler, each + // resolving -1 to its own current slot, so a negative index is resolved + // to the shared slot (5) first. It doesn't move the index senders use. + provider.setSharedKey("key-b", -1) + verify(rtcKeyProvider).setSharedKey(eq(5), eq("key-b".toByteArray())) + verify(rtcKeyProvider, never()).setSharedKey(eq(-1), any()) + assertEquals(5, provider.getLatestKeyIndex(LOCAL)) + assertTrue("no re-stamp for an unmoved index: $seen", seen.isEmpty()) + } + } + + @Test + fun nonSharedSetKeyKeepsPerParticipantIndexes() { + mockedFactory().use { + val provider = createProvider(sharedKey = false) + provider.setKey("local-key", LOCAL, 2) + provider.setKey("remote-key", REMOTE, 7) + + // Unchanged from before: each participant keeps its own latest index, + // so a remote install can't redirect the local sender. + assertEquals(2, provider.getLatestKeyIndex(LOCAL)) + assertEquals(7, provider.getLatestKeyIndex(REMOTE)) + } + } + + @Test + fun observerSeesWhoseIndexChangedAndRemovalStopsCallbacks() { + mockedFactory().use { + val shared = createProvider() + val seen = mutableListOf>() + shared.addKeyIndexObserver(this) { id, index -> seen.add(id to index) } + shared.setSharedKey("k3", 3) + shared.removeKeyIndexObserver(this) + shared.setSharedKey("k4", 4) + assertEquals(listOf>(null to 3), seen) + + val perParticipant = createProvider(sharedKey = false) + seen.clear() + perParticipant.addKeyIndexObserver(this) { id, index -> seen.add(id to index) } + perParticipant.setKey("k", REMOTE, 6) + assertEquals(listOf>(REMOTE to 6), seen) + } + } + + // --- Recorded indexes are the slots native actually writes --- + + @Test + fun sharedKeyIndexPastTheRingWrapsToTheInstalledSlot() { + mockedFactory().use { + val provider = createProvider() + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + + // Native installs index 20 into slot 20 % 16 = 4 and looks a sender's + // stamp up without a bounds check, so the stamp must be 4, never 20. + provider.setSharedKey("rotated", 20) + assertEquals(4, provider.getLatestKeyIndex(LOCAL)) + verify(senderCryptor).keyIndex = 4 + verify(senderCryptor, never()).keyIndex = 20 + } + } + + @Test + fun perParticipantIndexPastTheRingWrapsToTheInstalledSlot() { + mockedFactory().use { + val provider = createProvider(sharedKey = false) + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + + provider.setKey("rotated", LOCAL, 17) + verify(rtcKeyProvider).setKey(eq(LOCAL), eq(17), eq("rotated".toByteArray())) + assertEquals(1, provider.getLatestKeyIndex(LOCAL)) + verify(senderCryptor).keyIndex = 1 + verify(senderCryptor, never()).keyIndex = 17 + } + } + + @Test + fun negativePerParticipantInstallDoesNotMoveOrRestamp() { + mockedFactory().use { + val provider = createProvider(sharedKey = false) + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + provider.setKey("current", LOCAL, 2) + verify(senderCryptor).keyIndex = 2 + + // A negative index goes to native unchanged and doesn't move the stamped + // index. Stamping -1 would write it into every frame's trailer and send + // receivers to a slot that doesn't exist. + provider.setKey("replacement", LOCAL, -1) + verify(rtcKeyProvider).setKey(eq(LOCAL), eq(-1), eq("replacement".toByteArray())) + assertEquals(2, provider.getLatestKeyIndex(LOCAL)) + verify(senderCryptor, never()).keyIndex = -1 + } + } + + @Test + fun perParticipantImplicitOperationsDeferToNativeCurrentSlot() { + mockedFactory().use { + // Per-participant operations reach only that participant's handler, whose + // current pointer follows the slot their sender encrypts with (moved by an + // explicit or auto ratchet). Negative installs and null-index ratchets go to + // native unresolved so both land in that slot. + val provider = createProvider(sharedKey = false) + provider.setKey("k2", REMOTE, 2) + provider.ratchetKey(REMOTE, 5) + provider.setKey("replacement", REMOTE, -1) + verify(rtcKeyProvider).setKey(eq(REMOTE), eq(-1), eq("replacement".toByteArray())) + provider.ratchetKey(REMOTE, null) + verify(rtcKeyProvider).ratchetKey(REMOTE, -1) + assertEquals(2, provider.getLatestKeyIndex(REMOTE)) + } + } + + @Test + fun sharedImplicitOperationsNeverPassANegativeIndexToNative() { + mockedFactory().use { + // Native fans shared ratchets out to every participant handler with the + // given index; -1 would resolve per handler, and a peer that auto-ratcheted + // onto another slot would get the shared key's new material over its active + // key. Shared operations resolve to the recorded shared slot instead. + val provider = createProvider() + provider.setSharedKey("k3", 3) + provider.ratchetSharedKey(6) + provider.setSharedKey("replacement", -1) + verify(rtcKeyProvider).setSharedKey(eq(3), eq("replacement".toByteArray())) + provider.ratchetSharedKey(null) + provider.ratchetSharedKey(-1) + verify(rtcKeyProvider, times(2)).ratchetSharedKey(3) + verify(rtcKeyProvider, never()).ratchetSharedKey(-1) + verify(rtcKeyProvider, never()).setSharedKey(eq(-1), any()) + assertEquals(3, provider.getLatestKeyIndex(LOCAL)) + } + } + + @Test + fun ringSizeIsClampedLikeNative() { + mockedFactory().use { + whenever(rtcKeyProvider.setSharedKey(any(), any())).thenReturn(true) + + // <= 0 falls back to the default ring (16). + val zero = BaseKeyProvider(keyRingSize = 0) + zero.setSharedKey("key", 17) + assertEquals(1, zero.getLatestKeyIndex(LOCAL)) + + // > 256 is capped at 256. + val oversized = BaseKeyProvider(keyRingSize = 300) + oversized.setSharedKey("key", 257) + assertEquals(1, oversized.getLatestKeyIndex(LOCAL)) + oversized.setSharedKey("key", 255) + assertEquals(255, oversized.getLatestKeyIndex(LOCAL)) + } + } + + // --- Manager: stamping and re-stamping senders --- + + @Test + fun newSendersAreStampedWithLatestSharedKeyIndex() { + mockedFactory().use { + val provider = createProvider() + provider.setSharedKey("key", 4) + + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + + verify(senderCryptor).keyIndex = 4 + } + } + + @Test + fun existingSendersFollowSharedKeyRotation() { + mockedFactory().use { + val provider = createProvider() + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + + provider.setSharedKey("rotated", 9) + verify(senderCryptor).keyIndex = 9 + } + } + + @Test + fun senderPublishedAfterSharedKeyRotationUsesRotatedIndex() { + mockedFactory().use { + val provider = createProvider() + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant, sid = "first") + + provider.setSharedKey("rotated", 2) + verify(senderCryptor).keyIndex = 2 + + // A track published after the rotation must start on the rotated + // slot too; before the fix getLatestKeyIndex() returned 0 in shared + // mode, so it encrypted with a key receivers had already moved off. + addLocalSender(manager, room, localParticipant, sid = "second") + verify(secondSenderCryptor).keyIndex = 2 + verify(secondSenderCryptor, never()).keyIndex = 0 + + // Data packets take the same path. + manager.encrypt(byteArrayOf(1, 2, 3)) + assertEquals(2, dataPacketCryptorManager.lastEncryptKeyIndex) + } + } + + @Test + fun senderPublishedAfterLocalKeyRotationUsesRotatedIndex() { + mockedFactory().use { + val provider = createProvider(sharedKey = false) + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant, sid = "first") + + provider.setKey("rotated", LOCAL, 3) + verify(senderCryptor).keyIndex = 3 + + addLocalSender(manager, room, localParticipant, sid = "second") + verify(secondSenderCryptor).keyIndex = 3 + } + } + + @Test + fun remoteKeyInstallDoesNotRestampLocalSenders() { + mockedFactory().use { + val provider = createProvider(sharedKey = false) + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + + provider.setKey("remote-key", REMOTE, 4) + verify(senderCryptor, never()).keyIndex = 4 + + provider.setKey("local-key", LOCAL, 5) + verify(senderCryptor).keyIndex = 5 + } + } + + @Test + fun receiversAreNotRestamped() { + mockedFactory().use { + val provider = createProvider() + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + addRemoteReceiver(manager, room) + + provider.setSharedKey("rotated", 9) + verify(senderCryptor).keyIndex = 9 + verify(receiverCryptor, never()).keyIndex = 9 + } + } + + @Test + fun cleanupStopsRestamping() { + mockedFactory().use { + val provider = createProvider() + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + + manager.cleanup() + provider.setSharedKey("after-cleanup", 6) + verify(senderCryptor, never()).keyIndex = 6 + } + } + + // --- Ratchet targets the slot senders use --- + + @Test + fun managerRatchetAdvancesTheCurrentSharedSlot() { + mockedFactory().use { + val provider = createProvider() + val (manager, _, _) = createManager(provider) + provider.setSharedKey("rotated", 2) + + // Before the fix this ratcheted slot 0 (the interface default) while + // senders kept encrypting with slot 2. + manager.ratchetKey() + verify(rtcKeyProvider).ratchetSharedKey(2) + verify(rtcKeyProvider, never()).ratchetSharedKey(0) + } + } + + @Test + fun ratchetWithExplicitOrDefaultIndexIsUnchanged() { + mockedFactory().use { + val provider = createProvider() + provider.setSharedKey("rotated", 3) + + // The interface default (0) and explicit indexes keep their meaning. + provider.ratchetSharedKey() + verify(rtcKeyProvider).ratchetSharedKey(0) + provider.ratchetSharedKey(5) + verify(rtcKeyProvider).ratchetSharedKey(5) + } + } + + // --- Concurrency --- + + @Test + fun rotationDuringSenderSetupIsNotOverwrittenByStaleIndex() { + mockedFactory().use { + val base = createProvider() + base.setSharedKey("key", 2) + val provider = InterleavingKeyProvider(base) + val stamped = Collections.synchronizedList(mutableListOf()) + doAnswer { invocation -> + stamped.add(invocation.getArgument(0)) + null + }.whenever(senderCryptor).keyIndex = any() + + val (manager, room, localParticipant) = createManager(provider) + + // The sender has read index 2 but not stamped it yet; a rotation to 3 + // runs its re-stamp on another thread. Unsynchronized setup let that + // re-stamp land first and then overwrote it with the stale 2. + val rotation = Thread { base.setSharedKey("rotated", 3) } + provider.onLatestRead = { + rotation.start() + // Give the re-stamp time to run if setup doesn't hold the lock; with + // the lock held it blocks until setup finishes. + rotation.join(300) + } + addLocalSender(manager, room, localParticipant) + rotation.join(TimeUnit.SECONDS.toMillis(5)) + + assertEquals(3, stamped.last()) + } + } + + @Test + fun removingASenderDuringRotationNeverTouchesTheDisposedCryptor() { + mockedFactory().use { + val provider = createProvider() + val (manager, room, localParticipant) = createManager(provider) + addLocalSender(manager, room, localParticipant) + // A rotation arriving right after dispose: before the fix the disposed + // cryptor was still in the map, so the re-stamp hit it and threw. + val rotated = CountDownLatch(1) + val callsAfterDispose = throwWhenDisposed(senderCryptor) { + provider.setSharedKey("rotated", 5) + rotated.countDown() + } + val publication = mock() + whenever(publication.sid).thenReturn("sender-sid") + manager.removePublishedTrack(mock(), publication, localParticipant, room) + + assertTrue(rotated.await(5, TimeUnit.SECONDS)) + assertTrue("calls after dispose: $callsAfterDispose", callsAfterDispose.isEmpty()) + } + } + + @Test + fun removingAReceiverDuringAnEnabledToggleNeverTouchesTheDisposedCryptor() { + mockedFactory().use { + val provider = createProvider() + val (manager, room, _) = createManager(provider) + addRemoteReceiver(manager, room) + // The enabled toggle walks every cryptor, receivers included. + val toggled = CountDownLatch(1) + val callsAfterDispose = throwWhenDisposed(receiverCryptor) { + manager.enabled = false + toggled.countDown() + } + val participant = mock() + whenever(participant.identity).thenReturn(Participant.Identity(REMOTE)) + val publication = mock() + whenever(publication.sid).thenReturn("receiver-sid") + manager.removeSubscribedTrack(mock(), publication, participant, room) + + assertTrue(toggled.await(5, TimeUnit.SECONDS)) + assertTrue("calls after dispose: $callsAfterDispose", callsAfterDispose.isEmpty()) + } + } + + private companion object { + const val LOCAL = "local" + const val REMOTE = "remote" + } +}