diff --git a/.changeset/sender-key-index-observer.md b/.changeset/sender-key-index-observer.md new file mode 100644 index 000000000..fc750d7c1 --- /dev/null +++ b/.changeset/sender-key-index-observer.md @@ -0,0 +1,5 @@ +--- +"client-sdk-android": patch +--- + +Media frame cryptors now follow the key provider's current key index, matching the JavaScript and Swift SDKs. `BaseKeyProvider` implements the new `KeyIndexObservable` contract: installing a shared key moves the current index, `setCurrentKeyIndex` re-points live senders, and `getLatestKeyIndex` returns the current index. Custom `KeyProvider` implementations can opt into live re-pointing by implementing `KeyIndexObservable`. Behavior change: in non-shared key mode `setKey` no longer moves the sender index — the key may belong to a remote participant — use `setCurrentKeyIndex` to switch the local one. diff --git a/livekit-android-sdk/detekt-baseline-release.xml b/livekit-android-sdk/detekt-baseline-release.xml index 026aca043..1f8a4c1ac 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..a8520196e 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,14 +182,21 @@ 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() } + /** The index local senders stamp with: the observable provider's + * [KeyIndexObservable.currentKeyIndex] when it opts in, else the legacy + * latest-index lookup. */ + private fun localSenderKeyIndex(participantId: String): Int = + (keyProvider as? KeyIndexObservable)?.currentKeyIndex + ?: keyProvider.getLatestKeyIndex(participantId) + private fun e2eeStateFromFrameCryptoState(state: FrameCryptionState?): E2EEState { return when (state) { FrameCryptionState.NEW -> E2EEState.NEW @@ -205,9 +219,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 = localSenderKeyIndex(participantId.value) + } return frameCryptor } @@ -220,9 +238,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 } @@ -242,14 +264,42 @@ constructor( LKLog.d { "ratchetSharedKey: newKey: $newKey" } } + /** + * Re-stamps the frame cryptors of every track the local participant has + * already published with the provider's latest key index. Runs on the + * RTC thread like all other frame cryptor calls. + */ + internal fun setSenderKeyIndex(keyIndex: Int) { + executeOnRTCThread(rtcThreadToken) { + val localIdentity = room?.localParticipant?.identity ?: return@executeOnRTCThread + synchronized(frameCryptors) { + for ((key, frameCryptor) in frameCryptors) { + if (key.second == localIdentity) { + frameCryptor.keyIndex = keyIndex + } + } + } + } + } + + private fun observeKeyIndex() { + (keyProvider as? KeyIndexObservable)?.addKeyIndexObserver(this) { index -> + setSenderKeyIndex(index) + } + } + 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() } @@ -257,7 +307,7 @@ constructor( val participantId = room?.localParticipant?.identity ?: Participant.Identity("") return dataPacketCryptorManager.encrypt( participantId, - keyIndex = keyProvider.getLatestKeyIndex(participantId.value), + keyIndex = localSenderKeyIndex(participantId.value), payload = byteArray, ) } 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 a09d05779..2affecd3e 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 + +// Matches libwebrtc's MAX_KEYRING_SIZE — the native provider caps the ring here. +internal const val maxKeyRingSize = 256 internal const val defaultDiscardFrameWhenCryptorNotReady = false internal val defaultKeyDerivationAlgorithm = FrameCryptorKeyDerivationAlgorithm.PBKDF2 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 55dc57abd..405d13d3a 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 @@ -42,6 +42,34 @@ interface KeyProvider { var enableSharedKey: Boolean } +/** + * Implemented by [KeyProvider]s that track the key index the local + * participant encrypts with and can push changes to observers. + * + * [E2EEManager] subscribes so the frame cryptors of media tracks that are + * already published get re-stamped whenever the index changes. Receivers + * are unaffected: they read the index from each incoming frame. + */ +interface KeyIndexObservable { + + /** + * The key index the local participant encrypts with. + */ + val currentKeyIndex: Int + + /** + * Registers [observer] under [owner]; [removeKeyIndexObserver] with the + * same owner detaches it. The observer is invoked with the latest index + * on every change and may be called from any thread. + */ + fun addKeyIndexObserver(owner: Any, observer: (keyIndex: Int) -> Unit) + + /** + * Detaches the observer previously registered under [owner]. + */ + fun removeKeyIndexObserver(owner: Any) +} + class BaseKeyProvider( ratchetSalt: String = defaultRatchetSalt, uncryptedMagicBytes: String = defaultMagicBytes, @@ -51,9 +79,23 @@ class BaseKeyProvider( keyRingSize: Int = defaultKeyRingSize, discardFrameWhenCryptorNotReady: Boolean = defaultDiscardFrameWhenCryptorNotReady, keyDerivationAlgorithm: FrameCryptorKeyDerivationAlgorithm = defaultKeyDerivationAlgorithm, -) : KeyProvider { +) : KeyProvider, KeyIndexObservable { + + // The native provider clamps the requested ring size the same way + // (<= 0 falls back to the default, > 256 caps at 256); the local index + // must wrap by the effective size, not the requested one. + private val effectiveKeyRingSize: Int = + if (keyRingSize <= 0) defaultKeyRingSize else minOf(keyRingSize, maxKeyRingSize) + + private val keyIndexStateLock = Any() + private val keyIndexDispatchLock = Any() + private val keyIndexObservers = mutableMapOf Unit>() + + @Volatile + private var _currentKeyIndex: Int = 0 - private val latestSetIndex = mutableMapOf() + override val currentKeyIndex: Int + get() = _currentKeyIndex override val rtcKeyProvider: FrameCryptorKeyProvider = FrameCryptorFactory.createFrameCryptorKeyProvider( enableSharedKey, @@ -66,8 +108,24 @@ class BaseKeyProvider( keyDerivationAlgorithm, ) + /** + * Installs the shared key at [keyIndex] and makes it the local encryption + * index. A negative [keyIndex] installs into the current slot without + * moving it. + */ override fun setSharedKey(key: String, keyIndex: Int?): Boolean { - return rtcKeyProvider.setSharedKey(keyIndex ?: 0, key.toByteArray()) + // Resolve a negative index against this provider's current index, not + // the native handler's — the native pointer only moves on key installs + // and can diverge from this one after setCurrentKeyIndex. + val index = keyIndex ?: 0 + return rtcKeyProvider.setSharedKey( + if (index >= 0) index else currentKeyIndex, + key.toByteArray(), + ).also { succeeded -> + if (succeeded && index >= 0) { + setCurrentKeyIndex(index) + } + } } override fun ratchetSharedKey(keyIndex: Int?): ByteArray { @@ -94,10 +152,7 @@ class BaseKeyProvider( return } - val keyIndex = keyIndex ?: 0 - latestSetIndex[participantId] = keyIndex - - rtcKeyProvider.setKey(participantId, keyIndex, key.toByteArray()) + rtcKeyProvider.setKey(participantId, keyIndex ?: 0, key.toByteArray()) } override fun ratchetKey(participantId: String, keyIndex: Int?): ByteArray { @@ -112,7 +167,43 @@ class BaseKeyProvider( rtcKeyProvider.setSifTrailer(trailer) } + /** + * Switches the local participant's encryption to the key at [keyIndex] + * (modulo the effective key ring size: the default for a size <= 0, + * capped at 256, matching the native provider). + * + * Takes effect immediately for the media tracks already published and + * for every data packet sent afterwards. Receivers are unaffected: they + * read the index from each frame. + */ + fun setCurrentKeyIndex(keyIndex: Int) { + val observers = synchronized(keyIndexStateLock) { + _currentKeyIndex = keyIndex.mod(effectiveKeyRingSize) + keyIndexObservers.values.toList() + } + // Dispatch is serialized and each pass re-reads the newest index, + // so overlapping rotations can't leave senders on a stale index. + synchronized(keyIndexDispatchLock) { + val latest = _currentKeyIndex + observers.forEach { it(latest) } + } + } + + /** + * The key index outgoing media frames and data packets are stamped with. + * In non-shared key mode [setKey] does not move it — the key may belong + * to a remote participant — so switch the local one with + * [setCurrentKeyIndex]. + */ override fun getLatestKeyIndex(participantId: String): Int { - return latestSetIndex[participantId] ?: 0 + return currentKeyIndex + } + + override fun addKeyIndexObserver(owner: Any, observer: (keyIndex: Int) -> Unit) { + synchronized(keyIndexStateLock) { keyIndexObservers[owner] = observer } + } + + override fun removeKeyIndexObserver(owner: Any) { + synchronized(keyIndexStateLock) { keyIndexObservers.remove(owner) } } } 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 ebb9de898..de77cff77 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 @@ -332,6 +332,20 @@ constructor( * Options for end-to-end encryption. Must be setup prior to [connect]. * * If null, e2ee will be disabled. + * + * 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: + * keyProvider.setSharedKey("next-secret", keyIndex = 1) + * keyProvider.setCurrentKeyIndex(1) // already-published senders follow + * ``` + * 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..d0f29acef --- /dev/null +++ b/livekit-android-test/src/test/java/io/livekit/android/e2ee/FrameCryptorKeyIndexTest.kt @@ -0,0 +1,465 @@ +/* + * 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.assertTrue +import org.junit.Test +import org.mockito.Mockito.mockStatic +import org.mockito.Mockito.never +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 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(), + ) + }.thenReturn(rtcKeyProvider) + `when` { + FrameCryptorFactory.createFrameCryptorForRtpSender(any(), any(), any(), any(), any()) + }.thenReturn(senderCryptor) + `when` { + FrameCryptorFactory.createFrameCryptorForRtpReceiver(any(), any(), any(), any(), any()) + }.thenReturn(receiverCryptor) + } + + private fun createProvider(sharedKey: Boolean = true): BaseKeyProvider { + whenever(rtcKeyProvider.setSharedKey(any(), any())).thenReturn(true) + 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): FrameCryptor { + 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("sender-sid") + + manager.addPublishedTrack(track, publication, participant, room) + return senderCryptor + } + + /** 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 + + // Sender setup reads whichever path E2EEManager takes; fire the + // interleave on either so the hook tracks the real read. + private fun fireOnce(index: Int): Int { + onLatestRead?.let { + onLatestRead = null + it() + } + return index + } + + override val currentKeyIndex: Int + get() = fireOnce(base.currentKeyIndex) + + override fun getLatestKeyIndex(participantId: String): Int = + fireOnce(base.getLatestKeyIndex(participantId)) + } + + /** 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 + } + + private fun addRemoteReceiver(manager: E2EEManager, room: Room): FrameCryptor { + 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) + return receiverCryptor + } + + @Test + fun sharedKeyInstallMovesCurrentKeyIndex() { + mockedFactory().use { + val provider = createProvider() + provider.setSharedKey("key", 3) + assertEquals(3, provider.currentKeyIndex) + assertEquals(3, provider.getLatestKeyIndex("anyone")) + } + } + + @Test + fun setCurrentKeyIndexWrapsModuloKeyRingSize() { + mockedFactory().use { + val provider = createProvider() + provider.setCurrentKeyIndex(20) + assertEquals(20 % 16, provider.currentKeyIndex) + } + } + + @Test + fun nonSharedSetKeyDoesNotMoveCurrentKeyIndex() { + mockedFactory().use { + val provider = createProvider(sharedKey = false) + // A remote participant's key install cannot redirect the local sender index. + provider.setKey("key", "remote", 7) + assertEquals(0, provider.currentKeyIndex) + assertEquals(0, provider.getLatestKeyIndex("remote")) + } + } + + @Test + fun observerSeesLatestIndexAndRemovalStopsCallbacks() { + mockedFactory().use { + val provider = createProvider() + val seen = mutableListOf() + provider.addKeyIndexObserver(this) { seen.add(it) } + + provider.setCurrentKeyIndex(3) + provider.setCurrentKeyIndex(5) + assertEquals(listOf(3, 5), seen) + + provider.removeKeyIndexObserver(this) + provider.setCurrentKeyIndex(7) + assertEquals(listOf(3, 5), seen) + } + } + + @Test + fun newSendersAreStampedWithCurrentKeyIndex() { + 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 existingSendersFollowKeyIndexChanges() { + 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 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 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.setCurrentKeyIndex(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.setCurrentKeyIndex(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()) + } + } + + /** An observable provider whose legacy latest-index lookup disagrees with + * [currentKeyIndex] — the case [E2EEManager.localSenderKeyIndex] exists for. */ + private class DivergentProvider(private val base: BaseKeyProvider) : + KeyProvider by base, + KeyIndexObservable by base { + override val currentKeyIndex: Int + get() = 7 + } + + // 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() {} + } + + @Test + fun negativeSharedKeyIndexInstallsWithoutMovingCurrentKeyIndex() { + mockedFactory().use { + val provider = createProvider() + provider.setSharedKey("key-a", 5) + assertEquals(5, provider.currentKeyIndex) + val seen = mutableListOf() + provider.addKeyIndexObserver(this) { seen.add(it) } + + // A negative index installs into the current slot without moving + // it, so the stamp pointer stays put. + provider.setSharedKey("key-b", -1) + assertEquals(5, provider.currentKeyIndex) + assertTrue("no re-stamp for an unmoved index: $seen", seen.isEmpty()) + verify(rtcKeyProvider).setSharedKey(eq(5), eq("key-b".toByteArray())) + } + } + + @Test + fun negativeSharedKeyIndexInstallsAtKotlinCurrentSlotAfterSwitch() { + mockedFactory().use { + val provider = createProvider() + provider.setSharedKey("k0", 0) + provider.setSharedKey("k1", 1) + + // The native handler's pointer stays on the last installed slot; + // only the local index moves back. A negative install must target + // the slot senders actually use, not the stale native pointer. + provider.setCurrentKeyIndex(0) + provider.setSharedKey("replacement", -1) + + verify(rtcKeyProvider).setSharedKey(eq(0), eq("replacement".toByteArray())) + assertEquals(0, provider.currentKeyIndex) + } + } + + @Test + fun zeroKeyRingSizeFallsBackToDefaultRing() { + mockedFactory().use { + whenever(rtcKeyProvider.setSharedKey(any(), any())).thenReturn(true) + val provider = BaseKeyProvider(keyRingSize = 0) + + // Native clamps a non-positive size to the default ring (16), so the + // local index must wrap by that, not divide by zero. + provider.setSharedKey("key", 2) + assertEquals(2, provider.currentKeyIndex) + + provider.setCurrentKeyIndex(17) + assertEquals(17 % 16, provider.currentKeyIndex) + } + } + + @Test + fun oversizedKeyRingSizeCapsAtMax() { + mockedFactory().use { + val provider = BaseKeyProvider(keyRingSize = 300) + + // Native caps the ring at 256; the local index wraps by the capped size. + provider.setCurrentKeyIndex(257) + assertEquals(257 % 256, provider.currentKeyIndex) + } + } + + @Test + fun observableProvidersStampWithCurrentKeyIndex() { + mockedFactory().use { + val base = createProvider() + val provider = DivergentProvider(base) + val (manager, room, localParticipant) = createManager(provider) + + // getLatestKeyIndex() delegates to base and returns 0; the observable + // contract says new senders must use currentKeyIndex (7). + addLocalSender(manager, room, localParticipant) + verify(senderCryptor).keyIndex = 7 + + // Data packets take the same path. + manager.encrypt(byteArrayOf(1, 2, 3)) + assertEquals(7, dataPacketCryptorManager.lastEncryptKeyIndex) + + // Receivers are a remote participant's cryptors: they keep the + // per-participant lookup, not the local sender index. + addRemoteReceiver(manager, room) + verify(receiverCryptor).keyIndex = 0 + } + } +}