| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.AspNetCore.Http; |
| | | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using TeleFlow.Telegram.Internal; |
| | | 6 | | using TeleFlow.Telegram.Schema.Types; |
| | | 7 | | |
| | | 8 | | namespace TeleFlow.Telegram.Webhooks.Internal; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Handles raw ASP.NET Core webhook requests, validates Telegram webhook security metadata, |
| | | 12 | | /// deserializes updates, and passes accepted updates to the user-provided webhook handler. |
| | | 13 | | /// </summary> |
| | | 14 | | internal sealed partial class TelegramRawWebhookEndpoint |
| | | 15 | | { |
| | | 16 | | private const string SecretTokenHeaderName = "X-Telegram-Bot-Api-Secret-Token"; |
| | | 17 | | |
| | | 18 | | private const int SecretTokenRejectedEventId = 1; |
| | | 19 | | private const int InvalidPayloadRejectedEventId = 2; |
| | | 20 | | private const int UpdateReceivedEventId = 3; |
| | | 21 | | private const int UpdateProcessedEventId = 4; |
| | | 22 | | private const int UpdateProcessingFailedEventId = 5; |
| | | 23 | | private const int UpdateDecodeStoppedEventId = 6; |
| | | 24 | | private const int UpdateDecodeSkippedEventId = 7; |
| | | 25 | | |
| | 1 | 26 | | private static readonly TelegramJsonOptions DefaultJsonOptions = TelegramJsonOptions.CreateDefault(); |
| | | 27 | | |
| | | 28 | | private readonly TelegramRawWebhookHandler _handler; |
| | | 29 | | private readonly TelegramRawWebhookOptions _options; |
| | | 30 | | private readonly ILogger<TelegramRawWebhookEndpoint>? _logger; |
| | | 31 | | |
| | | 32 | | public TelegramRawWebhookEndpoint( |
| | | 33 | | TelegramRawWebhookHandler handler, |
| | | 34 | | TelegramRawWebhookOptions options, |
| | | 35 | | ILogger<TelegramRawWebhookEndpoint>? logger = null) |
| | | 36 | | { |
| | 27 | 37 | | _handler = handler ?? throw new ArgumentNullException(nameof(handler)); |
| | 27 | 38 | | _options = options ?? throw new ArgumentNullException(nameof(options)); |
| | 27 | 39 | | _logger = logger; |
| | 27 | 40 | | } |
| | | 41 | | |
| | | 42 | | public async Task<IResult> HandleAsync(HttpContext context) |
| | | 43 | | { |
| | 26 | 44 | | ArgumentNullException.ThrowIfNull(context); |
| | | 45 | | |
| | 26 | 46 | | if (!IsSecretTokenAccepted(context)) |
| | | 47 | | { |
| | 5 | 48 | | if (_logger is not null) |
| | | 49 | | { |
| | 5 | 50 | | LogSecretTokenRejected(_logger, _options.SecretTokenFailureStatusCode); |
| | | 51 | | } |
| | | 52 | | |
| | 5 | 53 | | return Results.StatusCode(_options.SecretTokenFailureStatusCode); |
| | | 54 | | } |
| | | 55 | | |
| | 21 | 56 | | var jsonOptions = context.RequestServices.GetService<TelegramJsonOptions>() ?? DefaultJsonOptions; |
| | | 57 | | JsonDocument? document; |
| | | 58 | | |
| | | 59 | | try |
| | | 60 | | { |
| | 21 | 61 | | document = await JsonDocument.ParseAsync( |
| | 21 | 62 | | context.Request.Body, |
| | 21 | 63 | | cancellationToken: context.RequestAborted).ConfigureAwait(false); |
| | 17 | 64 | | } |
| | 4 | 65 | | catch (JsonException) |
| | | 66 | | { |
| | 4 | 67 | | if (_logger is not null) |
| | | 68 | | { |
| | 4 | 69 | | LogInvalidPayloadRejected(_logger, _options.InvalidPayloadStatusCode); |
| | | 70 | | } |
| | | 71 | | |
| | 4 | 72 | | return Results.StatusCode(_options.InvalidPayloadStatusCode); |
| | | 73 | | } |
| | | 74 | | |
| | 17 | 75 | | using (document) |
| | | 76 | | { |
| | 17 | 77 | | var payload = document.RootElement; |
| | 17 | 78 | | if (!TryGetUpdateId(payload, out var updateId)) |
| | | 79 | | { |
| | 2 | 80 | | if (_logger is not null) |
| | | 81 | | { |
| | 2 | 82 | | LogInvalidPayloadRejected(_logger, _options.InvalidPayloadStatusCode); |
| | | 83 | | } |
| | | 84 | | |
| | 2 | 85 | | return Results.StatusCode(_options.InvalidPayloadStatusCode); |
| | | 86 | | } |
| | | 87 | | |
| | 15 | 88 | | var decodeResult = TelegramUpdateDecoder.Decode( |
| | 15 | 89 | | payload, |
| | 15 | 90 | | updateId, |
| | 15 | 91 | | jsonOptions.SerializerOptions); |
| | | 92 | | |
| | 15 | 93 | | if (!decodeResult.IsSuccess) |
| | | 94 | | { |
| | 4 | 95 | | return await HandleDecodeFailureAsync(context, decodeResult).ConfigureAwait(false); |
| | | 96 | | } |
| | | 97 | | |
| | 11 | 98 | | var update = decodeResult.Update!; |
| | 11 | 99 | | string? updateType = null; |
| | | 100 | | string GetUpdateType() |
| | | 101 | | { |
| | 4 | 102 | | return updateType ??= TelegramWebhookUpdateLogFormatter.GetUpdateType(update); |
| | | 103 | | } |
| | | 104 | | |
| | 11 | 105 | | if (_logger?.IsEnabled(LogLevel.Debug) == true) |
| | | 106 | | { |
| | 1 | 107 | | LogUpdateReceived(_logger, update.UpdateId, GetUpdateType()); |
| | | 108 | | } |
| | | 109 | | |
| | 11 | 110 | | var bot = context.RequestServices.GetRequiredService<ITelegramClient>(); |
| | | 111 | | try |
| | | 112 | | { |
| | 11 | 113 | | var result = await _handler(update, bot, context.RequestAborted).ConfigureAwait(false); |
| | | 114 | | |
| | 9 | 115 | | if (_logger?.IsEnabled(LogLevel.Debug) == true) |
| | | 116 | | { |
| | 1 | 117 | | LogUpdateProcessed(_logger, update.UpdateId, GetUpdateType()); |
| | | 118 | | } |
| | | 119 | | |
| | 9 | 120 | | return result; |
| | | 121 | | } |
| | 0 | 122 | | catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) |
| | | 123 | | { |
| | 0 | 124 | | throw; |
| | | 125 | | } |
| | 2 | 126 | | catch (Exception exception) |
| | | 127 | | { |
| | 2 | 128 | | if (_logger?.IsEnabled(LogLevel.Error) == true) |
| | | 129 | | { |
| | 2 | 130 | | LogUpdateProcessingFailed(_logger, exception, update.UpdateId, GetUpdateType()); |
| | | 131 | | } |
| | | 132 | | |
| | 2 | 133 | | throw; |
| | | 134 | | } |
| | | 135 | | } |
| | 23 | 136 | | } |
| | | 137 | | |
| | | 138 | | private async Task<IResult> HandleDecodeFailureAsync( |
| | | 139 | | HttpContext context, |
| | | 140 | | TelegramUpdateDecodeResult item) |
| | | 141 | | { |
| | 4 | 142 | | var exception = item.Exception |
| | 4 | 143 | | ?? throw new InvalidOperationException("A failed Telegram update decode result did not contain an exception. |
| | 4 | 144 | | var failure = new TelegramUpdateDecodeFailure( |
| | 4 | 145 | | TelegramUpdateTransport.Webhook, |
| | 4 | 146 | | item.UpdateId, |
| | 4 | 147 | | item.RawPayloadJson |
| | 4 | 148 | | ?? throw new InvalidOperationException("A failed Telegram update decode result did not contain raw paylo |
| | 4 | 149 | | item.PayloadSha256 |
| | 4 | 150 | | ?? throw new InvalidOperationException("A failed Telegram update decode result did not contain a payload |
| | 4 | 151 | | exception); |
| | 4 | 152 | | var policy = context.RequestServices.GetService<ITelegramUpdateDecodeFailurePolicy>() |
| | 4 | 153 | | ?? StopTelegramUpdateDecodeFailurePolicy.Instance; |
| | 4 | 154 | | var decision = await policy |
| | 4 | 155 | | .DecideAsync(failure, context.RequestAborted) |
| | 4 | 156 | | .ConfigureAwait(false); |
| | | 157 | | |
| | | 158 | | switch (decision) |
| | | 159 | | { |
| | | 160 | | case TelegramUpdateDecodeFailureDecision.Stop: |
| | 1 | 161 | | if (_logger is not null) |
| | | 162 | | { |
| | 1 | 163 | | LogUpdateDecodeStopped( |
| | 1 | 164 | | _logger, |
| | 1 | 165 | | exception, |
| | 1 | 166 | | item.UpdateId, |
| | 1 | 167 | | exception.JsonPath, |
| | 1 | 168 | | exception.PayloadSha256); |
| | | 169 | | } |
| | | 170 | | |
| | 1 | 171 | | return Results.StatusCode(StatusCodes.Status500InternalServerError); |
| | | 172 | | case TelegramUpdateDecodeFailureDecision.Skip: |
| | 2 | 173 | | if (_logger is not null) |
| | | 174 | | { |
| | 2 | 175 | | LogUpdateDecodeSkipped( |
| | 2 | 176 | | _logger, |
| | 2 | 177 | | item.UpdateId, |
| | 2 | 178 | | exception.JsonPath, |
| | 2 | 179 | | exception.PayloadSha256); |
| | | 180 | | } |
| | | 181 | | |
| | 2 | 182 | | return Results.Ok(); |
| | | 183 | | default: |
| | 0 | 184 | | throw new InvalidOperationException( |
| | 0 | 185 | | $"Unsupported Telegram update decode failure decision '{decision}'."); |
| | | 186 | | } |
| | 3 | 187 | | } |
| | | 188 | | |
| | | 189 | | private static bool TryGetUpdateId(JsonElement payload, out long updateId) |
| | | 190 | | { |
| | 17 | 191 | | updateId = default; |
| | 17 | 192 | | return payload.ValueKind == JsonValueKind.Object && |
| | 17 | 193 | | payload.TryGetProperty("update_id", out var updateIdElement) && |
| | 17 | 194 | | updateIdElement.ValueKind == JsonValueKind.Number && |
| | 17 | 195 | | updateIdElement.TryGetInt64(out updateId); |
| | | 196 | | } |
| | | 197 | | |
| | | 198 | | private bool IsSecretTokenAccepted(HttpContext context) |
| | | 199 | | { |
| | 26 | 200 | | if (_options.SecretToken is null) |
| | | 201 | | { |
| | 18 | 202 | | return true; |
| | | 203 | | } |
| | | 204 | | |
| | 8 | 205 | | return context.Request.Headers.TryGetValue(SecretTokenHeaderName, out var values) && |
| | 8 | 206 | | values.Count == 1 && |
| | 8 | 207 | | string.Equals(values[0], _options.SecretToken, StringComparison.Ordinal); |
| | | 208 | | } |
| | | 209 | | |
| | | 210 | | [LoggerMessage( |
| | | 211 | | EventId = SecretTokenRejectedEventId, |
| | | 212 | | Level = LogLevel.Warning, |
| | | 213 | | Message = "Telegram webhook request rejected because secret token validation failed. status={StatusCode}.")] |
| | | 214 | | private static partial void LogSecretTokenRejected( |
| | | 215 | | ILogger logger, |
| | | 216 | | int statusCode); |
| | | 217 | | |
| | | 218 | | [LoggerMessage( |
| | | 219 | | EventId = InvalidPayloadRejectedEventId, |
| | | 220 | | Level = LogLevel.Warning, |
| | | 221 | | Message = "Telegram webhook request rejected because payload was invalid. status={StatusCode}.")] |
| | | 222 | | private static partial void LogInvalidPayloadRejected( |
| | | 223 | | ILogger logger, |
| | | 224 | | int statusCode); |
| | | 225 | | |
| | | 226 | | [LoggerMessage( |
| | | 227 | | EventId = UpdateReceivedEventId, |
| | | 228 | | Level = LogLevel.Debug, |
| | | 229 | | Message = "Telegram webhook update received. update_id={UpdateId}, type={UpdateType}.")] |
| | | 230 | | private static partial void LogUpdateReceived( |
| | | 231 | | ILogger logger, |
| | | 232 | | long updateId, |
| | | 233 | | string updateType); |
| | | 234 | | |
| | | 235 | | [LoggerMessage( |
| | | 236 | | EventId = UpdateProcessedEventId, |
| | | 237 | | Level = LogLevel.Debug, |
| | | 238 | | Message = "Telegram webhook update processed. update_id={UpdateId}, type={UpdateType}.")] |
| | | 239 | | private static partial void LogUpdateProcessed( |
| | | 240 | | ILogger logger, |
| | | 241 | | long updateId, |
| | | 242 | | string updateType); |
| | | 243 | | |
| | | 244 | | [LoggerMessage( |
| | | 245 | | EventId = UpdateProcessingFailedEventId, |
| | | 246 | | Level = LogLevel.Error, |
| | | 247 | | Message = "Telegram webhook update processing failed. update_id={UpdateId}, type={UpdateType}.")] |
| | | 248 | | private static partial void LogUpdateProcessingFailed( |
| | | 249 | | ILogger logger, |
| | | 250 | | Exception exception, |
| | | 251 | | long updateId, |
| | | 252 | | string updateType); |
| | | 253 | | |
| | | 254 | | [LoggerMessage( |
| | | 255 | | EventId = UpdateDecodeStoppedEventId, |
| | | 256 | | Level = LogLevel.Error, |
| | | 257 | | Message = "Telegram webhook update decoding failed and the request was rejected for retry. update_id={UpdateId}, |
| | | 258 | | private static partial void LogUpdateDecodeStopped( |
| | | 259 | | ILogger logger, |
| | | 260 | | Exception exception, |
| | | 261 | | long updateId, |
| | | 262 | | string? jsonPath, |
| | | 263 | | string payloadSha256); |
| | | 264 | | |
| | | 265 | | [LoggerMessage( |
| | | 266 | | EventId = UpdateDecodeSkippedEventId, |
| | | 267 | | Level = LogLevel.Warning, |
| | | 268 | | Message = "Telegram webhook update decoding failed and the update was acknowledged by application policy. update |
| | | 269 | | private static partial void LogUpdateDecodeSkipped( |
| | | 270 | | ILogger logger, |
| | | 271 | | long updateId, |
| | | 272 | | string? jsonPath, |
| | | 273 | | string payloadSha256); |
| | | 274 | | } |