| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.AspNetCore.Http; |
| | | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using TeleFlow.Telegram.Schema.Types; |
| | | 6 | | |
| | | 7 | | namespace TeleFlow.Telegram.Webhooks.Internal; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Handles raw ASP.NET Core webhook requests, validates Telegram webhook security metadata, |
| | | 11 | | /// deserializes updates, and passes accepted updates to the user-provided webhook handler. |
| | | 12 | | /// </summary> |
| | | 13 | | internal sealed partial class TelegramRawWebhookEndpoint |
| | | 14 | | { |
| | | 15 | | private const string SecretTokenHeaderName = "X-Telegram-Bot-Api-Secret-Token"; |
| | | 16 | | |
| | | 17 | | private const int SecretTokenRejectedEventId = 1; |
| | | 18 | | private const int InvalidPayloadRejectedEventId = 2; |
| | | 19 | | private const int UpdateReceivedEventId = 3; |
| | | 20 | | private const int UpdateProcessedEventId = 4; |
| | | 21 | | private const int UpdateProcessingFailedEventId = 5; |
| | | 22 | | |
| | 1 | 23 | | private static readonly TelegramJsonOptions DefaultJsonOptions = TelegramJsonOptions.CreateDefault(); |
| | | 24 | | |
| | | 25 | | private readonly TelegramRawWebhookHandler _handler; |
| | | 26 | | private readonly TelegramRawWebhookOptions _options; |
| | | 27 | | private readonly ILogger<TelegramRawWebhookEndpoint>? _logger; |
| | | 28 | | |
| | | 29 | | public TelegramRawWebhookEndpoint( |
| | | 30 | | TelegramRawWebhookHandler handler, |
| | | 31 | | TelegramRawWebhookOptions options, |
| | | 32 | | ILogger<TelegramRawWebhookEndpoint>? logger = null) |
| | | 33 | | { |
| | 22 | 34 | | _handler = handler ?? throw new ArgumentNullException(nameof(handler)); |
| | 22 | 35 | | _options = options ?? throw new ArgumentNullException(nameof(options)); |
| | 22 | 36 | | _logger = logger; |
| | 22 | 37 | | } |
| | | 38 | | |
| | | 39 | | public async Task<IResult> HandleAsync(HttpContext context) |
| | | 40 | | { |
| | 21 | 41 | | ArgumentNullException.ThrowIfNull(context); |
| | | 42 | | |
| | 21 | 43 | | if (!IsSecretTokenAccepted(context)) |
| | | 44 | | { |
| | 5 | 45 | | if (_logger is not null) |
| | | 46 | | { |
| | 5 | 47 | | LogSecretTokenRejected(_logger, _options.SecretTokenFailureStatusCode); |
| | | 48 | | } |
| | | 49 | | |
| | 5 | 50 | | return Results.StatusCode(_options.SecretTokenFailureStatusCode); |
| | | 51 | | } |
| | | 52 | | |
| | 16 | 53 | | var jsonOptions = context.RequestServices.GetService<TelegramJsonOptions>() ?? DefaultJsonOptions; |
| | | 54 | | Update? update; |
| | | 55 | | |
| | | 56 | | try |
| | | 57 | | { |
| | 16 | 58 | | update = await JsonSerializer.DeserializeAsync<Update>( |
| | 16 | 59 | | context.Request.Body, |
| | 16 | 60 | | jsonOptions.SerializerOptions, |
| | 16 | 61 | | context.RequestAborted).ConfigureAwait(false); |
| | 12 | 62 | | } |
| | 4 | 63 | | catch (JsonException) |
| | | 64 | | { |
| | 4 | 65 | | if (_logger is not null) |
| | | 66 | | { |
| | 4 | 67 | | LogInvalidPayloadRejected(_logger, _options.InvalidPayloadStatusCode); |
| | | 68 | | } |
| | | 69 | | |
| | 4 | 70 | | return Results.StatusCode(_options.InvalidPayloadStatusCode); |
| | | 71 | | } |
| | | 72 | | |
| | 12 | 73 | | if (update is null) |
| | | 74 | | { |
| | 1 | 75 | | if (_logger is not null) |
| | | 76 | | { |
| | 1 | 77 | | LogInvalidPayloadRejected(_logger, _options.InvalidPayloadStatusCode); |
| | | 78 | | } |
| | | 79 | | |
| | 1 | 80 | | return Results.StatusCode(_options.InvalidPayloadStatusCode); |
| | | 81 | | } |
| | | 82 | | |
| | 11 | 83 | | string? updateType = null; |
| | | 84 | | string GetUpdateType() |
| | | 85 | | { |
| | 4 | 86 | | return updateType ??= TelegramWebhookUpdateLogFormatter.GetUpdateType(update); |
| | | 87 | | } |
| | | 88 | | |
| | 11 | 89 | | if (_logger?.IsEnabled(LogLevel.Debug) == true) |
| | | 90 | | { |
| | 1 | 91 | | LogUpdateReceived(_logger, update.UpdateId, GetUpdateType()); |
| | | 92 | | } |
| | | 93 | | |
| | 11 | 94 | | var bot = context.RequestServices.GetRequiredService<ITelegramClient>(); |
| | | 95 | | try |
| | | 96 | | { |
| | 11 | 97 | | var result = await _handler(update, bot, context.RequestAborted).ConfigureAwait(false); |
| | | 98 | | |
| | 9 | 99 | | if (_logger?.IsEnabled(LogLevel.Debug) == true) |
| | | 100 | | { |
| | 1 | 101 | | LogUpdateProcessed(_logger, update.UpdateId, GetUpdateType()); |
| | | 102 | | } |
| | | 103 | | |
| | 9 | 104 | | return result; |
| | | 105 | | } |
| | 0 | 106 | | catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) |
| | | 107 | | { |
| | 0 | 108 | | throw; |
| | | 109 | | } |
| | 2 | 110 | | catch (Exception exception) |
| | | 111 | | { |
| | 2 | 112 | | if (_logger?.IsEnabled(LogLevel.Error) == true) |
| | | 113 | | { |
| | 2 | 114 | | LogUpdateProcessingFailed(_logger, exception, update.UpdateId, GetUpdateType()); |
| | | 115 | | } |
| | | 116 | | |
| | 2 | 117 | | throw; |
| | | 118 | | } |
| | 19 | 119 | | } |
| | | 120 | | |
| | | 121 | | private bool IsSecretTokenAccepted(HttpContext context) |
| | | 122 | | { |
| | 21 | 123 | | if (_options.SecretToken is null) |
| | | 124 | | { |
| | 13 | 125 | | return true; |
| | | 126 | | } |
| | | 127 | | |
| | 8 | 128 | | return context.Request.Headers.TryGetValue(SecretTokenHeaderName, out var values) && |
| | 8 | 129 | | values.Count == 1 && |
| | 8 | 130 | | string.Equals(values[0], _options.SecretToken, StringComparison.Ordinal); |
| | | 131 | | } |
| | | 132 | | |
| | | 133 | | [LoggerMessage( |
| | | 134 | | EventId = SecretTokenRejectedEventId, |
| | | 135 | | Level = LogLevel.Warning, |
| | | 136 | | Message = "Telegram webhook request rejected because secret token validation failed. status={StatusCode}.")] |
| | | 137 | | private static partial void LogSecretTokenRejected( |
| | | 138 | | ILogger logger, |
| | | 139 | | int statusCode); |
| | | 140 | | |
| | | 141 | | [LoggerMessage( |
| | | 142 | | EventId = InvalidPayloadRejectedEventId, |
| | | 143 | | Level = LogLevel.Warning, |
| | | 144 | | Message = "Telegram webhook request rejected because payload was invalid. status={StatusCode}.")] |
| | | 145 | | private static partial void LogInvalidPayloadRejected( |
| | | 146 | | ILogger logger, |
| | | 147 | | int statusCode); |
| | | 148 | | |
| | | 149 | | [LoggerMessage( |
| | | 150 | | EventId = UpdateReceivedEventId, |
| | | 151 | | Level = LogLevel.Debug, |
| | | 152 | | Message = "Telegram webhook update received. update_id={UpdateId}, type={UpdateType}.")] |
| | | 153 | | private static partial void LogUpdateReceived( |
| | | 154 | | ILogger logger, |
| | | 155 | | long updateId, |
| | | 156 | | string updateType); |
| | | 157 | | |
| | | 158 | | [LoggerMessage( |
| | | 159 | | EventId = UpdateProcessedEventId, |
| | | 160 | | Level = LogLevel.Debug, |
| | | 161 | | Message = "Telegram webhook update processed. update_id={UpdateId}, type={UpdateType}.")] |
| | | 162 | | private static partial void LogUpdateProcessed( |
| | | 163 | | ILogger logger, |
| | | 164 | | long updateId, |
| | | 165 | | string updateType); |
| | | 166 | | |
| | | 167 | | [LoggerMessage( |
| | | 168 | | EventId = UpdateProcessingFailedEventId, |
| | | 169 | | Level = LogLevel.Error, |
| | | 170 | | Message = "Telegram webhook update processing failed. update_id={UpdateId}, type={UpdateType}.")] |
| | | 171 | | private static partial void LogUpdateProcessingFailed( |
| | | 172 | | ILogger logger, |
| | | 173 | | Exception exception, |
| | | 174 | | long updateId, |
| | | 175 | | string updateType); |
| | | 176 | | } |