Skip to content

Follow key provider key index on media frame cryptors - #1042

Open
tangowhisky-dev wants to merge 1 commit into
livekit:mainfrom
tangowhisky-dev:e2ee-sender-key-index-observer
Open

tangowhisky-dev wants to merge 1 commit into
livekit:mainfrom
tangowhisky-dev:e2ee-sender-key-index-observer

Conversation

@tangowhisky-dev

@tangowhisky-dev tangowhisky-dev commented Oct 22, 2026 •

Copy link
Copy Markdown

Supersedes #1039 — ports the approach merged in client-sdk-swift#1157 to Android.

Problem

addRtpSender stamps a sender's FrameCryptor.keyIndex once at creation and never updates it. Apps that rotate keys into different key-ring slots (e.g. per-epoch MLS key rings in E2EE deployments) can update live data packets via setSharedKey(key, index), but media senders keep stamping the old index — receivers hit MISSING_KEY and drop frames. There is no public API to re-point live senders.

Approach

Mirrors the Swift design rather than adding a setKeyIndex(participant) API (whose identity parameter let a remote identity redirect local encryption — the review concern on the earlier Swift PR #1156).

KeyIndexObservable — new opt-in contract for KeyProviders that track the local encryption index:

interface KeyIndexObservable {
    val currentKeyIndex: Int
    fun addKeyIndexObserver(owner: Any, observer: (keyIndex: Int) -> Unit)
    fun removeKeyIndexObserver(owner: Any)
}

BaseKeyProvider implements it — currentKeyIndex is the single source of truth:

  • setSharedKey(key, index) moves it (parity with JS SDK setSharedKey behavior merged in client-sdk-js#1830/#1831)
  • New setCurrentKeyIndex(index) exposes it directly (ring-size modulo)
  • getLatestKeyIndex() returns it — senders stamp at creation, data packets pick it up per-send
  • Observer dispatch is serialized and re-reads the latest index, so overlapping rotations can't leave senders stale

E2EEManager subscribes internally and re-stamps the frame cryptors of already-published local tracks on the RTC thread (via executeOnRTCThread, honoring the SDK's threading rule). Receivers are untouched — they read the index from each frame's trailer.

Behavior change

In non-shared key mode, setKey() no longer moves the sender index — the key may belong to a remote participant, so it must not redirect local encryption. Apps switching the local index should call setCurrentKeyIndex(). This matches the Swift change.

Custom KeyProvider implementations (e.g. ones that bypass BaseKeyProvider to hand raw key bytes to the RTC provider) opt into live re-pointing by implementing KeyIndexObservable.

Test plan

  • FrameCryptorKeyIndexTest (new, 7 tests): shared-key install moves index, setCurrentKeyIndex modulo wrap, non-shared setKey does not move index, observer add/remove, new senders stamp current index, existing senders follow changes, receivers not re-stamped
  • Existing e2ee tests pass (DataPacketCryptorMockE2ETest, DataTrackCryptorTest)
  • :livekit-android-sdk:detektRelease, spotlessCheck clean

@changeset-bot

changeset-bot Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 57a1cad

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
client-sdk-android Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

devin-ai-integration[bot]

This comment was marked as resolved.

@tangowhisky-dev

Copy link
Copy Markdown
Author

@davidliu can you please look into this. Merging it would remove issues associated with E2EE key rotations.
Thanks

@xianshijing-lk

Copy link
Copy Markdown
Contributor

@changt , could you please help review this PR ?

@tangowhisky-dev

Copy link
Copy Markdown
Author

Thanks, good catch. The initial stamp in addRtpSender was put → read latest index → set as separate steps, so a rotation landing between the read and the set could overwrite the re-stamped index with a stale one. Fixed in the latest commit:

  • addRtpSender / addRtpReceiver: insert, isEnabled and keyIndex now run inside synchronized(frameCryptors), the monitor the re-stamp loop holds, so either ordering ends on the latest index. Receivers read the index from the frame trailer, so the receiver change is for consistency only.
  • While there, I fixed a related window in removePublishedTrack / removeSubscribedTrack: they disposed a cryptor before removing it from the map, so a concurrent loop (the new re-stamp, the enabled toggle, or cleanup()) could call into a disposed FrameCryptor, which throws IllegalStateException. They now remove first and dispose only what they removed. That window predates this PR, but the new re-stamp loop makes it easier to hit.
  • The room read in setSenderKeyIndex now happens on the RTC thread.

I added three tests to FrameCryptorKeyIndexTest, covering the stamp race and use-after-dispose on both the sender and receiver paths — verified by mutation: all three fail against the unfixed E2EEManager.

Could a maintainer also approve the CI workflows for this fork PR? No checks have run on it yet.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@tangowhisky-dev

Copy link
Copy Markdown
Author

@changt can you please relook into proposed changes. This one is becoming a blocker for my app as it adversly affects the UX.
Thanks.

@davidliu davidliu left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a pretty big breaking change that will fail silently for upgraders. At the very minimum, it needs a minor version changeset, ideally with an example code upgrade path.


However, I think the fix for the actual bug, already-published senders never getting re-stamped, is a lot simpler than this, and doesn't need the index model to change.

Today latestSetIndex is already keyed by participant and E2EEManager only ever reads the local identity's entry, so setKey(key, localIdentity, n) moves the local sender and a remote participant's install can't. Swift had a single currentKeyIndex that any setKey could redirect, and carrying that behavior over here doesn't make sense here. What's missing is only the push: when the local index is written, tell the manager so it can update live senders. Something like:

  1. Keep latestSetIndex as is.
  2. Have setKey notify observers with (participantId, index) after it writes the map entry.
  3. Have setSharedKey notify with (null, index) after a successful install.
  4. In E2EEManager, re-stamp the local sender cryptors only when the notified id is null or matches room.localParticipant.identity.

This gives the live re-stamp in both modes with no behavior change for existing non-shared apps, and should cut down on the extra code needed. The changeset gets to stay a plain patch. The synchronization and remove-before-dispose fixes in E2EEManager and most of the new tests can carry over as-is.

@tangowhisky-dev
tangowhisky-dev force-pushed the e2ee-sender-key-index-observer branch from 0fdcffa to 17b95e1 Compare November 23, 2026 16:38
@tangowhisky-dev

tangowhisky-dev commented Nov 23, 2026 •

Copy link
Copy Markdown
Author

Thanks, agreed. I've reworked the PR along those lines and force-pushed it as a single commit on top of current main (including #1061's keySize).

What changed

latestSetIndex stays per-participant, so setKey(key, localIdentity, n) moves the local sender and a remote participant's install never does. Existing non-shared apps see no behavior change for valid indexes. The single currentKeyIndex and setCurrentKeyIndex are gone.
KeyIndexObservable now notifies (participantId, keyIndex): setKey sends the participant's id after writing the map, and setSharedKey sends null after a successful non-negative install.
E2EEManager re-stamps local sender cryptors only when the id is null or the local identity. It re-reads getLatestKeyIndex(localIdentity) on the RTC thread rather than using the notified value, so a re-stamp queued behind a newer one can't apply a stale index.
The locking around sender/receiver setup and remove-before-dispose carried over unchanged, with their tests.
The changeset is back to a patch.

Two additions beyond the suggestion, both needed for the shared-key case:

Senders created after a rotation. setSharedKey never wrote latestSetIndex, so in shared mode getLatestKeyIndex() always returned 0. Re-stamping fixes tracks that are already published, but a track published after setSharedKey(key, 1) (and every data packet) would still have used slot 0. BaseKeyProvider now records the installed shared slot, and getLatestKeyIndex returns it when enableSharedKey is on.
Ratchet slot. E2EEManager.ratchetKey() called ratchetSharedKey() with the default index 0, which advanced slot 0 while senders encrypted with slot 1. It now passes the slot senders use.

Index handling, matched to libwebrtc. Once indexes are pushed to live senders, the recorded index has to be exactly what native writes:

A non-negative index is recorded as index % keyRingSize, with the ring size clamped like native (≤ 0 → default, > 256 → 256). Native wraps on install, but GetKeySet does no bounds check, so stamping the raw index would read past the key ring.
A negative index records and re-stamps nothing, since native installs it into the current slot without moving it.
Native's SetSharedKey / RatchetSharedKey fan out to every participant handler with the given index, and each resolves -1 to its own current slot. So shared operations resolve a null or negative index to the recorded shared slot before the native call. Per-participant operations reach a single handler and still pass -1 through, which follows that participant's own current slot.
Explicit indexes and the interface defaults keep their meaning.

Tests: FrameCryptorKeyIndexTest has 23 cases. They cover:

shared and per-participant rotation
senders published after a rotation, plus data packets
remote installs not re-stamping local senders
failed and negative installs
ring-size wrap and clamp
shared operations never reaching native with -1
cleanup
the ratchet slot
the setup race and use-after-dispose

spotlessCheck, livekit-android-sdk:detektRelease and FrameCryptorKeyIndexTest pass locally.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

Media frame cryptors were stamped with a key index once, at sender
creation, so after a key rotation already-published 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, because getLatestKeyIndex() only knew
per-participant (setKey) indexes.

KeyProvider
- New opt-in KeyIndexObservable: observers are told (participantId,
  keyIndex) when a key index is written; null means the shared key.
- BaseKeyProvider keeps the per-participant latestSetIndex model (now a
  ConcurrentHashMap), so setKey(key, localIdentity, n) moves the local
  sender and a remote participant's install never does.
- setSharedKey records the installed shared slot; getLatestKeyIndex
  returns it in shared-key mode.
- Recorded indexes are the slot libwebrtc actually writes: a
  non-negative index wraps by the effective key ring size (clamped like
  native: <= 0 -> default, > 256 -> 256), and a negative index records
  nothing, so senders are never stamped with a slot that doesn't exist.
- Native fans shared installs and ratchets out to every participant
  handler with the given index, and each resolves -1 to its own current
  slot, so shared operations resolve a null or negative index to the
  recorded shared slot first. Per-participant operations reach one
  handler and pass -1 through for implicit ratchets / negative installs.

E2EEManager
- Re-stamps the local participant's sender cryptors when the notified
  id is null or the local identity, reading the index on the RTC thread.
- ratchetKey() ratchets the slot senders encrypt with, not slot 0.
- Sender/receiver setup inserts and stamps under the frameCryptors
  monitor; removePublishedTrack/removeSubscribedTrack remove the map
  entry before disposing.

Tests: FrameCryptorKeyIndexTest (23 cases).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UsvujjBPaU4EHCGdR6rXK4
@tangowhisky-dev
tangowhisky-dev force-pushed the e2ee-sender-key-index-observer branch from 8a29111 to 57a1cad Compare November 23, 2026 17:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants