< Summary

Information
Class: LiveKit.Rtc.E2EEOptions
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/E2EE.cs
Line coverage
100%
Covered lines: 24
Uncovered lines: 0
Coverable lines: 24
Total lines: 542
Line coverage: 100%
Branch coverage
75%
Covered branches: 3
Total branches: 4
Branch coverage: 75%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
ToProto()75%44100%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/E2EE.cs

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Text;
 6using LiveKit.Proto;
 7using LiveKit.Rtc.Internal;
 8
 9namespace LiveKit.Rtc
 10{
 11    /// <summary>
 12    /// Default constants for E2EE key ratcheting.
 13    /// </summary>
 14    public static class E2EEDefaults
 15    {
 16        /// <summary>
 17        /// Default ratchet salt.
 18        /// </summary>
 19        public static readonly byte[] RatchetSalt = Encoding.UTF8.GetBytes("LKFrameEncryptionKey");
 20
 21        /// <summary>
 22        /// Default ratchet window size.
 23        /// </summary>
 24        public const int RatchetWindowSize = 16;
 25
 26        /// <summary>
 27        /// Default failure tolerance (-1 means unlimited).
 28        /// </summary>
 29        public const int FailureTolerance = -1;
 30
 31        /// <summary>
 32        /// Default key ring size: 16 keys per participant, at key indices 0 to 15.
 33        /// </summary>
 34        public const int KeyRingSize = 16;
 35    }
 36
 37    /// <summary>
 38    /// Options for the key provider.
 39    /// </summary>
 40    public class KeyProviderOptions
 41    {
 42        /// <summary>
 43        /// Key shared by every participant. When set, it encrypts and decrypts the media of all
 44        /// participants; when null, set a key per participant with <see cref="KeyProvider.SetKey"/>.
 45        /// </summary>
 46        public byte[]? SharedKey { get; set; }
 47
 48        /// <summary>
 49        /// Salt used to ratchet keys. Defaults to <see cref="E2EEDefaults.RatchetSalt"/>, the value of the other
 50        /// LiveKit SDKs.
 51        /// </summary>
 52        public byte[] RatchetSalt { get; set; } = E2EEDefaults.RatchetSalt;
 53
 54        /// <summary>
 55        /// Number of ratchet steps tried when a frame does not decrypt with the current key. Defaults to
 56        /// <see cref="E2EEDefaults.RatchetWindowSize"/>.
 57        /// </summary>
 58        public int RatchetWindowSize { get; set; } = E2EEDefaults.RatchetWindowSize;
 59
 60        /// <summary>
 61        /// Number of consecutive decryption failures tolerated before the key is considered invalid; -1
 62        /// tolerates any number. Defaults to <see cref="E2EEDefaults.FailureTolerance"/>.
 63        /// </summary>
 64        public int FailureTolerance { get; set; } = E2EEDefaults.FailureTolerance;
 65
 66        /// <summary>
 67        /// Number of keys kept per participant, addressed by the key indices 0 to
 68        /// <c>KeyRingSize - 1</c>. The native SDK clamps it to the range 1 to 255. Defaults to
 69        /// <see cref="E2EEDefaults.KeyRingSize"/>.
 70        /// </summary>
 71        public int KeyRingSize { get; set; } = E2EEDefaults.KeyRingSize;
 72
 73        /// <summary>
 74        /// Key derivation function used to derive the frame keys. Defaults to PBKDF2, the default
 75        /// of every LiveKit SDK, so it only needs changing to interoperate with a client configured
 76        /// otherwise.
 77        /// </summary>
 78        public Proto.KeyDerivationFunction KeyDerivationFunction { get; set; } =
 79            Proto.KeyDerivationFunction.Pbkdf2;
 80    }
 81
 82    /// <summary>
 83    /// Options for end-to-end encryption.
 84    /// </summary>
 85    public class E2EEOptions
 86    {
 87        /// <summary>
 88        /// Options of the key provider: shared key, ratcheting and key ring.
 89        /// </summary>
 90        public KeyProviderOptions KeyProviderOptions { get; set; } = new KeyProviderOptions();
 91
 92        /// <summary>
 93        /// Encryption algorithm of the media. Defaults to <see cref="Proto.EncryptionType.Gcm"/>.
 94        /// </summary>
 95        public Proto.EncryptionType EncryptionType { get; set; } = Proto.EncryptionType.Gcm;
 96
 97        /// <summary>
 98        /// Converts to proto options.
 99        /// </summary>
 100        internal LiveKit.Proto.E2eeOptions ToProto()
 31101        {
 31102            var options = new LiveKit.Proto.E2eeOptions
 31103            {
 31104                EncryptionType = EncryptionType,
 31105                KeyProviderOptions = new LiveKit.Proto.KeyProviderOptions
 31106                {
 31107                    RatchetWindowSize = KeyProviderOptions.RatchetWindowSize,
 31108                    FailureTolerance = KeyProviderOptions.FailureTolerance,
 31109                    RatchetSalt = Google.Protobuf.ByteString.CopyFrom(
 31110                        KeyProviderOptions.RatchetSalt ?? E2EEDefaults.RatchetSalt
 31111                    ),
 31112                    // Sent as set: the native SDK clamps it to the range 1 to 255
 31113                    KeyRingSize = KeyProviderOptions.KeyRingSize,
 31114                    KeyDerivationFunction = KeyProviderOptions.KeyDerivationFunction,
 31115                },
 31116            };
 117
 31118            if (KeyProviderOptions.SharedKey != null)
 27119            {
 27120                options.KeyProviderOptions.SharedKey = Google.Protobuf.ByteString.CopyFrom(
 27121                    KeyProviderOptions.SharedKey
 27122                );
 27123            }
 124
 31125            return options;
 31126        }
 127    }
 128
 129    /// <summary>
 130    /// Provides key management for E2EE.
 131    /// </summary>
 132    public class KeyProvider
 133    {
 134        private readonly ulong _roomHandle;
 135        private readonly KeyProviderOptions _options;
 136
 137        /// <summary>
 138        /// Used by the SDK, which creates the key provider with the E2EE manager. Get it from
 139        /// <see cref="E2EEManager.KeyProvider"/> instead of constructing it.
 140        /// </summary>
 141        /// <param name="roomHandle">Native handle of the room, which the public API does not expose.</param>
 142        /// <param name="options">The key provider options.</param>
 143        public KeyProvider(ulong roomHandle, KeyProviderOptions options)
 144        {
 145            _roomHandle = roomHandle;
 146            _options = options ?? throw new ArgumentNullException(nameof(options));
 147        }
 148
 149        /// <summary>
 150        /// Gets the key provider options.
 151        /// </summary>
 152        public KeyProviderOptions Options => _options;
 153
 154        /// <summary>
 155        /// Sets the shared encryption key. Only a room connected with
 156        /// <see cref="KeyProviderOptions.SharedKey"/> set uses a shared key.
 157        /// </summary>
 158        /// <param name="key">The encryption key.</param>
 159        /// <param name="keyIndex">Index of the key in the key ring, from 0 to
 160        /// <see cref="KeyProviderOptions.KeyRingSize"/> - 1.</param>
 161        /// <exception cref="InvalidOperationException">Thrown when <paramref name="keyIndex"/> is
 162        /// outside the key ring, or when the room was connected without
 163        /// <see cref="KeyProviderOptions.SharedKey"/>.</exception>
 164        public void SetSharedKey(byte[] key, int keyIndex = 0)
 165        {
 166            if (key == null)
 167                throw new ArgumentNullException(nameof(key));
 168
 169            var request = new FfiRequest
 170            {
 171                E2Ee = new E2eeRequest
 172                {
 173                    RoomHandle = _roomHandle,
 174                    SetSharedKey = new SetSharedKeyRequest
 175                    {
 176                        KeyIndex = keyIndex,
 177                        SharedKey = Google.Protobuf.ByteString.CopyFrom(key),
 178                    },
 179                },
 180            };
 181
 182            FfiClient.Instance.SendRequest(request);
 183        }
 184
 185        /// <summary>
 186        /// Exports the shared encryption key.
 187        /// </summary>
 188        /// <param name="keyIndex">Index of the key in the key ring, from 0 to
 189        /// <see cref="KeyProviderOptions.KeyRingSize"/> - 1.</param>
 190        /// <returns>The exported key, or an empty array when that index holds no key or is outside
 191        /// the key ring.</returns>
 192        public byte[] ExportSharedKey(int keyIndex = 0)
 193        {
 194            var request = new FfiRequest
 195            {
 196                E2Ee = new E2eeRequest
 197                {
 198                    RoomHandle = _roomHandle,
 199                    GetSharedKey = new GetSharedKeyRequest { KeyIndex = keyIndex },
 200                },
 201            };
 202
 203            var response = FfiClient.Instance.SendRequest(request);
 204            return response.E2Ee.GetSharedKey.Key.ToByteArray();
 205        }
 206
 207        /// <summary>
 208        /// Ratchets the shared encryption key.
 209        /// </summary>
 210        /// <param name="keyIndex">Index of the key in the key ring, from 0 to
 211        /// <see cref="KeyProviderOptions.KeyRingSize"/> - 1.</param>
 212        /// <returns>The new ratcheted key, or an empty array when that index holds no key or is
 213        /// outside the key ring.</returns>
 214        public byte[] RatchetSharedKey(int keyIndex = 0)
 215        {
 216            var request = new FfiRequest
 217            {
 218                E2Ee = new E2eeRequest
 219                {
 220                    RoomHandle = _roomHandle,
 221                    RatchetSharedKey = new RatchetSharedKeyRequest { KeyIndex = keyIndex },
 222                },
 223            };
 224
 225            var response = FfiClient.Instance.SendRequest(request);
 226            return response.E2Ee.RatchetSharedKey.NewKey.ToByteArray();
 227        }
 228
 229        /// <summary>
 230        /// Sets the encryption key for a specific participant.
 231        /// </summary>
 232        /// <param name="participantIdentity">The participant identity.</param>
 233        /// <param name="key">The encryption key.</param>
 234        /// <param name="keyIndex">Index of the key in the key ring, from 0 to
 235        /// <see cref="KeyProviderOptions.KeyRingSize"/> - 1.</param>
 236        /// <exception cref="InvalidOperationException">Thrown when <paramref name="keyIndex"/> is
 237        /// outside the key ring.</exception>
 238        public void SetKey(string participantIdentity, byte[] key, int keyIndex = 0)
 239        {
 240            if (string.IsNullOrEmpty(participantIdentity))
 241                throw new ArgumentNullException(nameof(participantIdentity));
 242            if (key == null)
 243                throw new ArgumentNullException(nameof(key));
 244
 245            var request = new FfiRequest
 246            {
 247                E2Ee = new E2eeRequest
 248                {
 249                    RoomHandle = _roomHandle,
 250                    SetKey = new SetKeyRequest
 251                    {
 252                        ParticipantIdentity = participantIdentity,
 253                        KeyIndex = keyIndex,
 254                        Key = Google.Protobuf.ByteString.CopyFrom(key),
 255                    },
 256                },
 257            };
 258
 259            FfiClient.Instance.SendRequest(request);
 260        }
 261
 262        /// <summary>
 263        /// Exports the encryption key for a specific participant.
 264        /// </summary>
 265        /// <param name="participantIdentity">The participant identity.</param>
 266        /// <param name="keyIndex">Index of the key in the key ring, from 0 to
 267        /// <see cref="KeyProviderOptions.KeyRingSize"/> - 1.</param>
 268        /// <returns>The exported key, or an empty array when that index holds no key or is outside
 269        /// the key ring.</returns>
 270        public byte[] ExportKey(string participantIdentity, int keyIndex = 0)
 271        {
 272            if (string.IsNullOrEmpty(participantIdentity))
 273                throw new ArgumentNullException(nameof(participantIdentity));
 274
 275            var request = new FfiRequest
 276            {
 277                E2Ee = new E2eeRequest
 278                {
 279                    RoomHandle = _roomHandle,
 280                    GetKey = new GetKeyRequest
 281                    {
 282                        ParticipantIdentity = participantIdentity,
 283                        KeyIndex = keyIndex,
 284                    },
 285                },
 286            };
 287
 288            var response = FfiClient.Instance.SendRequest(request);
 289            return response.E2Ee.GetKey.Key.ToByteArray();
 290        }
 291
 292        /// <summary>
 293        /// Ratchets the encryption key for a specific participant.
 294        /// </summary>
 295        /// <param name="participantIdentity">The participant identity.</param>
 296        /// <param name="keyIndex">Index of the key in the key ring, from 0 to
 297        /// <see cref="KeyProviderOptions.KeyRingSize"/> - 1.</param>
 298        /// <returns>The new ratcheted key, or an empty array when that index holds no key or is
 299        /// outside the key ring.</returns>
 300        public byte[] RatchetKey(string participantIdentity, int keyIndex = 0)
 301        {
 302            if (string.IsNullOrEmpty(participantIdentity))
 303                throw new ArgumentNullException(nameof(participantIdentity));
 304
 305            var request = new FfiRequest
 306            {
 307                E2Ee = new E2eeRequest
 308                {
 309                    RoomHandle = _roomHandle,
 310                    RatchetKey = new RatchetKeyRequest
 311                    {
 312                        ParticipantIdentity = participantIdentity,
 313                        KeyIndex = keyIndex,
 314                    },
 315                },
 316            };
 317
 318            var response = FfiClient.Instance.SendRequest(request);
 319            return response.E2Ee.RatchetKey.NewKey.ToByteArray();
 320        }
 321    }
 322
 323    /// <summary>
 324    /// Frame cryptor for a specific participant.
 325    /// </summary>
 326    public class FrameCryptor
 327    {
 328        private readonly ulong _roomHandle;
 329        private readonly string _participantIdentity;
 330        private readonly string _trackSid;
 331        private int _keyIndex;
 332        private bool _enabled;
 333
 334        /// <summary>
 335        /// Used by the SDK. Get the cryptors from <see cref="E2EEManager.GetFrameCryptors"/> instead: a cryptor
 336        /// created without a track SID cannot be addressed by <see cref="SetEnabled"/> and <see cref="SetKeyIndex"/>.
 337        /// </summary>
 338        /// <param name="roomHandle">Native handle of the room, which the public API does not expose.</param>
 339        /// <param name="participantIdentity">The participant identity.</param>
 340        /// <param name="keyIndex">The key index.</param>
 341        /// <param name="enabled">Whether encryption is enabled.</param>
 342        public FrameCryptor(
 343            ulong roomHandle,
 344            string participantIdentity,
 345            int keyIndex,
 346            bool enabled
 347        )
 348            : this(roomHandle, participantIdentity, string.Empty, keyIndex, enabled) { }
 349
 350        /// <summary>
 351        /// Used by the SDK. Get the cryptors from <see cref="E2EEManager.GetFrameCryptors"/> instead of
 352        /// constructing them.
 353        /// </summary>
 354        /// <param name="roomHandle">Native handle of the room, which the public API does not expose.</param>
 355        /// <param name="participantIdentity">The participant identity.</param>
 356        /// <param name="trackSid">The SID of the track the cryptor encrypts or decrypts.</param>
 357        /// <param name="keyIndex">The key index.</param>
 358        /// <param name="enabled">Whether encryption is enabled.</param>
 359        public FrameCryptor(
 360            ulong roomHandle,
 361            string participantIdentity,
 362            string trackSid,
 363            int keyIndex,
 364            bool enabled
 365        )
 366        {
 367            _roomHandle = roomHandle;
 368            _participantIdentity = participantIdentity;
 369            _trackSid = trackSid ?? string.Empty;
 370            _keyIndex = keyIndex;
 371            _enabled = enabled;
 372        }
 373
 374        /// <summary>
 375        /// Gets the SID of the track this cryptor encrypts or decrypts.
 376        /// </summary>
 377        public string TrackSid => _trackSid;
 378
 379        /// <summary>
 380        /// Gets the participant identity.
 381        /// </summary>
 382        public string ParticipantIdentity => _participantIdentity;
 383
 384        /// <summary>
 385        /// Gets the key index.
 386        /// </summary>
 387        public int KeyIndex => _keyIndex;
 388
 389        /// <summary>
 390        /// Gets whether encryption is enabled.
 391        /// </summary>
 392        public bool Enabled => _enabled;
 393
 394        /// <summary>
 395        /// Sets whether encryption is enabled.
 396        /// </summary>
 397        /// <param name="enabled">True to enable, false to disable.</param>
 398        public void SetEnabled(bool enabled)
 399        {
 400            _enabled = enabled;
 401
 402            var request = new FfiRequest
 403            {
 404                E2Ee = new E2eeRequest
 405                {
 406                    RoomHandle = _roomHandle,
 407                    CryptorSetEnabled = new FrameCryptorSetEnabledRequest
 408                    {
 409                        ParticipantIdentity = _participantIdentity,
 410                        TrackSid = _trackSid,
 411                        Enabled = enabled,
 412                    },
 413                },
 414            };
 415
 416            FfiClient.Instance.SendRequest(request);
 417        }
 418
 419        /// <summary>
 420        /// Sets the key index.
 421        /// </summary>
 422        /// <param name="keyIndex">The key index.</param>
 423        public void SetKeyIndex(int keyIndex)
 424        {
 425            _keyIndex = keyIndex;
 426
 427            var request = new FfiRequest
 428            {
 429                E2Ee = new E2eeRequest
 430                {
 431                    RoomHandle = _roomHandle,
 432                    CryptorSetKeyIndex = new FrameCryptorSetKeyIndexRequest
 433                    {
 434                        ParticipantIdentity = _participantIdentity,
 435                        TrackSid = _trackSid,
 436                        KeyIndex = keyIndex,
 437                    },
 438                },
 439            };
 440
 441            FfiClient.Instance.SendRequest(request);
 442        }
 443    }
 444
 445    /// <summary>
 446    /// Manager for end-to-end encryption.
 447    /// </summary>
 448    public class E2EEManager
 449    {
 450        private readonly ulong _roomHandle;
 451        private readonly E2EEOptions? _options;
 452        private readonly KeyProvider? _keyProvider;
 453        private bool _enabled;
 454
 455        /// <summary>
 456        /// Used by the SDK, which creates the manager when <see cref="Room.ConnectAsync"/> runs. Get it from
 457        /// <see cref="Room.E2EEManager"/> instead of constructing it.
 458        /// </summary>
 459        /// <param name="roomHandle">Native handle of the room, which the public API does not expose.</param>
 460        /// <param name="options">The E2EE options, or null when encryption is disabled.</param>
 461        public E2EEManager(ulong roomHandle, E2EEOptions? options)
 462        {
 463            _roomHandle = roomHandle;
 464            _options = options;
 465            _enabled = options != null;
 466
 467            if (options != null)
 468            {
 469                _keyProvider = new KeyProvider(roomHandle, options.KeyProviderOptions);
 470            }
 471        }
 472
 473        /// <summary>
 474        /// Gets the key provider.
 475        /// </summary>
 476        public KeyProvider? KeyProvider => _keyProvider;
 477
 478        /// <summary>
 479        /// Gets whether E2EE is enabled.
 480        /// </summary>
 481        public bool Enabled => _enabled;
 482
 483        /// <summary>
 484        /// Gets the E2EE options.
 485        /// </summary>
 486        public E2EEOptions? Options => _options;
 487
 488        /// <summary>
 489        /// Sets whether E2EE is enabled.
 490        /// </summary>
 491        /// <param name="enabled">True to enable, false to disable.</param>
 492        public void SetEnabled(bool enabled)
 493        {
 494            _enabled = enabled;
 495
 496            var request = new FfiRequest
 497            {
 498                E2Ee = new E2eeRequest
 499                {
 500                    RoomHandle = _roomHandle,
 501                    ManagerSetEnabled = new E2eeManagerSetEnabledRequest { Enabled = enabled },
 502                },
 503            };
 504
 505            FfiClient.Instance.SendRequest(request);
 506        }
 507
 508        /// <summary>
 509        /// Gets the list of frame cryptors for all participants.
 510        /// </summary>
 511        /// <returns>A list of frame cryptors.</returns>
 512        public List<FrameCryptor> GetFrameCryptors()
 513        {
 514            var request = new FfiRequest
 515            {
 516                E2Ee = new E2eeRequest
 517                {
 518                    RoomHandle = _roomHandle,
 519                    ManagerGetFrameCryptors = new E2eeManagerGetFrameCryptorsRequest(),
 520                },
 521            };
 522
 523            var response = FfiClient.Instance.SendRequest(request);
 524            var cryptors = new List<FrameCryptor>();
 525
 526            foreach (var cryptor in response.E2Ee.ManagerGetFrameCryptors.FrameCryptors)
 527            {
 528                cryptors.Add(
 529                    new FrameCryptor(
 530                        _roomHandle,
 531                        cryptor.ParticipantIdentity,
 532                        cryptor.TrackSid,
 533                        cryptor.KeyIndex,
 534                        cryptor.Enabled
 535                    )
 536                );
 537            }
 538
 539            return cryptors;
 540        }
 541    }
 542}

Methods/Properties

ToProto()