From fa66714db9e5a7d80878685a4ae148fa7a57a6c2 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 9 Nov 2026 03:59:05 +0800 Subject: [PATCH] refactor(telegram): share administrator delivery channel --- .../Telegram/AdministratorTelegramChannel.php | 199 +++++++++++ .../AdministratorTelegramDestination.php | 20 ++ .../AdministratorTelegramLocalUnavailable.php | 6 + ...dministratorTelegramPreflightException.php | 6 + ...ministratorTelegramRemoteEffectUnknown.php | 6 + .../AdministratorTelegramTransport.php | 20 ++ .../Telegram/TelegramBotApiTransport.php | 47 +++ web/app/Services/TicketTelegramConfig.php | 19 ++ web/app/Services/TicketTelegramNotifier.php | 155 ++++----- .../AdministratorTelegramChannelTest.php | 308 ++++++++++++++++++ .../TicketTelegramNotifierSecurityTest.php | 55 ++++ 11 files changed, 751 insertions(+), 90 deletions(-) create mode 100644 web/app/Services/Telegram/AdministratorTelegramChannel.php create mode 100644 web/app/Services/Telegram/AdministratorTelegramDestination.php create mode 100644 web/app/Services/Telegram/AdministratorTelegramLocalUnavailable.php create mode 100644 web/app/Services/Telegram/AdministratorTelegramPreflightException.php create mode 100644 web/app/Services/Telegram/AdministratorTelegramRemoteEffectUnknown.php create mode 100644 web/app/Services/Telegram/AdministratorTelegramTransport.php create mode 100644 web/app/Services/Telegram/TelegramBotApiTransport.php create mode 100644 web/tests/AdministratorTelegramChannelTest.php diff --git a/web/app/Services/Telegram/AdministratorTelegramChannel.php b/web/app/Services/Telegram/AdministratorTelegramChannel.php new file mode 100644 index 00000000..c9b325fb --- /dev/null +++ b/web/app/Services/Telegram/AdministratorTelegramChannel.php @@ -0,0 +1,199 @@ +is_admin && (int) $user->enable === 1; + } + + /** + * Resolve the authoritative private-chat destination. Old binding rows are + * upgraded once with a generation while holding the configuration row lock. + */ + public function currentDestination(): ?AdministratorTelegramDestination + { + try { + $runtime = TicketTelegramConfig::runtimeForDelivery(); + } catch (\Throwable $exception) { + throw new AdministratorTelegramLocalUnavailable( + 'Administrator Telegram configuration is temporarily unavailable' + ); + } + if ($runtime === null) { + return null; + } + return $this->boundDestination(); + } + + /** Resolve a stored binding even while outbound Telegram is disabled. */ + public function boundDestination(): ?AdministratorTelegramDestination + { + $row = Configurations::where('name', TicketTelegramConfig::BINDING)->first(); + $state = self::readState($row); + $destination = $this->destinationFromState($state); + if ($destination !== null) { + return $destination; + } + if ($row === null || !$this->eligibleBindingState($state, false)) { + return null; + } + + return (new Configurations())->getConnection()->transaction(function (): ?AdministratorTelegramDestination { + $locked = Configurations::where('name', TicketTelegramConfig::BINDING) + ->lockForUpdate()->first(); + $current = self::readState($locked); + if ($locked === null || !$this->eligibleBindingState($current, false)) { + return null; + } + if (preg_match( + '/^[a-f0-9]{32}$/D', + (string) ($current['binding_generation'] ?? '') + ) !== 1) { + $current['binding_generation'] = bin2hex(random_bytes(16)); + $locked->value = json_encode($current, JSON_THROW_ON_ERROR); + if (!$locked->save()) { + throw new \RuntimeException('Telegram binding generation storage failed'); + } + } + return $this->destinationFromState($current); + }); + } + + /** + * Send once to the expected binding generation. A concurrent unbind/rebind + * is rejected before the remote request, so a reserved business delivery + * can never drift to another administrator or chat. + * + * @param array $options + */ + public function send( + AdministratorTelegramDestination $expected, + string $text, + array $options = [] + ): int { + $textLength = mb_strlen($text, 'UTF-8'); + if ($textLength < 1 || $textLength > 4096) { + throw new AdministratorTelegramPreflightException( + 'Telegram message length is invalid' + ); + } + foreach (array_keys($options) as $key) { + if (!is_string($key) || !in_array($key, self::ALLOWED_OPTIONS, true)) { + throw new AdministratorTelegramPreflightException( + 'Telegram send option is not allowed' + ); + } + } + if (isset($options['reply_to_message_id']) + && (!is_int($options['reply_to_message_id']) + || $options['reply_to_message_id'] <= 0)) { + throw new AdministratorTelegramPreflightException( + 'Telegram reply message id is invalid' + ); + } + + // Both reads are authoritative. Config runtime also rejects disabled or + // unreadable credentials; the binding read fences recipient changes. + try { + $config = TicketTelegramConfig::runtimeForDelivery(); + } catch (\Throwable $exception) { + throw new AdministratorTelegramLocalUnavailable( + 'Administrator Telegram configuration is temporarily unavailable' + ); + } + if ($config === null) { + throw new AdministratorTelegramPreflightException( + 'Administrator Telegram configuration is unavailable' + ); + } + try { + $current = $this->boundDestination(); + } catch (\Throwable $exception) { + throw new AdministratorTelegramLocalUnavailable( + 'Administrator Telegram binding is temporarily unavailable' + ); + } + if ($current === null || !$current->equals($expected)) { + throw new AdministratorTelegramPreflightException( + 'Administrator Telegram destination changed' + ); + } + + try { + return $this->transport->sendMessage( + (string) $config['bot_token'], + $current->chatId, + $text, + $options + ); + } catch (AdministratorTelegramRemoteEffectUnknown $exception) { + throw $exception; + } catch (\Throwable $exception) { + throw new AdministratorTelegramRemoteEffectUnknown( + 'Administrator Telegram remote effect is unknown' + ); + } + } + + private function destinationFromState(array $state): ?AdministratorTelegramDestination + { + if (!$this->eligibleBindingState($state, true)) { + return null; + } + return new AdministratorTelegramDestination( + (int) $state['bound_admin_id'], + (string) $state['chat_id'], + (string) $state['binding_generation'] + ); + } + + private function eligibleBindingState(array $state, bool $requireGeneration): bool + { + $administratorId = (int) ($state['bound_admin_id'] ?? 0); + $chatId = $state['chat_id'] ?? null; + if ((!is_string($chatId) && !is_int($chatId)) + || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $chatId) !== 1 + || !$this->eligibleAdministrator($administratorId)) { + return false; + } + return !$requireGeneration || preg_match( + '/^[a-f0-9]{32}$/D', + (string) ($state['binding_generation'] ?? '') + ) === 1; + } + + private static function readState($row): array + { + $state = $row === null ? [] : json_decode((string) $row->value, true); + return is_array($state) ? $state : []; + } +} diff --git a/web/app/Services/Telegram/AdministratorTelegramDestination.php b/web/app/Services/Telegram/AdministratorTelegramDestination.php new file mode 100644 index 00000000..fbda25a2 --- /dev/null +++ b/web/app/Services/Telegram/AdministratorTelegramDestination.php @@ -0,0 +1,20 @@ +administratorId === $other->administratorId + && hash_equals($this->chatId, $other->chatId) + && hash_equals($this->bindingGeneration, $other->bindingGeneration); + } +} diff --git a/web/app/Services/Telegram/AdministratorTelegramLocalUnavailable.php b/web/app/Services/Telegram/AdministratorTelegramLocalUnavailable.php new file mode 100644 index 00000000..e1d15958 --- /dev/null +++ b/web/app/Services/Telegram/AdministratorTelegramLocalUnavailable.php @@ -0,0 +1,6 @@ + $options + */ + public function sendMessage( + string $botToken, + string $chatId, + string $text, + array $options = [] + ): int; +} diff --git a/web/app/Services/Telegram/TelegramBotApiTransport.php b/web/app/Services/Telegram/TelegramBotApiTransport.php new file mode 100644 index 00000000..3863d26a --- /dev/null +++ b/web/app/Services/Telegram/TelegramBotApiTransport.php @@ -0,0 +1,47 @@ +call('sendMessage', array_merge([ + 'chat_id' => $chatId, + 'text' => $text, + ], $options), 10); + } catch (\Throwable $exception) { + // SDK exception text can contain the bot token through its request URL. + throw new AdministratorTelegramRemoteEffectUnknown( + 'Administrator Telegram remote effect is unknown' + ); + } + + $messageId = is_array($result) ? ($result['message_id'] ?? null) : null; + if (is_object($result)) { + if (method_exists($result, 'getMessageId')) { + $messageId = $result->getMessageId(); + } elseif (isset($result->message_id)) { + $messageId = $result->message_id; + } + } + if ((!is_int($messageId) && !is_string($messageId)) + || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $messageId) !== 1 + || strlen((string) $messageId) > strlen((string) PHP_INT_MAX) + || (strlen((string) $messageId) === strlen((string) PHP_INT_MAX) + && strcmp((string) $messageId, (string) PHP_INT_MAX) > 0)) { + throw new AdministratorTelegramRemoteEffectUnknown( + 'Administrator Telegram remote effect is unknown' + ); + } + return (int) $messageId; + } +} diff --git a/web/app/Services/TicketTelegramConfig.php b/web/app/Services/TicketTelegramConfig.php index 1d31d472..90ade2c3 100644 --- a/web/app/Services/TicketTelegramConfig.php +++ b/web/app/Services/TicketTelegramConfig.php @@ -70,6 +70,25 @@ final class TicketTelegramConfig return self::runtimeFromRows($rows, $requireEnabled); } + /** + * Return the authoritative outbound runtime, or null only when delivery is + * explicitly disabled/incomplete. Infrastructure and credential failures + * remain distinguishable so callers can retry instead of silently skip. + */ + public static function runtimeForDelivery(): ?array + { + $rows = self::authoritativeRows(); + if (!self::truthy($rows[self::ENABLED] ?? 'false')) { + return null; + } + if (trim((string) ($rows[self::WEBHOOK_BASE_URL] ?? '')) === '' + || trim((string) ($rows[self::BOT_TOKEN] ?? '')) === '' + || trim((string) ($rows[self::WEBHOOK_SECRET] ?? '')) === '') { + return null; + } + return self::runtimeFromRows($rows, true); + } + private static function runtimeFromRows(array $rows, bool $requireEnabled): array { $enabled = self::truthy($rows[self::ENABLED] ?? 'false'); diff --git a/web/app/Services/TicketTelegramNotifier.php b/web/app/Services/TicketTelegramNotifier.php index f4673437..a4daefd9 100644 --- a/web/app/Services/TicketTelegramNotifier.php +++ b/web/app/Services/TicketTelegramNotifier.php @@ -13,6 +13,10 @@ use App\Services\Ticket\TicketNotificationDispatcher; use App\Services\Ticket\TicketReplyStateConflict; use App\Services\Ticket\TicketTelegramNotificationResult; use App\Services\Ticket\TicketThreadService; +use App\Services\Telegram\AdministratorTelegramChannel; +use App\Services\Telegram\AdministratorTelegramDestination; +use App\Services\Telegram\AdministratorTelegramLocalUnavailable; +use App\Services\Telegram\AdministratorTelegramPreflightException; use TelegramBot\Api\BotApi; /** Administrator-only ticket alerts and replies to mapped notification messages. */ @@ -51,15 +55,19 @@ final class TicketTelegramNotifier public static function bindingStatus(): array { - $state = self::readState(Configurations::where('name', self::KEY)->first()); - $adminId = (int) ($state['bound_admin_id'] ?? 0); - return ['bound' => !empty($state['chat_id']) && self::eligibleAdmin($adminId), 'admin_id' => $adminId]; + // Disabling outbound Telegram intentionally preserves the binding; + // keep showing it so the administrator can still remove it. + $destination = self::channel()->boundDestination(); + return [ + 'bound' => $destination !== null, + 'admin_id' => $destination?->administratorId, + ]; } public static function createBinding(int $adminId): array { TicketTelegramConfig::runtime(true); - if (!self::eligibleAdmin($adminId)) { + if (!self::channel()->eligibleAdministrator($adminId)) { throw new \RuntimeException('只有超级管理员可以绑定工单通知'); } $code = bin2hex(random_bytes(24)); @@ -131,7 +139,7 @@ final class TicketTelegramNotifier $adminId = (int) ($state['pending_admin_id'] ?? 0); if ($row === null || (int) ($state['pending_expires_at'] ?? 0) <= time() || !hash_equals((string) ($state['pending_hash'] ?? ''), hash('sha256', $command['code'])) - || !self::eligibleAdmin($adminId)) { + || !self::channel()->eligibleAdministrator($adminId)) { return false; } // One-time token consumed atomically; replay cannot change the recipient. @@ -162,17 +170,14 @@ final class TicketTelegramNotifier if ($command === null) { return false; } - $state = self::deliveryBindingState(); - $adminId = (int) ($state['bound_admin_id'] ?? 0); - if (($state['chat_id'] ?? null) !== $command['chat_id'] - || preg_match('/^[a-f0-9]{32}$/D', - (string) ($state['binding_generation'] ?? '')) !== 1 - || !self::eligibleAdmin($adminId)) { + $destination = self::channel()->currentDestination(); + if ($destination === null || $destination->chatId !== $command['chat_id']) { return false; } + $adminId = $destination->administratorId; $delivery = TicketTelegramDelivery::where( - 'binding_generation', (string) $state['binding_generation'] + 'binding_generation', $destination->bindingGeneration )->where('chat_id', $command['chat_id']) ->where('telegram_message_id', $command['reply_to_message_id']) ->where('state', 'sent')->first(); @@ -194,7 +199,7 @@ final class TicketTelegramNotifier null, null, true, - 'telegram.' . $state['binding_generation'] + 'telegram.' . $destination->bindingGeneration . '.update.' . $command['update_id'], 1 )); @@ -306,14 +311,15 @@ final class TicketTelegramNotifier string $text ): void { try { - $config = TicketTelegramConfig::runtime(true); - (new BotApi($config['bot_token']))->call('sendMessage', [ - 'chat_id' => $chatId, - 'text' => $text, + $destination = self::channel()->currentDestination(); + if ($destination === null || $destination->chatId !== $chatId) { + return; + } + self::channel()->send($destination, $text, [ 'reply_to_message_id' => $replyToMessageId, 'allow_sending_without_reply' => 'true', 'disable_web_page_preview' => 'true', - ], 10); + ]); } catch (\Throwable $exception) { // The ticket transaction has already committed. Never request a // Telegram replay merely because this best-effort receipt failed. @@ -334,28 +340,25 @@ final class TicketTelegramNotifier return TicketTelegramNotificationResult::Failed; } try { - $config = TicketTelegramConfig::runtime(true); - $state = self::deliveryBindingState(); - $chatId = $state['chat_id'] ?? null; - if ((!is_string($chatId) && !is_int($chatId)) - || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $chatId) !== 1 - || !self::eligibleAdmin((int) ($state['bound_admin_id'] ?? 0))) { + $destination = self::channel()->currentDestination(); + if ($destination === null) { return TicketTelegramNotificationResult::Skipped; } $text = self::notificationText($event); - [$delivery, $ownsDispatch] = self::reserveDelivery($event, $state, $text); + [$delivery, $ownsDispatch] = self::reserveDelivery( + $event, + $destination, + $text + ); if (!$ownsDispatch) { return (string) $delivery->state === 'sent' ? TicketTelegramNotificationResult::Sent : TicketTelegramNotificationResult::Failed; } try { - $result = (new BotApi($config['bot_token']))->call('sendMessage', [ - 'chat_id' => (string) $chatId, - 'text' => $text, + $messageId = self::channel()->send($destination, $text, [ 'disable_web_page_preview' => 'true', - ], 10); - $messageId = self::telegramMessageId($result); + ]); $updated = TicketTelegramDelivery::where('id', (int) $delivery->id) ->where('state', 'dispatching')->update([ 'telegram_message_id' => $messageId, @@ -367,6 +370,9 @@ final class TicketTelegramNotifier throw new \RuntimeException('Telegram delivery finalization failed'); } return TicketTelegramNotificationResult::Sent; + } catch (AdministratorTelegramPreflightException|AdministratorTelegramLocalUnavailable $exception) { + self::releasePreflightDelivery((int) $delivery->id); + return TicketTelegramNotificationResult::Failed; } catch (\Throwable $exception) { self::markDeliveryUnknown((int) $delivery->id); throw $exception; @@ -381,9 +387,13 @@ final class TicketTelegramNotifier /** * @return array{TicketTelegramDelivery, bool} */ - private static function reserveDelivery(TicketEvent $event, array $state, string $text): array + private static function reserveDelivery( + TicketEvent $event, + AdministratorTelegramDestination $destination, + string $text + ): array { - $generation = (string) $state['binding_generation']; + $generation = $destination->bindingGeneration; $messageId = (int) $event->result->message->id; $kind = (string) $event->kind; $existing = self::deliveryForEvent($generation, $messageId, $kind); @@ -394,8 +404,8 @@ final class TicketTelegramNotifier $delivery = new TicketTelegramDelivery(); $delivery->binding_generation = $generation; - $delivery->bound_admin_id = (int) $state['bound_admin_id']; - $delivery->chat_id = (string) $state['chat_id']; + $delivery->bound_admin_id = $destination->administratorId; + $delivery->chat_id = $destination->chatId; $delivery->ticket_id = (int) $event->result->root->id; $delivery->ticket_message_id = $messageId; $delivery->event_kind = $kind; @@ -449,23 +459,6 @@ final class TicketTelegramNotifier ->where('event_kind', $kind)->first(); } - private static function telegramMessageId(mixed $result): int - { - $messageId = is_array($result) ? ($result['message_id'] ?? null) : null; - if (is_object($result)) { - if (method_exists($result, 'getMessageId')) { - $messageId = $result->getMessageId(); - } elseif (isset($result->message_id)) { - $messageId = $result->message_id; - } - } - if ((!is_int($messageId) && !is_string($messageId)) - || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $messageId) !== 1) { - throw new \RuntimeException('Telegram did not return a valid message identifier'); - } - return (int) $messageId; - } - private static function markDeliveryUnknown(int $deliveryId): void { try { @@ -480,34 +473,16 @@ final class TicketTelegramNotifier } } - private static function deliveryBindingState(): array + private static function releasePreflightDelivery(int $deliveryId): void { - $row = Configurations::where('name', self::KEY)->first(); - $state = self::readState($row); - if (preg_match('/^[a-f0-9]{32}$/D', (string) ($state['binding_generation'] ?? '')) === 1) { - return $state; - } - if ($row === null || empty($state['chat_id']) - || !self::eligibleAdmin((int) ($state['bound_admin_id'] ?? 0))) { - return $state; - } - - return (new Configurations())->getConnection()->transaction(function () { - $locked = Configurations::where('name', self::KEY)->lockForUpdate()->first(); - $current = self::readState($locked); - if ($locked === null || empty($current['chat_id']) - || !self::eligibleAdmin((int) ($current['bound_admin_id'] ?? 0))) { - return $current; - } - if (preg_match('/^[a-f0-9]{32}$/D', (string) ($current['binding_generation'] ?? '')) !== 1) { - $current['binding_generation'] = bin2hex(random_bytes(16)); - $locked->value = json_encode($current, JSON_THROW_ON_ERROR); - if (!$locked->save()) { - throw new \RuntimeException('Telegram binding generation storage failed'); - } - } - return $current; - }); + try { + TicketTelegramDelivery::where('id', $deliveryId) + ->where('state', 'dispatching')->delete(); + } catch (\Throwable $exception) { + // The remote request is known not to have started. A retained + // dispatching row is intentionally fenced and will age to unknown. + error_log('Administrator ticket Telegram preflight release failed'); + } } private static function notificationText(TicketEvent $event): string @@ -630,12 +605,17 @@ final class TicketTelegramNotifier private static function sendBindingConfirmation(string $chatId): void { try { - $config = TicketTelegramConfig::runtime(true); - (new BotApi($config['bot_token']))->call('sendMessage', [ - 'chat_id' => $chatId, - 'text' => "绑定成功\n此 Telegram 账号已绑定为管理员工单提醒接收账号。", + $destination = self::channel()->currentDestination(); + if ($destination === null || $destination->chatId !== $chatId) { + return; + } + self::channel()->send( + $destination, + "绑定成功\n此 Telegram 账号已绑定为管理员工单提醒接收账号。", + [ 'disable_web_page_preview' => 'true', - ], 10); + ] + ); } catch (\Throwable $exception) { // SDK error URLs may contain bot secrets. Never log their messages. error_log('Administrator Telegram binding confirmation failed'); @@ -661,13 +641,8 @@ final class TicketTelegramNotifier return 'Telegram 配置读取失败,请检查数据库与服务器日志'; } - private static function eligibleAdmin(int $adminId): bool + private static function channel(): AdministratorTelegramChannel { - $allowed = array_map('intval', explode(',', (string) Config::get('super_admin', ''))); - if ($adminId <= 0 || !in_array($adminId, $allowed, true)) { - return false; - } - $user = User::find($adminId); - return $user !== null && (bool) $user->is_admin && (int) $user->enable === 1; + return new AdministratorTelegramChannel(); } } diff --git a/web/tests/AdministratorTelegramChannelTest.php b/web/tests/AdministratorTelegramChannelTest.php new file mode 100644 index 00000000..be5f67a5 --- /dev/null +++ b/web/tests/AdministratorTelegramChannelTest.php @@ -0,0 +1,308 @@ +name] = clone $this; + return true; + } + } +} + +namespace App\Services { + final class Config + { + public static string $superAdministrators = '1'; + + public static function get(string $key, mixed $default = null): mixed + { + return $key === 'super_admin' ? self::$superAdministrators : $default; + } + } + + final class TicketTelegramConfig + { + public const BINDING = 'ticket_telegram_binding'; + public static bool $enabled = true; + public static bool $failRuntime = false; + public static string $token = '123456789:' . 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; + + public static function runtime(bool $requireEnabled = true): array + { + if ($requireEnabled && !self::$enabled) { + throw new \RuntimeException('disabled'); + } + return ['bot_token' => self::$token]; + } + + public static function runtimeForDelivery(): ?array + { + if (self::$failRuntime) { + throw new \RuntimeException('synthetic configuration database failure'); + } + return self::$enabled ? ['bot_token' => self::$token] : null; + } + } +} + +namespace { + use App\Models\Configurations; + use App\Models\User; + use App\Services\TicketTelegramConfig; + use App\Services\Telegram\AdministratorTelegramChannel; + use App\Services\Telegram\AdministratorTelegramLocalUnavailable; + use App\Services\Telegram\AdministratorTelegramPreflightException; + use App\Services\Telegram\AdministratorTelegramRemoteEffectUnknown; + use App\Services\Telegram\AdministratorTelegramTransport; + + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramDestination.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramTransport.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramPreflightException.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramLocalUnavailable.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramRemoteEffectUnknown.php'; + + final class AdministratorTelegramChannelConnection + { + public function transaction(callable $callback): mixed + { + Configurations::$transactions++; + try { + return $callback(); + } finally { + Configurations::$transactions--; + } + } + } + + final class AdministratorTelegramChannelQuery + { + public function __construct(private readonly string $name) {} + + public function lockForUpdate(): self + { + if (Configurations::$transactions !== 1) { + throw new RuntimeException('lock outside transaction'); + } + Configurations::$locks++; + return $this; + } + + public function first(): ?Configurations + { + if (Configurations::$failReads) { + throw new RuntimeException('synthetic binding database failure'); + } + $row = Configurations::$rows[$this->name] ?? null; + return $row === null ? null : clone $row; + } + } + + final class AdministratorTelegramChannelFakeTransport + implements AdministratorTelegramTransport + { + public array $calls = []; + public bool $fail = false; + + public function sendMessage( + string $botToken, + string $chatId, + string $text, + array $options = [] + ): int { + $this->calls[] = compact('botToken', 'chatId', 'text', 'options'); + if ($this->fail) { + throw new AdministratorTelegramRemoteEffectUnknown( + 'synthetic transport failure' + ); + } + return 9001; + } + } + + require dirname(__DIR__) . '/app/Services/Telegram/TelegramBotApiTransport.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramChannel.php'; + + $assert = static function (bool $condition, string $message): void { + if (!$condition) { + fwrite(STDERR, $message . PHP_EOL); + exit(1); + } + }; + $expectFailure = static function (callable $callback, string $message) use ($assert): void { + try { + $callback(); + } catch (Throwable $exception) { + return; + } + $assert(false, $message); + }; + $setBinding = static function (array $state): void { + Configurations::$rows[TicketTelegramConfig::BINDING] = new Configurations( + TicketTelegramConfig::BINDING, + json_encode($state, JSON_THROW_ON_ERROR) + ); + }; + + User::$rows[1] = new User(1); + $transport = new AdministratorTelegramChannelFakeTransport(); + $channel = new AdministratorTelegramChannel($transport); + + $setBinding(['bound_admin_id' => 1, 'chat_id' => '123456']); + $destination = $channel->currentDestination(); + $assert($destination !== null + && $destination->administratorId === 1 + && $destination->chatId === '123456' + && preg_match('/^[a-f0-9]{32}$/D', $destination->bindingGeneration) === 1 + && Configurations::$locks === 1 + && Configurations::$transactions === 0, + 'Legacy binding was not upgraded atomically with a valid generation.'); + + $messageId = $channel->send($destination, 'Test alert', [ + 'disable_web_page_preview' => 'true', + ]); + $assert($messageId === 9001 && count($transport->calls) === 1 + && $transport->calls[0]['chatId'] === '123456' + && $transport->calls[0]['botToken'] === TicketTelegramConfig::$token, + 'Authoritative destination was not sent exactly once.'); + + $expectFailure( + fn () => $channel->send($destination, 'Unsafe', ['parse_mode' => 'HTML']), + 'Unknown Telegram option was accepted.' + ); + $assert(count($transport->calls) === 1, + 'Rejected Telegram options reached the network transport.'); + + $setBinding([ + 'bound_admin_id' => 1, + 'chat_id' => '654321', + 'binding_generation' => bin2hex(random_bytes(16)), + ]); + $expectFailure( + fn () => $channel->send($destination, 'Stale destination'), + 'A stale binding generation was sent after rebind.' + ); + $assert(count($transport->calls) === 1, + 'A stale destination reached the Telegram transport.'); + + $setBinding([ + 'bound_admin_id' => 1, + 'chat_id' => '123456', + 'binding_generation' => $destination->bindingGeneration, + ]); + TicketTelegramConfig::$enabled = false; + $assert($channel->currentDestination() === null, + 'Disabled Telegram configuration still exposed a destination.'); + $assert($channel->boundDestination()?->equals($destination) === true, + 'Disabling outbound Telegram hid the retained administrator binding.'); + $expectFailure( + fn () => $channel->send($destination, 'Disabled channel'), + 'Disabled Telegram configuration still sent a message.' + ); + TicketTelegramConfig::$enabled = true; + $assert(count($transport->calls) === 1, + 'Disabled Telegram configuration reached the transport.'); + + TicketTelegramConfig::$failRuntime = true; + $localFailure = null; + try { + $channel->currentDestination(); + } catch (Throwable $exception) { + $localFailure = $exception; + } + $assert($localFailure instanceof AdministratorTelegramLocalUnavailable, + 'Configuration infrastructure failure was collapsed into disabled.'); + try { + $channel->send($destination, 'Local configuration failure'); + } catch (Throwable $exception) { + $localFailure = $exception; + } + $assert($localFailure instanceof AdministratorTelegramLocalUnavailable + && count($transport->calls) === 1, + 'Local configuration failure reached transport or became remote unknown.'); + TicketTelegramConfig::$failRuntime = false; + + Configurations::$failReads = true; + try { + $channel->send($destination, 'Local binding failure'); + } catch (Throwable $exception) { + $localFailure = $exception; + } + $assert($localFailure instanceof AdministratorTelegramLocalUnavailable + && count($transport->calls) === 1, + 'Binding read failure reached transport or became remote unknown.'); + Configurations::$failReads = false; + + $transport->fail = true; + $remoteFailure = null; + try { + $channel->send($destination, 'Unknown-effect send'); + } catch (Throwable $exception) { + $remoteFailure = $exception; + } + $assert($remoteFailure instanceof AdministratorTelegramRemoteEffectUnknown, + 'Transport failure was not classified as remote-effect unknown.'); + $assert(count($transport->calls) === 2, + 'A transport failure was internally retried.'); + $transport->fail = false; + + $setBinding([ + 'bound_admin_id' => 1, + 'chat_id' => '654321', + 'binding_generation' => bin2hex(random_bytes(16)), + ]); + $preflightFailure = null; + try { + $channel->send($destination, 'Known preflight failure'); + } catch (Throwable $exception) { + $preflightFailure = $exception; + } + $assert($preflightFailure instanceof AdministratorTelegramPreflightException + && count($transport->calls) === 2, + 'Destination change was not classified before the remote request.'); + + User::$rows[1]->enable = 0; + $assert($channel->currentDestination() === null, + 'Disabled administrator remained an eligible destination.'); + User::$rows[1]->enable = 1; + \App\Services\Config::$superAdministrators = '2'; + $assert($channel->currentDestination() === null, + 'Removed super administrator remained an eligible destination.'); + + echo "Administrator Telegram channel tests passed.\n"; +} diff --git a/web/tests/TicketTelegramNotifierSecurityTest.php b/web/tests/TicketTelegramNotifierSecurityTest.php index 53eba430..b64a0507 100644 --- a/web/tests/TicketTelegramNotifierSecurityTest.php +++ b/web/tests/TicketTelegramNotifierSecurityTest.php @@ -132,6 +132,17 @@ namespace App\Models { } return $updated; } + public function delete() + { + $deleted = 0; + foreach (TicketTelegramDelivery::$rows as $id => $row) { + if ($this->matches($row)) { + unset(TicketTelegramDelivery::$rows[$id]); + $deleted++; + } + } + return $deleted; + } private function matches(TicketTelegramDelivery $row): bool { foreach ($this->filters as $key => $value) { @@ -152,6 +163,7 @@ namespace App\Models { public static int $queries = 0; public static bool $failQueries = false; public static bool $failWrites = false; + public static mixed $bindingReadHook = null; public function __construct(public string $name = '', public string $value = '{}') {} public static function where($key, $value) { @@ -380,6 +392,10 @@ namespace { } public function first() { + if ($this->name === 'ticket_telegram_binding' + && is_callable(Configurations::$bindingReadHook)) { + (Configurations::$bindingReadHook)(); + } $row = Configurations::$rows[$this->name] ?? null; return $row === null ? null : clone $row; } @@ -430,6 +446,13 @@ namespace { require dirname(__DIR__) . '/app/Services/AdminPermission.php'; require dirname(__DIR__) . '/app/Services/TicketTelegramCredentialCipher.php'; require dirname(__DIR__) . '/app/Services/TicketTelegramConfig.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramDestination.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramTransport.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramPreflightException.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramLocalUnavailable.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramRemoteEffectUnknown.php'; + require dirname(__DIR__) . '/app/Services/Telegram/TelegramBotApiTransport.php'; + require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramChannel.php'; require dirname(__DIR__) . '/app/Services/Ticket/TicketWriteResult.php'; require dirname(__DIR__) . '/app/Services/Ticket/TicketEvent.php'; require dirname(__DIR__) . '/app/Services/Ticket/TicketTelegramNotificationResult.php'; @@ -656,6 +679,38 @@ namespace { && count(BotApi::$calls) === $callsAfterUnknown, 'An uncertain Telegram delivery was not fenced against replay.'); + // A concurrent rebind after reservation but before the network request is + // a known preflight failure: no message was sent and no unknown row remains. + $bindingBeforePreflight = $state(); + $bindingReads = 0; + Configurations::$bindingReadHook = function () use ( + &$bindingReads, + $setState, + $bindingBeforePreflight + ): void { + $bindingReads++; + if ($bindingReads === 2) { + $setState([ + 'bound_admin_id' => 1, + 'chat_id' => '123456', + 'binding_generation' => bin2hex(random_bytes(16)), + ]); + } + }; + $callsBeforePreflight = count(BotApi::$calls); + $assert(TicketTelegramNotifier::notify($ticketEvent('user_reply', 47)) + === TicketTelegramNotificationResult::Failed, + 'Concurrent rebind preflight was reported as a successful send.'); + Configurations::$bindingReadHook = null; + $preflightRows = array_filter( + TicketTelegramDelivery::$rows, + fn ($row) => $row->ticket_message_id === 47 + ); + $assert(count(BotApi::$calls) === $callsBeforePreflight + && $preflightRows === [], + 'Preflight failure reached Telegram or was persisted as unknown.'); + $setState($bindingBeforePreflight); + TicketThreadService::$commands = []; TicketThreadService::$results = []; TicketThreadService::$closed = false;