< Summary

Information
Class: Livekit.Server.Sdk.Dotnet.WebhookReceiver
Assembly: LivekitApi
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitApi/WebhookReceiver.cs
Line coverage
100%
Covered lines: 47
Uncovered lines: 0
Coverable lines: 47
Total lines: 161
Line coverage: 100%
Branch coverage
100%
Covered branches: 10
Total branches: 10
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
.ctor(...)100%11100%
Receive(...)100%22100%
Receive(...)100%22100%
Receive(...)100%66100%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitApi/WebhookReceiver.cs

#LineLine coverage
 1using System;
 2using System.Security.Cryptography;
 3using System.Text;
 4using Google.Protobuf;
 5
 6namespace Livekit.Server.Sdk.Dotnet
 7{
 8    /// <summary>
 9    /// Receives the webhook events LiveKit posts: verifies the token of the <c>Authorization</c> header and the
 10    /// SHA-256 of the body, then parses the <see cref="WebhookEvent"/>.
 11    /// </summary>
 12    /// <example>
 13    /// <code language="csharp">
 14    /// var receiver = new WebhookReceiver("api-key", "api-secret");
 15    ///
 16    /// // ASP.NET Core minimal API. Pass the raw body: LiveKit signs its SHA-256.
 17    /// app.MapPost("/livekit/webhook", async (HttpRequest request) =>
 18    /// {
 19    ///     using var body = new MemoryStream();
 20    ///     await request.Body.CopyToAsync(body);
 21    ///
 22    ///     WebhookEvent webhookEvent = receiver.Receive(
 23    ///         body.ToArray(),
 24    ///         request.Headers.Authorization.ToString()
 25    ///     );
 26    ///     Console.WriteLine($"{webhookEvent.Event} in room {webhookEvent.Room?.Name}");
 27    ///     return Results.Ok();
 28    /// });
 29    /// </code>
 30    /// </example>
 31    public class WebhookReceiver : TokenVerifier
 32    {
 33        /// <summary>
 34        /// Creates a receiver for webhooks signed with the given API key and secret.
 35        /// </summary>
 36        /// <param name="apiKey">API key; the <c>LIVEKIT_API_KEY</c> environment variable when omitted.</param>
 37        /// <param name="apiSecret">API secret, at least 32 bytes long; the <c>LIVEKIT_API_SECRET</c> environment variab
 38        /// <exception cref="ArgumentException">The key or the secret is missing, or the secret is shorter than 32 bytes
 39        public WebhookReceiver(string apiKey = null, string apiSecret = null)
 3140            : base(apiKey, apiSecret) { }
 41
 42        /// <summary>
 43        /// Creates a receiver with a custom clock tolerance for the token lifetime.
 44        /// </summary>
 45        /// <param name="apiKey">API key; the <c>LIVEKIT_API_KEY</c> environment variable when null.</param>
 46        /// <param name="apiSecret">API secret, at least 32 bytes long; the <c>LIVEKIT_API_SECRET</c> environment variab
 47        /// <param name="leeway">Clock tolerance applied to the token lifetime; <see cref="Constants.DefaultLeeway"/> wh
 48        /// <exception cref="ArgumentException">The key or the secret is missing, or the secret is shorter than 32 bytes
 49        public WebhookReceiver(string apiKey, string apiSecret, TimeSpan? leeway)
 350            : base(apiKey, apiSecret, leeway) { }
 51
 52        /// <summary>
 53        /// Verifies a webhook request and parses its event, from the raw bytes of the body, which is what
 54        /// LiveKit signs. Prefer this overload.
 55        /// </summary>
 56        /// <param name="body">The raw bytes of the posted body.</param>
 57        /// <param name="authHeader">Value of the <c>Authorization</c> header of the request.</param>
 58        /// <param name="skipAuth">True to skip the token and SHA-256 checks.</param>
 59        /// <param name="ignoreUnknownFields">True to ignore the fields this version of the SDK does not know, so events
 60        /// <returns>The decoded event.</returns>
 61        /// <exception cref="ArgumentNullException"><paramref name="body"/> is null.</exception>
 62        /// <exception cref="Exception">The header is empty, or the SHA-256 of the body does not match the token.</excep
 63        /// <exception cref="Microsoft.IdentityModel.Tokens.SecurityTokenException">The token has a wrong signature or i
 64        /// <exception cref="ArgumentException">The header is not a well-formed JWT (<c>SecurityTokenMalformedException<
 65        /// <exception cref="Google.Protobuf.InvalidJsonException">The body is not valid JSON.</exception>
 66        /// <exception cref="Google.Protobuf.InvalidProtocolBufferException">The body is not a webhook event, or has unk
 67        public WebhookEvent Receive(
 68            byte[] body,
 69            string authHeader = null,
 70            bool skipAuth = false,
 71            bool ignoreUnknownFields = true
 72        )
 473        {
 474            if (body == null)
 175            {
 176                throw new ArgumentNullException(nameof(body));
 77            }
 378            return Receive(
 379                body,
 380                Encoding.UTF8.GetString(body),
 381                authHeader,
 382                skipAuth,
 383                ignoreUnknownFields
 384            );
 185        }
 86
 87        /// <summary>
 88        /// Verifies a webhook request and parses its event, from the body as a string. The text is encoded
 89        /// as UTF-8 again to check its SHA-256, so it must be exactly what LiveKit posted; the
 90        /// <see cref="Receive(byte[], string, bool, bool)"/> overload avoids that conversion.
 91        /// </summary>
 92        /// <param name="body">The posted body, as text.</param>
 93        /// <param name="authHeader">Value of the <c>Authorization</c> header of the request.</param>
 94        /// <param name="skipAuth">True to skip the token and SHA-256 checks.</param>
 95        /// <param name="ignoreUnknownFields">True to ignore the fields this version of the SDK does not know, so events
 96        /// <returns>The decoded event.</returns>
 97        /// <exception cref="ArgumentNullException"><paramref name="body"/> is null.</exception>
 98        /// <exception cref="Exception">The header is empty, or the SHA-256 of the body does not match the token.</excep
 99        /// <exception cref="Microsoft.IdentityModel.Tokens.SecurityTokenException">The token has a wrong signature or i
 100        /// <exception cref="ArgumentException">The header is not a well-formed JWT (<c>SecurityTokenMalformedException<
 101        /// <exception cref="Google.Protobuf.InvalidJsonException">The body is not valid JSON.</exception>
 102        /// <exception cref="Google.Protobuf.InvalidProtocolBufferException">The body is not a webhook event, or has unk
 103        public WebhookEvent Receive(
 104            string body,
 105            string authHeader = null,
 106            bool skipAuth = false,
 107            bool ignoreUnknownFields = true
 108        )
 12109        {
 12110            if (body == null)
 1111            {
 1112                throw new ArgumentNullException(nameof(body));
 113            }
 11114            return Receive(
 11115                Encoding.UTF8.GetBytes(body),
 11116                body,
 11117                authHeader,
 11118                skipAuth,
 11119                ignoreUnknownFields
 11120            );
 5121        }
 122
 123        private WebhookEvent Receive(
 124            byte[] bodyBytes,
 125            string body,
 126            string authHeader,
 127            bool skipAuth,
 128            bool ignoreUnknownFields
 129        )
 14130        {
 131            // Verify token.
 14132            if (!skipAuth)
 13133            {
 13134                if (string.IsNullOrEmpty(authHeader))
 4135                {
 4136                    throw new Exception("Authorization header is empty");
 137                }
 138
 9139                var claims = Verify(authHeader);
 140
 141                // Validate Sha256.
 8142                using (var sha256 = SHA256.Create())
 8143                {
 8144                    var hash = sha256.ComputeHash(bodyBytes);
 8145                    var hashBase64 = Convert.ToBase64String(hash);
 8146                    if (claims.Sha256 != hashBase64)
 1147                    {
 1148                        throw new Exception("Sha256 checksum of the body does not match");
 149                    }
 7150                }
 7151            }
 152
 153            // Parse the body. The JSON parser must be told to ignore unknown fields, otherwise any
 154            // field added by a newer server makes every webhook fail after passing authentication.
 8155            var parser = new JsonParser(
 8156                JsonParser.Settings.Default.WithIgnoreUnknownFields(ignoreUnknownFields)
 8157            );
 8158            return parser.Parse<WebhookEvent>(body);
 6159        }
 160    }
 161}