Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/sender-key-index-observer.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions livekit-android-sdk/detekt-baseline-release.xml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
<ID>SwallowedException:TextureViewRenderer.kt$TextureViewRenderer$e: NotFoundException</ID>
<ID>TooManyFunctions:CommunicationWorkaround.kt$CommunicationWorkaroundImpl : CommunicationWorkaround</ID>
<ID>TooManyFunctions:E2EEManager.kt$E2EEManager</ID>
<ID>TooManyFunctions:KeyProvider.kt$BaseKeyProvider : KeyProviderKeyIndexObservable</ID>
<ID>TooManyFunctions:LKLog.kt$LKLog$Companion</ID>
<ID>TooManyFunctions:LocalParticipant.kt$LocalParticipant : ParticipantOutgoingDataStreamManagerRpcManager</ID>
<ID>TooManyFunctions:LocalVideoTrack.kt$LocalVideoTrack : VideoTrack</ID>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -40,16 +42,18 @@ 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
constructor(
@Assisted val keyProvider: KeyProvider,
val peerConnectionFactory: PeerConnectionFactory,
dataPacketCryptorManagerFactory: DataPacketCryptorManager.Factory,
private val rtcThreadToken: RTCThreadToken,
) {
private var room: Room? = null
private val frameCryptors = mutableMapOf<Pair<String, Participant.Identity>, FrameCryptor>()
private val frameCryptors = Collections.synchronizedMap(mutableMapOf<Pair<String, Participant.Identity>, FrameCryptor>())
private var algorithm: FrameCryptorAlgorithm = FrameCryptorAlgorithm.AES_GCM
private lateinit var emitEvent: (roomEvent: RoomEvent) -> Unit?

Expand All @@ -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
}
}
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}

Expand All @@ -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
}

Expand All @@ -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
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
}
}
}
}
}

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()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -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<String, Int>()

private val latestSetIndex = mutableMapOf<String, Int>()
@Volatile
private var sharedKeyIndex: Int = 0

private val keyIndexObservers = ConcurrentHashMap<Any, (String?, Int) -> Unit>()

override val rtcKeyProvider: FrameCryptorKeyProvider = FrameCryptorFactory.createFrameCryptorKeyProvider(
enableSharedKey,
Expand All @@ -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)
}
Expand All @@ -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 {
Expand All @@ -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
}
}
Loading
Loading