import { afterEach, describe, expect, it, vitest } from 'vitest'; import { appendPacketTrailer, extractPacketTrailer } from '../../frameMetadata/frameMetadata'; import type { FrameMetadataPublishOptions } from '../../frameMetadata/types'; import { workerLogger } from '../../logger'; import type { VideoCodec } from '../../room/track/options'; import type { NonSharedUint8Array } from '../../type-polyfills/non-shared-typed-arrays'; import { subscribeToEvents } from '../../utils/subscribeToEvents'; import { IV_LENGTH, KEY_PROVIDER_DEFAULTS } from '../constants'; import { CryptorErrorReason } from '../errors'; import { type CryptorCallbacks, CryptorEvent } from '../events'; import type { KeyProviderOptions } from '../types'; import { createKeyMaterialFromString } from '../utils'; import { FrameCryptor, isFrameServerInjected, setLocalEncryptionEnabled } from './FrameCryptor'; import { ParticipantKeyHandler } from './ParticipantKeyHandler'; import { parseH264IdrPpsId } from './naluUtils'; function mockEncryptedRTCEncodedVideoFrame(keyIndex: number): RTCEncodedVideoFrame { const trailer = mockFrameTrailer(keyIndex); const data = new Uint8Array(trailer.length + 10); data.set(trailer, 10); return mockRTCEncodedVideoFrame(data); } function mockRTCEncodedVideoFrame(data: NonSharedUint8Array): RTCEncodedVideoFrame { return { data: data.buffer, timestamp: vitest.getMockedSystemTime()?.getTime() ?? 0, type: 'key', getMetadata(): RTCEncodedVideoFrameMetadata { return {}; }, }; } function mockFrameTrailer(keyIndex: number): NonSharedUint8Array { const frameTrailer = new Uint8Array(2); frameTrailer[0] = IV_LENGTH; frameTrailer[1] = keyIndex; return frameTrailer; } class TestUnderlyingSource implements UnderlyingSource { controller: ReadableStreamController; start(controller: ReadableStreamController): void { this.controller = controller; } write(chunk: T): void { this.controller.enqueue(chunk as any); } close(): void { this.controller.close(); } } class TestUnderlyingSink implements UnderlyingSink { public chunks: T[] = []; write(chunk: T): void { this.chunks.push(chunk); } } function prepareParticipantTestDecoder( participantIdentity: string, partialKeyProviderOptions: Partial, ) { return prepareParticipantTest('decode', participantIdentity, partialKeyProviderOptions); } function prepareParticipantTestEncoder( participantIdentity: string, partialKeyProviderOptions: Partial, packetTrailer?: FrameMetadataPublishOptions, codec?: VideoCodec, ) { return prepareParticipantTest( 'encode', participantIdentity, partialKeyProviderOptions, packetTrailer, codec, ); } function prepareParticipantTest( mode: 'encode' | 'decode', participantIdentity: string, partialKeyProviderOptions: Partial, packetTrailer?: FrameMetadataPublishOptions, codec?: VideoCodec, ): { keys: ParticipantKeyHandler; cryptor: FrameCryptor; input: TestUnderlyingSource; output: TestUnderlyingSink; } { const keyProviderOptions = { ...KEY_PROVIDER_DEFAULTS, ...partialKeyProviderOptions }; const keys = new ParticipantKeyHandler(participantIdentity, keyProviderOptions); setLocalEncryptionEnabled(true); const cryptor = new FrameCryptor({ participantIdentity, keys, keyProviderOptions, sifTrailer: new Uint8Array(), }); cryptor.setEncrypted(true); const input = new TestUnderlyingSource(); const output = new TestUnderlyingSink(); cryptor.setupTransform( mode, new ReadableStream(input), new WritableStream(output), 'testTrack', codec, packetTrailer, ); return { keys, cryptor, input, output }; } describe('FrameCryptor', () => { const participantIdentity = 'testParticipant'; it('identifies server injected frame correctly', () => { const frameTrailer = new TextEncoder().encode('LKROCKS'); const frameData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, ...frameTrailer]).buffer; expect(isFrameServerInjected(frameData, frameTrailer)).toBe(true); }); it('identifies server non server injected frame correctly', () => { const frameTrailer = new TextEncoder().encode('LKROCKS'); const frameData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, ...frameTrailer, 10]); expect(isFrameServerInjected(frameData.buffer, frameTrailer)).toBe(false); frameData.fill(0); expect(isFrameServerInjected(frameData.buffer, frameTrailer)).toBe(false); }); describe('encode', () => { afterEach(() => { setLocalEncryptionEnabled(undefined); }); it('drops the frame and emits an error while the local state is unknown', async () => { // Create an encoder for the local participant const { cryptor, input, output } = prepareParticipantTestEncoder(participantIdentity, {}); const cryptorEvents = subscribeToEvents(cryptor, [CryptorEvent.Error]); // The app did not say yet whether the local participant encrypts setLocalEncryptionEnabled(undefined); // Send a frame input.write(mockRTCEncodedVideoFrame(new Uint8Array(16))); // The cryptor reports an error const error = await cryptorEvents.waitFor(CryptorEvent.Error); expect(error.reason).toStrictEqual(CryptorErrorReason.InternalError); // The frame was not sent expect(output.chunks).toStrictEqual([]); }); it('encrypts after the participant was unset', async () => { // Create an encoder for the local participant, with a key const { cryptor, keys, input, output } = prepareParticipantTestEncoder( participantIdentity, {}, ); await keys.setKey(await createKeyMaterialFromString('key1'), 1); // Unset the participant of the cryptor cryptor.unsetParticipant(); // Send a frame of 16 bytes input.write(mockRTCEncodedVideoFrame(new Uint8Array(16))); await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); // The sent frame is longer, because encryption appends the IV and the trailer expect(output.chunks[0].data.byteLength).toBeGreaterThan(16); }); it('passthrough if participant encryption disabled', async () => { vitest.useFakeTimers(); try { const { input, output } = prepareParticipantTestEncoder(participantIdentity, {}); // disable encryption for the local participant setLocalEncryptionEnabled(false); const frame = mockRTCEncodedVideoFrame(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); input.write(frame); await vitest.advanceTimersToNextTimerAsync(); expect(output.chunks).toEqual([frame]); } finally { vitest.useRealTimers(); } }); it('passthrough for empty frame', async () => { vitest.useFakeTimers(); try { const { input, output } = prepareParticipantTestEncoder(participantIdentity, {}); // empty frame const frame = mockRTCEncodedVideoFrame(new Uint8Array(0)); input.write(frame); await vitest.advanceTimersToNextTimerAsync(); expect(output.chunks).toEqual([frame]); } finally { vitest.useRealTimers(); } }); it('immediately drops frame and emits error if no key set', async () => { vitest.useFakeTimers(); try { const { cryptor, input, output } = prepareParticipantTestEncoder(participantIdentity, {}); const errorListener = vitest.fn(); cryptor.on(CryptorEvent.Error, errorListener); const frame = mockRTCEncodedVideoFrame(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); input.write(frame); await vitest.advanceTimersToNextTimerAsync(); expect(output.chunks).toEqual([]); expect(errorListener).toHaveBeenCalled(); } finally { vitest.useRealTimers(); } }); it('encrypts frame', async () => { vitest.useFakeTimers(); try { const { keys, input, output } = prepareParticipantTestEncoder(participantIdentity, {}); await keys.setKey(await createKeyMaterialFromString('key1'), 1); const plainTextData = new Uint8Array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ]); const frame = mockRTCEncodedVideoFrame(plainTextData); input.write(frame); await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); expect(output.chunks).toEqual([frame]); expect(frame.data.byteLength).toBeGreaterThan(16); // first bytes are unencrypted expect(new Uint8Array(frame.data.slice(0, 10))).toEqual(plainTextData.subarray(0, 10)); // remainder should not be the same expect(new Uint8Array(frame.data.slice(10, 16))).not.toEqual( plainTextData.subarray(10, 16), ); const frameTrailer = new Uint8Array(frame.data.slice(frame.data.byteLength - 2)); // IV length expect(frameTrailer[0]).toEqual(IV_LENGTH); // key index expect(frameTrailer[1]).toEqual(1); } finally { vitest.useRealTimers(); } }); describe('H.264 start codes (#2140)', () => { const sps = [0x67, 0x64, 0x00, 0x1f, 0xac, 0xd9]; const pps = [0x68, 0xee, 0x3c, 0xb0]; const idr = [0x65, 0x88, 0x84, 0x21, 0x43, 0x55, 0x66, 0x77]; async function encryptAndDecrypt(plainTextData: NonSharedUint8Array) { const encoder = prepareParticipantTestEncoder(participantIdentity, {}); await encoder.keys.setKey(await createKeyMaterialFromString('key1'), 1); const encrypted = mockRTCEncodedVideoFrame(plainTextData); encoder.input.write(encrypted); await vitest.waitFor(() => expect(encoder.output.chunks).toHaveLength(1)); const encryptedData = new Uint8Array(encrypted.data.slice(0)); const decoder = prepareParticipantTestDecoder(participantIdentity, {}); await decoder.keys.setKey(await createKeyMaterialFromString('key1'), 1); const decrypted = mockRTCEncodedVideoFrame(new Uint8Array(encryptedData)); decoder.input.write(decrypted); await vitest.waitFor(() => expect(decoder.output.chunks).toHaveLength(1)); return { encryptedData, decryptedData: new Uint8Array(decrypted.data) }; } it('rewrites 3-byte start codes in the unencrypted header to 4-byte start codes', async () => { const { encryptedData, decryptedData } = await encryptAndDecrypt( new Uint8Array([0, 0, 1, ...sps, 0, 0, 1, ...pps, 0, 0, 1, ...idr]), ); // The unencrypted header runs through the first 2 bytes of the slice NALU. const expectedHeader = [0, 0, 0, 1, ...sps, 0, 0, 0, 1, ...pps, 0, 0, 0, 1, 0x65, 0x88]; expect(Array.from(encryptedData.subarray(0, expectedHeader.length))).toEqual( expectedHeader, ); expect(Array.from(decryptedData)).toEqual([ 0, 0, 0, 1, ...sps, 0, 0, 0, 1, ...pps, 0, 0, 0, 1, ...idr, ]); }); it('rewrites a 3-byte start code on a delta frame', async () => { const pSlice = [0x41, 0x9a, 0x21, 0x43, 0x55, 0x66]; const { encryptedData, decryptedData } = await encryptAndDecrypt( new Uint8Array([0, 0, 1, ...pSlice]), ); expect(Array.from(encryptedData.subarray(0, 6))).toEqual([0, 0, 0, 1, 0x41, 0x9a]); expect(Array.from(decryptedData)).toEqual([0, 0, 0, 1, ...pSlice]); }); it('leaves 4-byte start codes in the unencrypted header unchanged', async () => { const plainTextData = [0, 0, 0, 1, ...sps, 0, 0, 0, 1, ...pps, 0, 0, 0, 1, ...idr]; const { encryptedData, decryptedData } = await encryptAndDecrypt( new Uint8Array(plainTextData), ); const expectedHeader = [0, 0, 0, 1, ...sps, 0, 0, 0, 1, ...pps, 0, 0, 0, 1, 0x65, 0x88]; expect(Array.from(encryptedData.subarray(0, expectedHeader.length))).toEqual( expectedHeader, ); expect(Array.from(decryptedData)).toEqual(plainTextData); }); it('keeps the PPS id readable when it lies past the unencrypted bytes (#2180)', async () => { // Intel Quick Sync IDR slice: the PPS id is the first encrypted bit, so a single // encryption leaves it at 0 only half the time. const qsvIdr = [0x65, 0x88, 0x80, 0x40, 0x87, 0x0a, 0x55, 0x66]; const plainTextData = [0, 0, 0, 1, ...sps, 0, 0, 0, 1, ...pps, 0, 0, 0, 1, ...qsvIdr]; const sliceStart = plainTextData.length - qsvIdr.length; for (let i = 0; i < 16; i++) { const { encryptedData, decryptedData } = await encryptAndDecrypt( new Uint8Array(plainTextData), ); expect(parseH264IdrPpsId(encryptedData.subarray(sliceStart))).toBe(0); expect(Array.from(decryptedData)).toEqual(plainTextData); } }); it('logs the frame bytes once when NALU processing fails', async () => { vitest.useFakeTimers(); const warn = vitest.spyOn(workerLogger, 'warn'); try { const { keys, input, output } = prepareParticipantTestEncoder( participantIdentity, {}, undefined, 'h264', ); await keys.setKey(await createKeyMaterialFromString('key1'), 1); // No start code at offset 0, so findNALUIndices throws 'byte stream contains // leading data' and the cryptor falls back to VP8 handling. input.write( mockRTCEncodedVideoFrame(new Uint8Array([9, 9, 9, 9, 1, 2, 3, 4, 5, 6, 7, 8])), ); await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); expect(warn).toHaveBeenCalledWith( 'NALU processing failed, falling back to VP8 handling', expect.objectContaining({ detectedCodec: 'h264', frameType: 'key', byteLength: 12, firstBytes: expect.stringMatching(/^09 09 09 09 /), }), ); // same payload type, so the once-per-tuple guard must suppress the second log input.write( mockRTCEncodedVideoFrame(new Uint8Array([8, 8, 8, 8, 1, 2, 3, 4, 5, 6, 7, 8])), ); await vitest.waitFor(() => expect(output.chunks).toHaveLength(2)); expect(warn).toHaveBeenCalledTimes(1); } finally { warn.mockRestore(); vitest.useRealTimers(); } }); it('appends packet trailer after encryption', async () => { vitest.useFakeTimers(); const now = new Date('2025-04-10T12:00:00.123Z'); vitest.setSystemTime(now); try { const { keys, input, output } = prepareParticipantTestEncoder( participantIdentity, {}, { timestamp: true, frameId: true }, ); await keys.setKey(await createKeyMaterialFromString('key1'), 1); const frame = mockRTCEncodedVideoFrame( new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), ); input.write(frame); await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); const extracted = extractPacketTrailer(frame.data); expect(extracted.metadata?.userTimestamp).toBeGreaterThanOrEqual( BigInt(now.getTime()) * BigInt(1000), ); expect(extracted.metadata?.frameId).toBe(1); const frameTrailer = new Uint8Array( extracted.data.buffer.slice(extracted.data.byteLength - 2), ); expect(frameTrailer[0]).toEqual(IV_LENGTH); expect(frameTrailer[1]).toEqual(1); } finally { vitest.useRealTimers(); } }); it('does not append packet trailer after encryption when no trailer features are enabled', async () => { vitest.useFakeTimers(); try { const { keys, input, output } = prepareParticipantTestEncoder( participantIdentity, {}, { timestamp: false, frameId: false }, ); await keys.setKey(await createKeyMaterialFromString('key1'), 1); const frame = mockRTCEncodedVideoFrame( new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), ); input.write(frame); await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); const extracted = extractPacketTrailer(frame.data); expect(extracted.metadata).toBeUndefined(); expect(extracted.data.byteLength).toBe(frame.data.byteLength); const frameTrailer = new Uint8Array(frame.data.slice(frame.data.byteLength - 2)); expect(frameTrailer[0]).toEqual(IV_LENGTH); expect(frameTrailer[1]).toEqual(1); } finally { vitest.useRealTimers(); } }); it('appends only timestamp packet trailer metadata after encryption', async () => { vitest.useFakeTimers(); const now = new Date('2025-04-10T12:00:00.123Z'); vitest.setSystemTime(now); try { const { keys, input, output } = prepareParticipantTestEncoder( participantIdentity, {}, { timestamp: true }, ); await keys.setKey(await createKeyMaterialFromString('key1'), 1); const frame = mockRTCEncodedVideoFrame( new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), ); input.write(frame); await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); const extracted = extractPacketTrailer(frame.data); expect(frame.data.byteLength - extracted.data.byteLength).toBe(15); expect(extracted.metadata?.userTimestamp).toBeGreaterThanOrEqual( BigInt(now.getTime()) * BigInt(1000), ); expect(extracted.metadata?.frameId).toBe(0); } finally { vitest.useRealTimers(); } }); it('appends only frame id packet trailer metadata after encryption', async () => { const { keys, input, output } = prepareParticipantTestEncoder( participantIdentity, {}, { frameId: true }, ); await keys.setKey(await createKeyMaterialFromString('key1'), 1); const frame = mockRTCEncodedVideoFrame( new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), ); input.write(frame); await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); const extracted = extractPacketTrailer(frame.data); expect(frame.data.byteLength - extracted.data.byteLength).toBe(11); expect(extracted.metadata).toEqual({ userTimestamp: BigInt(0), frameId: 1, }); }); }); }); describe('decode', () => { afterEach(() => {}); it('passthrough if participant encryption disabled', async () => { vitest.useFakeTimers(); try { const { cryptor, input, output } = prepareParticipantTestDecoder(participantIdentity, {}); // the track is published unencrypted cryptor.setEncrypted(false); const frame = mockEncryptedRTCEncodedVideoFrame(1); input.write(frame); await vitest.advanceTimersToNextTimerAsync(); expect(output.chunks).toEqual([frame]); } finally { vitest.useRealTimers(); } }); it('passthrough for empty frame', async () => { vitest.useFakeTimers(); try { const { input, output } = prepareParticipantTestDecoder(participantIdentity, {}); // empty frame const frame = mockRTCEncodedVideoFrame(new Uint8Array(0)); input.write(frame); await vitest.advanceTimersToNextTimerAsync(); expect(output.chunks).toEqual([frame]); } finally { vitest.useRealTimers(); } }); it('immediately drops frames when key marked invalid', async () => { vitest.useFakeTimers(); try { const { keys, input, output } = prepareParticipantTestDecoder(participantIdentity, { failureTolerance: 0, }); keys.decryptionFailure(); input.write(mockEncryptedRTCEncodedVideoFrame(1)); await vitest.advanceTimersToNextTimerAsync(); expect(output.chunks).toEqual([]); keys.decryptionFailure(); input.write(mockEncryptedRTCEncodedVideoFrame(0)); await vitest.advanceTimersToNextTimerAsync(); expect(output.chunks).toEqual([]); } finally { vitest.useRealTimers(); } }); it('calls decryptionFailure on missing key and emits error', async () => { vitest.useFakeTimers(); try { const { cryptor, keys, input } = prepareParticipantTestDecoder(participantIdentity, {}); const errorListener = vitest.fn(); cryptor.on(CryptorEvent.Error, errorListener); vitest.spyOn(keys, 'decryptionFailure'); // no key is set at this index input.write(mockEncryptedRTCEncodedVideoFrame(1)); await vitest.advanceTimersToNextTimerAsync(); expect(keys.decryptionFailure).toHaveBeenCalledTimes(1); expect(keys.decryptionFailure).toHaveBeenCalledWith(1); expect(errorListener).toHaveBeenCalled(); } finally { vitest.useRealTimers(); } }); it('logs a missing key at most once per throttle interval', async () => { vitest.useFakeTimers(); const warn = vitest.spyOn(workerLogger, 'warn'); try { const { input } = prepareParticipantTestDecoder(participantIdentity, { failureTolerance: -1, }); const missingKeyWarnings = () => warn.mock.calls.filter(([message]) => String(message).startsWith('skipping decryption')); for (let frame = 0; frame < 3; frame++) { input.write(mockEncryptedRTCEncodedVideoFrame(1)); await vitest.advanceTimersToNextTimerAsync(); } expect(missingKeyWarnings()).toHaveLength(1); vitest.advanceTimersByTime(1001); input.write(mockEncryptedRTCEncodedVideoFrame(1)); await vitest.advanceTimersToNextTimerAsync(); expect(missingKeyWarnings()).toHaveLength(2); } finally { warn.mockRestore(); vitest.useRealTimers(); } }); it('immediately drops frame if no key', async () => { vitest.useFakeTimers(); try { const { input, output } = prepareParticipantTestDecoder(participantIdentity, {}); vitest.spyOn(crypto.subtle, 'decrypt'); input.write(mockEncryptedRTCEncodedVideoFrame(1)); await vitest.advanceTimersToNextTimerAsync(); expect(crypto.subtle.decrypt).not.toHaveBeenCalled(); expect(output.chunks).toEqual([]); } finally { vitest.useRealTimers(); } }); it('calls decryptionFailure with incorrect key and emits error', async () => { vitest.useFakeTimers(); try { const { cryptor, keys, input, output } = prepareParticipantTestDecoder( participantIdentity, { ratchetWindowSize: 0 }, ); vitest.spyOn(crypto.subtle, 'decrypt'); vitest.spyOn(keys, 'decryptionFailure'); const errorListener = vitest.fn(); cryptor.on(CryptorEvent.Error, errorListener); await keys.setKey(await createKeyMaterialFromString('incorrect key'), 1); const frame = mockRTCEncodedVideoFrame( new Uint8Array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 254, 96, 91, 111, 187, 132, 31, 12, 207, 136, 17, 221, 233, 116, 174, 6, 50, 37, 214, 71, 119, 196, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 199, 51, 12, 1, ]), ); // global.RTCEncodedAudioFrame = vitest.fn(); input.write(frame); await vitest.waitFor(() => expect(keys.decryptionFailure).toHaveBeenCalled()); expect(crypto.subtle.decrypt).toHaveBeenCalled(); expect(output.chunks).toEqual([]); expect(errorListener).toHaveBeenCalled(); expect(keys.decryptionFailure).toHaveBeenCalledTimes(1); expect(keys.decryptionFailure).toHaveBeenCalledWith(1); } finally { vitest.useRealTimers(); } }); it('decrypts frame with correct key', async () => { vitest.useFakeTimers(); try { const { keys, input, output } = prepareParticipantTestDecoder(participantIdentity, {}); vitest.spyOn(keys, 'decryptionSuccess'); await keys.setKey(await createKeyMaterialFromString('key1'), 1); const frame = mockRTCEncodedVideoFrame( new Uint8Array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 254, 96, 91, 111, 187, 132, 31, 12, 207, 136, 17, 221, 233, 116, 174, 6, 50, 37, 214, 71, 119, 196, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 199, 51, 12, 1, ]), ); input.write(frame); await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); expect(output.chunks).toEqual([frame]); expect(keys.decryptionSuccess).toHaveBeenCalledTimes(1); expect(keys.decryptionSuccess).toHaveBeenCalledWith(1); expect(frame.data.byteLength).toBe(16); expect(new Uint8Array(frame.data)).toEqual( new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), ); } finally { vitest.useRealTimers(); } }); it('posts packet trailer metadata when the advertised trailer path is active', async () => { vitest.useFakeTimers(); try { const { cryptor, input, output } = prepareParticipantTestDecoder(participantIdentity, {}); const postMessage = vitest.fn(); vitest.stubGlobal('postMessage', postMessage); cryptor.setHasFrameMetadata(true); cryptor.setEncrypted(false); const payload = Uint8Array.from([1, 2, 3, 4]); const trailer = appendPacketTrailer(payload, 1_744_249_600_123_456n, 0); const frame = mockRTCEncodedVideoFrame(trailer); input.write(frame); await vitest.advanceTimersToNextTimerAsync(); expect(new Uint8Array(output.chunks[0].data)).toEqual(payload); expect(postMessage).toHaveBeenCalledWith({ kind: 'packetTrailerMetadata', data: { trackId: 'testTrack', rtpTimestamp: frame.timestamp, ssrc: 0, metadata: { userTimestamp: 1_744_249_600_123_456n, frameId: 0, }, }, }); } finally { vitest.unstubAllGlobals(); vitest.useRealTimers(); } }); it('recovers from delayed use of rotated key', async () => { vitest.useFakeTimers(); try { // 1. we (the local participant) have just joined a room and do not have the existing key (index 0) for the existing/remote participant const { keys, input, output } = prepareParticipantTestDecoder(participantIdentity, { failureTolerance: 1, ratchetWindowSize: 0, }); vitest.spyOn(keys, 'decryptionFailure'); // 2. we receive some frames from the existing participant encrypted with the existing key 0 that we don't have input.write(mockEncryptedRTCEncodedVideoFrame(0)); input.write(mockEncryptedRTCEncodedVideoFrame(0)); input.write(mockEncryptedRTCEncodedVideoFrame(0)); input.write(mockEncryptedRTCEncodedVideoFrame(0)); // 3. we should have marked key at index 0 as invalid by now and dropped all the frames await vitest.waitFor(() => expect(keys.decryptionFailure).toHaveBeenCalledTimes(2)); expect(keys.hasInvalidKeyAtIndex(0)).toBe(true); expect(output.chunks).toEqual([]); // 4. the existing participant then notices that we have joined the room and generates a new key (with a new key index 1) // and distributes it out of band to us await keys.setKey(await createKeyMaterialFromString('key1'), 1); // 5. the existing participant waits a period of time before using the new key and continues sending media using the previous key 0. // we receive these frames and should drop them as we still don't have the key. input.write(mockEncryptedRTCEncodedVideoFrame(0)); input.write(mockEncryptedRTCEncodedVideoFrame(0)); input.write(mockEncryptedRTCEncodedVideoFrame(0)); input.write(mockEncryptedRTCEncodedVideoFrame(0)); await vitest.advanceTimersToNextTimerAsync(); expect(output.chunks).toEqual([]); // 6. the existing participant moves over to the new key index 1 and we start to receive frames for index 1 that we // should be able to decrypt even though we had the previous failures. input.write( mockRTCEncodedVideoFrame( new Uint8Array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 254, 96, 91, 111, 187, 132, 31, 12, 207, 136, 17, 221, 233, 116, 174, 6, 50, 37, 214, 71, 119, 196, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 199, 51, 12, 1, ]), ), ); input.write( mockRTCEncodedVideoFrame( new Uint8Array([ 99, 2, 3, 4, 5, 6, 7, 8, 9, 10, 154, 108, 209, 239, 253, 33, 72, 111, 13, 125, 10, 101, 28, 209, 141, 162, 0, 238, 189, 254, 66, 156, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 96, 247, 12, 1, ]), ), ); await vitest.waitFor(() => expect(output.chunks.length).toEqual(2)); expect(new Uint8Array(output.chunks[0].data)).toEqual( new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), ); expect(new Uint8Array(output.chunks[1].data)).toEqual( new Uint8Array([99, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), ); } finally { vitest.useRealTimers(); } }); }); });