diff --git a/web/app/Controllers/TelegramWebhookController.php b/web/app/Controllers/TelegramWebhookController.php index 8444ba9f..5a17e8f9 100644 --- a/web/app/Controllers/TelegramWebhookController.php +++ b/web/app/Controllers/TelegramWebhookController.php @@ -31,7 +31,9 @@ final class TelegramWebhookController extends BaseController TicketTelegramNotifier::handleUpdate($update); return $response->withJson(['ok' => true]); } catch (\Throwable $exception) { - error_log('Administrator Telegram binding storage failed'); + // Database errors may be retryable, but must never expose bot + // credentials or administrator reply content in logs/responses. + error_log('Administrator Telegram update processing failed'); return $response->withJson(['ok' => false], 503); } } diff --git a/web/app/Services/Ticket/ReplyTicketCommand.php b/web/app/Services/Ticket/ReplyTicketCommand.php index ed28e3f5..4a253e11 100644 --- a/web/app/Services/Ticket/ReplyTicketCommand.php +++ b/web/app/Services/Ticket/ReplyTicketCommand.php @@ -12,7 +12,8 @@ final readonly class ReplyTicketCommand public mixed $request, public ?int $ownerId = null, public bool $actorIsAdmin = false, - public string $requestKey = '' + public string $requestKey = '', + public ?int $requiredCurrentStatus = null ) { } } diff --git a/web/app/Services/Ticket/TicketReplyStateConflict.php b/web/app/Services/Ticket/TicketReplyStateConflict.php new file mode 100644 index 00000000..b91d72f3 --- /dev/null +++ b/web/app/Services/Ticket/TicketReplyStateConflict.php @@ -0,0 +1,11 @@ +status, [0, 1], true)) { throw new \InvalidArgumentException('工单状态无效'); } + if ($command->requiredCurrentStatus !== null + && !in_array($command->requiredCurrentStatus, [0, 1], true)) { + throw new \InvalidArgumentException('工单当前状态限制无效'); + } $content = $this->cleanRequired($command->content, '请填写回复内容'); $event = $command->actorIsAdmin ? '管理员回复工单' : '用户回复工单'; $fingerprints = TicketAttachmentService::fingerprints($command->request); @@ -154,6 +158,10 @@ final class TicketThreadService $intent->delete(); return null; } + if ($command->requiredCurrentStatus !== null + && (int) $root->status !== $command->requiredCurrentStatus) { + throw new TicketReplyStateConflict(); + } $event = $command->status === 1 && (int) $root->status !== 1 ? '工单重新开启' diff --git a/web/app/Services/TicketTelegramNotifier.php b/web/app/Services/TicketTelegramNotifier.php index f60312ea..78faf2dd 100644 --- a/web/app/Services/TicketTelegramNotifier.php +++ b/web/app/Services/TicketTelegramNotifier.php @@ -6,10 +6,15 @@ use App\Models\CloudInstance; use App\Models\Configurations; use App\Models\TicketTelegramDelivery; use App\Models\User; +use App\Services\Ticket\ReplyTicketCommand; use App\Services\Ticket\TicketEvent; +use App\Services\Ticket\TicketIdempotencyConflict; +use App\Services\Ticket\TicketNotificationDispatcher; +use App\Services\Ticket\TicketReplyStateConflict; +use App\Services\Ticket\TicketThreadService; use TelegramBot\Api\BotApi; -/** Administrator-only ticket alerts. No Telegram user login or ticket reply commands. */ +/** Administrator-only ticket alerts and replies to mapped notification messages. */ final class TicketTelegramNotifier { private const KEY = TicketTelegramConfig::BINDING; @@ -115,7 +120,7 @@ final class TicketTelegramNotifier { $command = self::bindingCommand($update); if ($command === null) { - return false; + return self::handleTicketReply($update); } $bound = (new Configurations())->getConnection()->transaction(function () use ($command) { $row = Configurations::where('name', self::KEY)->lockForUpdate()->first(); @@ -148,6 +153,156 @@ final class TicketTelegramNotifier return true; } + private static function handleTicketReply(array $update): bool + { + $command = self::ticketReplyCommand($update); + 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)) { + return false; + } + + $delivery = TicketTelegramDelivery::where( + 'binding_generation', (string) $state['binding_generation'] + )->where('chat_id', $command['chat_id']) + ->where('telegram_message_id', $command['reply_to_message_id']) + ->where('state', 'sent')->first(); + if ($delivery === null || (int) $delivery->bound_admin_id !== $adminId) { + self::sendReplyAcknowledgement( + $command['chat_id'], + $command['message_id'], + '无法识别这条工单通知,请在管理后台处理。' + ); + return true; + } + + try { + $result = (new TicketThreadService())->reply(new ReplyTicketCommand( + (int) $delivery->ticket_id, + $adminId, + $command['text'], + 1, + null, + null, + true, + 'telegram.update.' . $command['update_id'], + 1 + )); + } catch (TicketReplyStateConflict $exception) { + self::sendReplyAcknowledgement( + $command['chat_id'], $command['message_id'], $exception->getMessage() + ); + return true; + } catch (TicketIdempotencyConflict $exception) { + self::sendReplyAcknowledgement( + $command['chat_id'], + $command['message_id'], + '这条 Telegram 更新已用于其他回复,请在管理后台核对。' + ); + return true; + } catch (\InvalidArgumentException $exception) { + self::sendReplyAcknowledgement( + $command['chat_id'], $command['message_id'], $exception->getMessage() + ); + return true; + } + + if ($result === null) { + self::sendReplyAcknowledgement( + $command['chat_id'], + $command['message_id'], + '工单已不存在,请在管理后台核对。' + ); + return true; + } + if (!$result->wasCreated) { + return true; + } + + (new TicketNotificationDispatcher())->dispatch(TicketEvent::adminReply($result)); + self::sendReplyAcknowledgement( + $command['chat_id'], + $command['message_id'], + '✅ 已回复工单 #' . (int) $result->root->id + . "\n用户已可在工单页面查看。" + ); + return true; + } + + private static function ticketReplyCommand(array $update): ?array + { + $message = $update['message'] ?? null; + $updateId = $update['update_id'] ?? null; + if (!is_array($message) + || (!is_int($updateId) && !is_string($updateId)) + || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $updateId) !== 1 + || ($message['chat']['type'] ?? '') !== 'private' + || !empty($message['from']['is_bot']) + || !empty($message['via_bot']) + || !empty($message['sender_chat']) + || !empty($message['forward_origin']) + || !empty($message['forward_from']) + || !empty($message['forward_date'])) { + return null; + } + $chatId = (string) ($message['chat']['id'] ?? ''); + $senderId = (string) ($message['from']['id'] ?? ''); + $messageId = $message['message_id'] ?? null; + $replyMessageId = $message['reply_to_message']['message_id'] ?? null; + $text = $message['text'] ?? null; + if (preg_match('/^[1-9][0-9]{0,18}$/D', $chatId) !== 1 + || $chatId !== $senderId + || (!is_int($messageId) && !is_string($messageId)) + || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $messageId) !== 1 + || (!is_int($replyMessageId) && !is_string($replyMessageId)) + || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $replyMessageId) !== 1 + || !is_string($text) + || trim($text) === '' + || str_starts_with(trim($text), '/')) { + return null; + } + foreach (['animation', 'audio', 'document', 'photo', 'sticker', 'video', + 'video_note', 'voice'] as $media) { + if (array_key_exists($media, $message)) { + return null; + } + } + return [ + 'update_id' => (string) $updateId, + 'chat_id' => $chatId, + 'message_id' => (int) $messageId, + 'reply_to_message_id' => (int) $replyMessageId, + 'text' => trim($text), + ]; + } + + private static function sendReplyAcknowledgement( + string $chatId, + int $replyToMessageId, + string $text + ): void { + try { + $config = TicketTelegramConfig::runtime(true); + (new BotApi($config['bot_token']))->call('sendMessage', [ + 'chat_id' => $chatId, + 'text' => $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. + error_log('Administrator Telegram ticket reply confirmation failed'); + } + } + public static function notify(TicketEvent $event): bool { $ticketId = (int) $event->result->root->id; diff --git a/web/tests/TicketReplyTransactionTest.php b/web/tests/TicketReplyTransactionTest.php index 406c6171..0edfe373 100644 --- a/web/tests/TicketReplyTransactionTest.php +++ b/web/tests/TicketReplyTransactionTest.php @@ -9,6 +9,7 @@ require dirname(__DIR__) . '/vendor/autoload.php'; use App\Services\TicketAttachmentService; use App\Services\Ticket\OpenTicketCommand; use App\Services\Ticket\ReplyTicketCommand; +use App\Services\Ticket\TicketReplyStateConflict; use App\Services\Ticket\TicketThreadService; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -185,6 +186,23 @@ $assert((string) $attachment->original_name === 'ok.png', $assert(is_file(BASE_PATH . '/storage/ticket-attachments/' . $attachment->storage_key), 'Successful attachment file is missing.'); +// Telegram replies require the ticket to remain open at the moment the root +// row is locked. A stale preflight read must never reopen a closed thread. +try { + $service->reply(new ReplyTicketCommand( + 1, 9, 'must stay closed', 1, $request([]), null, true, + 'telegram.update.500', 1 + )); + throw new RuntimeException('A guarded administrator reply reopened a closed ticket.'); +} catch (TicketReplyStateConflict $exception) { + // Expected; the assertions below verify the transaction rollback. +} +$assert((int) Capsule::table('ticket')->where('id', 1)->value('status') === 0 + && Capsule::table('ticket')->where('rootid', 1)->count() === 1 + && !Capsule::table('ticket_write_requests') + ->where('request_key', 'telegram.update.500')->exists(), + 'Closed-ticket Telegram guard left a reply or idempotency intent behind.'); + // Closing and reopening are observable thread behaviors. Reopening a closed // thread has its own event so notification adapters can explain the change. $reopened = $service->reply(new ReplyTicketCommand( diff --git a/web/tests/TicketTelegramNotifierSecurityTest.php b/web/tests/TicketTelegramNotifierSecurityTest.php index c5919267..62249081 100644 --- a/web/tests/TicketTelegramNotifierSecurityTest.php +++ b/web/tests/TicketTelegramNotifierSecurityTest.php @@ -209,6 +209,86 @@ namespace App\Services\Cloud { } } +namespace App\Services\Ticket { + final readonly class ReplyTicketCommand + { + public function __construct( + public int $ticketId, + public int $actorId, + public string $content, + public int $status, + public mixed $request, + public ?int $ownerId = null, + public bool $actorIsAdmin = false, + public string $requestKey = '', + public ?int $requiredCurrentStatus = null + ) {} + } + + final class TicketReplyStateConflict extends \RuntimeException + { + public function __construct() + { + parent::__construct('工单已关闭,无法通过 Telegram 回复', 409); + } + } + + final class TicketIdempotencyConflict extends \RuntimeException {} + + final class TicketThreadService + { + public static array $commands = []; + public static array $results = []; + public static bool $closed = false; + public static bool $fail = false; + + public function reply(ReplyTicketCommand $command): ?TicketWriteResult + { + if (self::$fail) { + throw new \RuntimeException('synthetic ticket database failure'); + } + if (self::$closed) { + throw new TicketReplyStateConflict(); + } + self::$commands[] = $command; + if (isset(self::$results[$command->requestKey])) { + $previous = self::$results[$command->requestKey]; + return new TicketWriteResult( + $previous->root, + $previous->message, + $previous->event, + $previous->attachments, + false + ); + } + $root = new \App\Models\Ticket(); + $root->id = $command->ticketId; + $root->userid = 7; + $root->title = 'Example'; + $root->rootid = 0; + $root->status = 1; + $message = clone $root; + $message->id = 900 + count(self::$results); + $message->rootid = $root->id; + $message->content = $command->content; + $result = new TicketWriteResult( + $root, $message, '管理员回复工单', [], true + ); + self::$results[$command->requestKey] = $result; + return $result; + } + } + + final class TicketNotificationDispatcher + { + public static array $events = []; + public function dispatch(TicketEvent $event): void + { + self::$events[] = $event; + } + } +} + namespace App\Controllers { class BaseController {} class AdminController extends BaseController {} @@ -246,6 +326,8 @@ namespace { use App\Services\TicketTelegramCredentialCipher; use App\Services\TicketTelegramNotifier; use App\Services\Ticket\TicketEvent; + use App\Services\Ticket\TicketNotificationDispatcher; + use App\Services\Ticket\TicketThreadService; use App\Services\Ticket\TicketWriteResult; use App\Controllers\Admin\TelegramController; use App\Controllers\TelegramWebhookController; @@ -389,6 +471,23 @@ namespace { $result = new TicketWriteResult($root, $message, '新工单', [new \stdClass(), new \stdClass()]); return $kind === 'created' ? TicketEvent::created($result) : TicketEvent::userReply($result); }; + $ticketReply = function ( + int $updateId, + string $text = 'Telegram administrator reply', + string $chatId = '123456', + int $replyToMessageId = 1000 + ): array { + return [ + 'update_id' => $updateId, + 'message' => [ + 'message_id' => 2000 + $updateId, + 'chat' => ['id' => $chatId, 'type' => 'private'], + 'from' => ['id' => $chatId, 'is_bot' => false], + 'text' => $text, + 'reply_to_message' => ['message_id' => $replyToMessageId], + ], + ]; + }; $System_Config = ['enable_telegram' => true, 'telegram_token' => '123456789:' . str_repeat('A', 35), 'telegram_request_token' => 'synthetic-webhook-secret-123', 'super_admin' => '1,2', 'baseUrl' => 'https://example.invalid']; @@ -538,6 +637,75 @@ namespace { && !TicketTelegramNotifier::notify($ticketEvent('user_reply', 43)) && count(BotApi::$calls) === $callsAfterUnknown, 'An uncertain Telegram delivery was not fenced against replay.'); + + TicketThreadService::$commands = []; + TicketThreadService::$results = []; + TicketThreadService::$closed = false; + TicketThreadService::$fail = false; + TicketNotificationDispatcher::$events = []; + $reply = $ticketReply(501); + $assert(TicketTelegramNotifier::handleUpdate($reply), + 'A reply to a mapped Telegram ticket notification was rejected.'); + $replyCommand = TicketThreadService::$commands[0] ?? null; + $replyReceipt = BotApi::$calls[count(BotApi::$calls) - 1] ?? null; + $assert($replyCommand !== null + && $replyCommand->ticketId === 42 + && $replyCommand->actorId === 1 + && $replyCommand->actorIsAdmin + && $replyCommand->requiredCurrentStatus === 1 + && $replyCommand->requestKey === 'telegram.update.501' + && count(TicketNotificationDispatcher::$events) === 1 + && $replyReceipt[0] === 'sendMessage' + && str_contains($replyReceipt[1]['text'], '已回复工单 #42'), + 'Mapped Telegram reply did not reuse the guarded ticket workflow.'); + $receiptCount = count(BotApi::$calls); + $dispatchCount = count(TicketNotificationDispatcher::$events); + $assert(TicketTelegramNotifier::handleUpdate($reply) + && count(TicketNotificationDispatcher::$events) === $dispatchCount + && count(BotApi::$calls) === $receiptCount, + 'A replayed Telegram update duplicated the reply notification or receipt.'); + + $groupReply = $ticketReply(502); + $groupReply['message']['chat']['type'] = 'group'; + $forwardedReply = $ticketReply(503); + $forwardedReply['message']['forward_origin'] = ['type' => 'user']; + $wrongChatReply = $ticketReply(504, 'wrong chat', '654321'); + foreach ([$groupReply, $forwardedReply, $wrongChatReply] as $unsafeReply) { + $assert(!TicketTelegramNotifier::handleUpdate($unsafeReply), + 'A group, forwarded or wrong-chat Telegram reply reached the ticket workflow.'); + } + + TicketThreadService::$closed = true; + $closedReply = $ticketReply(505); + $assert(TicketTelegramNotifier::handleUpdate($closedReply), + 'A closed-ticket Telegram reply was not handled terminally.'); + $closedReceipt = BotApi::$calls[count(BotApi::$calls) - 1] ?? null; + $assert($closedReceipt[0] === 'sendMessage' + && str_contains($closedReceipt[1]['text'], '工单已关闭'), + 'Closed-ticket Telegram reply did not receive a safe explanation.'); + TicketThreadService::$closed = false; + + BotApi::$fail = true; + $dispatchBeforeFailedReceipt = count(TicketNotificationDispatcher::$events); + $assert(TicketTelegramNotifier::handleUpdate($ticketReply(506)), + 'A failed post-commit Telegram receipt changed a saved ticket reply into failure.'); + BotApi::$fail = false; + $assert(count(TicketNotificationDispatcher::$events) + === $dispatchBeforeFailedReceipt + 1, + 'A failed Telegram receipt rolled back or suppressed the committed ticket reply.'); + + TicketThreadService::$fail = true; + $webhookForReplyFailure = new TelegramWebhookController(); + $replyFailureRequest = new TelegramTestRequest( + TicketTelegramConfig::runtime(true)['webhook_secret'], + new TelegramTestStream((string) json_encode($ticketReply(507))) + ); + $replyFailureResponse = $webhookForReplyFailure->handle( + $replyFailureRequest, new TelegramTestResponse(), [] + ); + TicketThreadService::$fail = false; + $assert($replyFailureResponse->status === 503, + 'A pre-commit Telegram ticket database failure was acknowledged as success.'); $calls = count(BotApi::$calls); foreach ([['bound_admin_id' => 1, 'chat_id' => '-100123456'], ['bound_admin_id' => 2, 'chat_id' => '123456'],