diff --git a/web/app/Models/TicketTelegramDelivery.php b/web/app/Models/TicketTelegramDelivery.php new file mode 100644 index 00000000..8b1dac20 --- /dev/null +++ b/web/app/Models/TicketTelegramDelivery.php @@ -0,0 +1,19 @@ + 'int', + 'bound_admin_id' => 'int', + 'ticket_id' => 'int', + 'ticket_message_id' => 'int', + 'telegram_message_id' => 'int', + 'created_at' => 'int', + 'sent_at' => 'int', + 'updated_at' => 'int', + ]; +} diff --git a/web/app/Services/TicketTelegramNotifier.php b/web/app/Services/TicketTelegramNotifier.php index 32697f68..f60312ea 100644 --- a/web/app/Services/TicketTelegramNotifier.php +++ b/web/app/Services/TicketTelegramNotifier.php @@ -4,6 +4,7 @@ namespace App\Services; use App\Models\CloudInstance; use App\Models\Configurations; +use App\Models\TicketTelegramDelivery; use App\Models\User; use App\Services\Ticket\TicketEvent; use TelegramBot\Api\BotApi; @@ -126,7 +127,11 @@ final class TicketTelegramNotifier return false; } // One-time token consumed atomically; replay cannot change the recipient. - $row->value = json_encode(['bound_admin_id' => $adminId, 'chat_id' => $command['chat_id']], JSON_THROW_ON_ERROR); + $row->value = json_encode([ + 'bound_admin_id' => $adminId, + 'chat_id' => $command['chat_id'], + 'binding_generation' => bin2hex(random_bytes(16)), + ], JSON_THROW_ON_ERROR); if (!$row->save()) { throw new \RuntimeException('Administrator Telegram binding storage failed'); } @@ -148,7 +153,7 @@ final class TicketTelegramNotifier $ticketId = (int) $event->result->root->id; try { $config = TicketTelegramConfig::runtime(true); - $state = self::readState(Configurations::where('name', self::KEY)->first()); + $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 @@ -156,12 +161,32 @@ final class TicketTelegramNotifier return false; } $text = self::notificationText($event); - (new BotApi($config['bot_token']))->call('sendMessage', [ - 'chat_id' => (string) $chatId, - 'text' => $text, - 'disable_web_page_preview' => 'true', - ], 10); - return true; + [$delivery, $ownsDispatch] = self::reserveDelivery($event, $state, $text); + if (!$ownsDispatch) { + return (string) $delivery->state === 'sent'; + } + try { + $result = (new BotApi($config['bot_token']))->call('sendMessage', [ + 'chat_id' => (string) $chatId, + 'text' => $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, + 'state' => 'sent', + 'sent_at' => time(), + 'updated_at' => time(), + ]); + if ((int) $updated !== 1) { + throw new \RuntimeException('Telegram delivery finalization failed'); + } + return true; + } catch (\Throwable $exception) { + self::markDeliveryUnknown((int) $delivery->id); + throw $exception; + } } catch (\Throwable $exception) { // SDK error URLs may contain bot secrets. Never log their messages. error_log('Administrator ticket Telegram delivery failed; ticket=' . $ticketId); @@ -169,6 +194,118 @@ final class TicketTelegramNotifier } } + /** + * @return array{TicketTelegramDelivery, bool} + */ + private static function reserveDelivery(TicketEvent $event, array $state, string $text): array + { + $generation = (string) $state['binding_generation']; + $messageId = (int) $event->result->message->id; + $kind = (string) $event->kind; + $existing = self::deliveryForEvent($generation, $messageId, $kind); + if ($existing !== null) { + return [$existing, false]; + } + + $delivery = new TicketTelegramDelivery(); + $delivery->binding_generation = $generation; + $delivery->bound_admin_id = (int) $state['bound_admin_id']; + $delivery->chat_id = (string) $state['chat_id']; + $delivery->ticket_id = (int) $event->result->root->id; + $delivery->ticket_message_id = $messageId; + $delivery->event_kind = $kind; + $delivery->telegram_message_id = null; + $delivery->state = 'dispatching'; + $delivery->content_hash = hash('sha256', $text); + $delivery->created_at = time(); + $delivery->sent_at = null; + $delivery->updated_at = time(); + try { + if (!$delivery->save()) { + throw new \RuntimeException('Telegram delivery reservation failed'); + } + return [$delivery, true]; + } catch (\Throwable $exception) { + // The unique event key elects one sender when dispatchers race. + $existing = self::deliveryForEvent($generation, $messageId, $kind); + if ($existing !== null) { + return [$existing, false]; + } + throw $exception; + } + } + + private static function deliveryForEvent( + string $generation, + int $messageId, + string $kind + ): ?TicketTelegramDelivery { + return TicketTelegramDelivery::where('binding_generation', $generation) + ->where('ticket_message_id', $messageId) + ->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 { + TicketTelegramDelivery::where('id', $deliveryId) + ->where('state', 'dispatching')->update([ + 'telegram_message_id' => null, + 'state' => 'unknown', + 'updated_at' => time(), + ]); + } catch (\Throwable $exception) { + error_log('Administrator ticket Telegram delivery reconciliation failed'); + } + } + + private static function deliveryBindingState(): array + { + $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; + }); + } + private static function notificationText(TicketEvent $event): string { $root = $event->result->root; diff --git a/web/app/Services/UserDataDeletionService.php b/web/app/Services/UserDataDeletionService.php index 2fb7a2cf..0368c4c9 100644 --- a/web/app/Services/UserDataDeletionService.php +++ b/web/app/Services/UserDataDeletionService.php @@ -14,6 +14,7 @@ class UserDataDeletionService ['paylist', 'userid'], ['ss_invite_code', 'user_id'], ['ticket', 'userid'], ['ticket_read_states', 'reader_id'], ['ticket_write_requests', 'actor_user_id'], + ['ticket_telegram_deliveries', 'bound_admin_id'], ['ticket_user_guards', 'user_id'], ['user_survey_responses', 'user_id'], ['cloud_ssh_keys', 'user_id'], ['cloud_sessions', 'user_id'], @@ -268,6 +269,8 @@ class UserDataDeletionService $connection, 'ticket_read_states', 'ticket_id', $roots); $deleted += $this->deleteWhereIn( $connection, 'ticket_write_requests', 'ticket_id', $roots); + $deleted += $this->deleteWhereIn( + $connection, 'ticket_telegram_deliveries', 'ticket_id', $roots); $deleted += $this->deleteWhereIn($connection, 'ticket', 'rootid', $roots); } $deleted += $this->deleteWhereIn($connection, 'ticket_attachments', 'user_id', $ids); diff --git a/web/sql/ss.sql b/web/sql/ss.sql index 50375217..7a8c40d5 100644 --- a/web/sql/ss.sql +++ b/web/sql/ss.sql @@ -375,6 +375,27 @@ CREATE TABLE `ticket_write_requests` ( KEY `ticket_write_created` (`created_at`,`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE `ticket_telegram_deliveries` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `binding_generation` char(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `bound_admin_id` bigint(20) NOT NULL, + `chat_id` varchar(20) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `ticket_id` bigint(20) NOT NULL, + `ticket_message_id` bigint(20) NOT NULL, + `event_kind` varchar(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `telegram_message_id` bigint(20) unsigned DEFAULT NULL, + `state` varchar(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'dispatching', + `content_hash` char(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `created_at` bigint(20) unsigned NOT NULL DEFAULT 0, + `sent_at` bigint(20) unsigned DEFAULT NULL, + `updated_at` bigint(20) unsigned NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + UNIQUE KEY `ticket_telegram_event` (`binding_generation`,`ticket_message_id`,`event_kind`), + UNIQUE KEY `ticket_telegram_message` (`binding_generation`,`chat_id`,`telegram_message_id`), + KEY `ticket_telegram_ticket` (`ticket_id`,`ticket_message_id`), + KEY `ticket_telegram_admin` (`bound_admin_id`,`created_at`,`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + CREATE TABLE `ticket_user_guards` ( `user_id` bigint(20) NOT NULL, `updated_at` bigint(20) unsigned NOT NULL DEFAULT 0, diff --git a/web/tests/TicketTelegramDeliverySchemaContractTest.php b/web/tests/TicketTelegramDeliverySchemaContractTest.php new file mode 100644 index 00000000..e3ad7648 --- /dev/null +++ b/web/tests/TicketTelegramDeliverySchemaContractTest.php @@ -0,0 +1,31 @@ +where($key, $value); + } + public function save() + { + if ($this->id === null) { + foreach (self::$rows as $row) { + if ($row->binding_generation === $this->binding_generation + && $row->ticket_message_id === $this->ticket_message_id + && $row->event_kind === $this->event_kind) { + throw new \RuntimeException('synthetic duplicate delivery'); + } + } + $this->id = self::$nextId++; + } + self::$rows[$this->id] = $this; + return true; + } + } + + final class TicketTelegramDeliveryQuery + { + private array $filters = []; + public function where($key, $value) + { + $this->filters[$key] = $value; + return $this; + } + public function first() + { + foreach (TicketTelegramDelivery::$rows as $row) { + if ($this->matches($row)) { + return $row; + } + } + return null; + } + public function update(array $values) + { + $updated = 0; + foreach (TicketTelegramDelivery::$rows as $row) { + if (!$this->matches($row)) { + continue; + } + foreach ($values as $key => $value) { + $row->$key = $value; + } + TicketTelegramDelivery::$rows[$row->id] = $row; + $updated++; + } + return $updated; + } + private function matches(TicketTelegramDelivery $row): bool + { + foreach ($this->filters as $key => $value) { + if (($row->$key ?? null) != $value) { + return false; + } + } + return true; + } + } + final class Configurations { public static array $rows = []; @@ -138,6 +219,7 @@ namespace TelegramBot\Api { { public static array $calls = []; public static bool $fail = false; + public static int $nextMessageId = 1000; public function __construct(private string $token) {} public function call($method, $parameters, $timeout) { @@ -145,7 +227,8 @@ namespace TelegramBot\Api { if (self::$fail) { throw new \RuntimeException('synthetic SDK failure with token=' . $this->token); } - return true; + return $method === 'sendMessage' + ? ['message_id' => self::$nextMessageId++] : true; } } } @@ -154,6 +237,7 @@ namespace { use App\Models\Configurations; use App\Models\CloudInstance; use App\Models\Ticket; + use App\Models\TicketTelegramDelivery; use App\Models\User; use App\Services\Auth; use App\Services\Cloud\CloudSecrets; @@ -287,7 +371,7 @@ namespace { return ['message' => ['chat' => ['id' => $chatId, 'type' => 'private'], 'from' => ['id' => $chatId, 'is_bot' => false], 'text' => '/start ' . $code]]; }; - $ticketEvent = function (string $kind = 'created'): TicketEvent { + $ticketEvent = function (string $kind = 'created', int $messageId = 42): TicketEvent { $root = new Ticket(); $root->id = 42; $root->userid = 7; @@ -300,6 +384,7 @@ namespace { $root->priority = 'high'; $root->instance_id = 55; $message = clone $root; + $message->id = $messageId; $message->content = "Body\nSecond line"; $result = new TicketWriteResult($root, $message, '新工单', [new \stdClass(), new \stdClass()]); return $kind === 'created' ? TicketEvent::created($result) : TicketEvent::userReply($result); @@ -374,7 +459,11 @@ namespace { $assert(BotApi::$calls === [], 'A failed binding state write still sent a success confirmation.'); $binding = TicketTelegramNotifier::createBinding(1); $assert(TicketTelegramNotifier::handleUpdate($update($binding['code'])), 'Valid private binding failed.'); - $assert($state() === ['bound_admin_id' => 1, 'chat_id' => '123456'], 'Consumed token or recipient state is incorrect.'); + $boundState = $state(); + $assert(($boundState['bound_admin_id'] ?? 0) === 1 + && ($boundState['chat_id'] ?? '') === '123456' + && preg_match('/^[a-f0-9]{32}$/D', (string) ($boundState['binding_generation'] ?? '')) === 1, + 'Consumed token, recipient or binding generation state is incorrect.'); $assert(count(BotApi::$calls) === 1 && BotApi::$calls[0][0] === 'sendMessage' && BotApi::$calls[0][1]['chat_id'] === '123456' @@ -400,13 +489,19 @@ namespace { $assert(TicketTelegramNotifier::handleUpdate($update($binding['code'])), 'A failed Telegram confirmation changed a committed binding into a webhook failure.'); BotApi::$fail = false; - $assert($state() === ['bound_admin_id' => 1, 'chat_id' => '123456'], + $failedConfirmationState = $state(); + $assert(($failedConfirmationState['bound_admin_id'] ?? 0) === 1 + && ($failedConfirmationState['chat_id'] ?? '') === '123456' + && preg_match('/^[a-f0-9]{32}$/D', (string) ($failedConfirmationState['binding_generation'] ?? '')) === 1, 'A failed Telegram confirmation rolled back the committed binding.'); $callsAfterFailedConfirmation = count(BotApi::$calls); $assert(!TicketTelegramNotifier::handleUpdate($update($binding['code'])) && count(BotApi::$calls) === $callsAfterFailedConfirmation, 'A replay after a failed confirmation resent or re-consumed the binding code.'); BotApi::$calls = []; + BotApi::$nextMessageId = 1000; + TicketTelegramDelivery::$rows = []; + TicketTelegramDelivery::$nextId = 1; $setState(['bound_admin_id' => 1, 'chat_id' => '123456']); $assert(TicketTelegramNotifier::notify($ticketEvent()), 'Eligible administrator was not notified.'); $alertText = BotApi::$calls[0][1]['text']; @@ -423,6 +518,26 @@ namespace { && !str_contains($alertText, 'owner-secret@example.test') && !str_contains($alertText, '+15550001111') && !isset(BotApi::$calls[0][1]['parse_mode']), 'Rich alert content or plain-text privacy boundary is wrong.'); + $delivery = TicketTelegramDelivery::$rows[1] ?? null; + $assert($delivery !== null && $delivery->state === 'sent' + && $delivery->telegram_message_id === 1000 + && preg_match('/^[a-f0-9]{32}$/D', $delivery->binding_generation) === 1, + 'Successful Telegram notification did not persist a reply mapping.'); + $assert(TicketTelegramNotifier::notify($ticketEvent()) + && count(BotApi::$calls) === 1 + && count(TicketTelegramDelivery::$rows) === 1, + 'A repeated ticket event was sent or persisted more than once.'); + BotApi::$fail = true; + $assert(!TicketTelegramNotifier::notify($ticketEvent('user_reply', 43)), + 'An uncertain Telegram send was reported as successful.'); + BotApi::$fail = false; + $uncertain = TicketTelegramDelivery::$rows[2] ?? null; + $callsAfterUnknown = count(BotApi::$calls); + $assert($uncertain !== null && $uncertain->state === 'unknown' + && $uncertain->telegram_message_id === null + && !TicketTelegramNotifier::notify($ticketEvent('user_reply', 43)) + && count(BotApi::$calls) === $callsAfterUnknown, + 'An uncertain Telegram delivery was not fenced against replay.'); $calls = count(BotApi::$calls); foreach ([['bound_admin_id' => 1, 'chat_id' => '-100123456'], ['bound_admin_id' => 2, 'chat_id' => '123456'],