| | | 1 | | using System.Net; |
| | | 2 | | using System.Security.Cryptography; |
| | | 3 | | using System.Text; |
| | | 4 | | using Elsa.Diagnostics.OpenTelemetry.Options; |
| | | 5 | | using Microsoft.AspNetCore.Http; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Diagnostics.OpenTelemetry.Ingestion; |
| | | 8 | | |
| | | 9 | | public static class OtlpIngestionSecurity |
| | | 10 | | { |
| | | 11 | | public static bool IsAuthorized(HttpContext httpContext, OpenTelemetryDiagnosticsOptions options) |
| | | 12 | | { |
| | 11 | 13 | | if (string.IsNullOrWhiteSpace(options.ApiKey)) |
| | 8 | 14 | | return options.AllowUnauthenticatedLoopback && IsLoopback(httpContext); |
| | | 15 | | |
| | 3 | 16 | | return httpContext.Request.Headers.TryGetValue(options.ApiKeyHeaderName, out var value) && ApiKeysMatch(value.To |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | private static bool IsLoopback(HttpContext httpContext) |
| | | 20 | | { |
| | 8 | 21 | | var remoteAddress = httpContext.Connection.RemoteIpAddress; |
| | 8 | 22 | | return remoteAddress != null && IPAddress.IsLoopback(remoteAddress); |
| | | 23 | | } |
| | | 24 | | |
| | | 25 | | private static bool ApiKeysMatch(string providedApiKey, string expectedApiKey) |
| | | 26 | | { |
| | 3 | 27 | | var providedBytes = Encoding.UTF8.GetBytes(providedApiKey); |
| | 3 | 28 | | var expectedBytes = Encoding.UTF8.GetBytes(expectedApiKey); |
| | 3 | 29 | | var providedHash = SHA256.HashData(providedBytes); |
| | 3 | 30 | | var expectedHash = SHA256.HashData(expectedBytes); |
| | | 31 | | |
| | | 32 | | try |
| | | 33 | | { |
| | 3 | 34 | | return CryptographicOperations.FixedTimeEquals(providedHash, expectedHash); |
| | | 35 | | } |
| | | 36 | | finally |
| | | 37 | | { |
| | 3 | 38 | | CryptographicOperations.ZeroMemory(providedBytes); |
| | 3 | 39 | | CryptographicOperations.ZeroMemory(expectedBytes); |
| | 3 | 40 | | CryptographicOperations.ZeroMemory(providedHash); |
| | 3 | 41 | | CryptographicOperations.ZeroMemory(expectedHash); |
| | 3 | 42 | | } |
| | 3 | 43 | | } |
| | | 44 | | } |