You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/TicketTelegramNotifierSecur...

993 lines
46 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
// In-memory doubles only: no application bootstrap, database, Redis or Telegram.
namespace App\Models {
final class User
{
public static array $users = [];
public function __construct(
public int $id,
public int $is_admin = 0,
public int $enable = 1,
public string $user_name = '',
public string $email = '',
public string $phone = ''
) {}
public static function find($id) { return self::$users[(int) $id] ?? null; }
}
final class Ticket
{
public int $id = 0;
public int $userid = 0;
public string $title = '';
public string $content = '';
public int $rootid = 0;
public int $datetime = 0;
public int $status = 1;
public string $ticket_type = 'technical';
public string $priority = 'medium';
public ?int $instance_id = null;
}
final class CloudInstance
{
public static array $instances = [];
public function __construct(public int $id, public int $user_id, public string $name) {}
public static function where($key, $value)
{
return (new CloudInstanceQuery())->where($key, $value);
}
}
final class CloudInstanceQuery
{
private array $filters = [];
public function where($key, $value)
{
$this->filters[$key] = $value;
return $this;
}
public function first()
{
foreach (CloudInstance::$instances as $instance) {
foreach ($this->filters as $key => $value) {
if (($instance->$key ?? null) != $value) {
continue 2;
}
}
return $instance;
}
return null;
}
}
final class TicketTelegramDelivery
{
public static array $rows = [];
public static int $nextId = 1;
public ?int $id = null;
public string $binding_generation = '';
public int $bound_admin_id = 0;
public string $chat_id = '';
public int $ticket_id = 0;
public int $ticket_message_id = 0;
public string $event_kind = '';
public ?int $telegram_message_id = null;
public string $state = '';
public string $content_hash = '';
public int $created_at = 0;
public ?int $sent_at = null;
public int $updated_at = 0;
public static function where($key, $value)
{
return (new TicketTelegramDeliveryQuery())->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 = [];
public static int $transactions = 0;
public static int $locks = 0;
public static int $writes = 0;
public static int $queries = 0;
public static bool $failQueries = false;
public static bool $failWrites = false;
public function __construct(public string $name = '', public string $value = '{}') {}
public static function where($key, $value)
{
if (self::$failQueries) { throw new \RuntimeException('SQLSTATE synthetic-internal-detail'); }
self::$queries++;
return new \TelegramTestQuery($value);
}
public static function whereIn($key, $values)
{
if (self::$failQueries) { throw new \RuntimeException('SQLSTATE synthetic-internal-detail'); }
self::$queries++;
return new \TelegramTestWhereInQuery($values);
}
public function getConnection() { return new \TelegramTestConnection(); }
public function save()
{
if (self::$failWrites) { return false; }
self::$rows[$this->name] = $this;
self::$writes++;
return true;
}
}
}
namespace App\Services {
final class Auth
{
public static $user;
public static function getUser() { return self::$user; }
}
final class RedisClient
{
public static array $store = [];
public static array $ttls = [];
public static bool $fail = false;
public static int $gets = 0;
public static int $sets = 0;
public static int $deletes = 0;
public function __construct()
{
if (self::$fail) { throw new \RuntimeException('Redis unavailable'); }
}
public function getClient() { return new \TelegramTestRedisBackend(); }
public function setex($key, $ttl, $value) { return $this->getClient()->setex($key, $ttl, $value); }
public function del($key) { return $this->getClient()->del($key); }
}
}
namespace App\Services\Cloud {
final class CloudSecrets
{
public static int $calls = 0;
public static function key(string $purpose): string { self::$calls++; return str_repeat("\x42", 32); }
}
}
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 {}
}
namespace TelegramBot\Api {
final class BotApi
{
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)
{
self::$calls[] = [$method, $parameters, $timeout];
if (self::$fail) {
throw new \RuntimeException('synthetic SDK failure with token=' . $this->token);
}
return $method === 'sendMessage'
? ['message_id' => self::$nextMessageId++] : true;
}
}
}
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;
use App\Services\RedisClient;
use App\Services\TicketTelegramConfig;
use App\Services\TicketTelegramCredentialCipher;
use App\Services\TicketTelegramNotifier;
use App\Services\Ticket\TicketEvent;
use App\Services\Ticket\TicketNotificationDispatcher;
use App\Services\Ticket\TicketTelegramNotificationResult;
use App\Services\Ticket\TicketThreadService;
use App\Services\Ticket\TicketWriteResult;
use App\Controllers\Admin\TelegramController;
use App\Controllers\TelegramWebhookController;
use TelegramBot\Api\BotApi;
final class TelegramTestConnection
{
public function transaction($callback)
{
Configurations::$transactions++;
try { return $callback(); }
finally { Configurations::$transactions--; }
}
}
final class TelegramTestRedisBackend
{
public function get($key)
{
if (RedisClient::$fail) { throw new RuntimeException('Redis unavailable'); }
RedisClient::$gets++;
return RedisClient::$store[$key] ?? null;
}
public function setex($key, $ttl, $value)
{
if (RedisClient::$fail) { throw new RuntimeException('Redis unavailable'); }
RedisClient::$sets++;
RedisClient::$ttls[$key] = (int) $ttl;
RedisClient::$store[$key] = (string) $value;
return true;
}
public function del($key)
{
if (RedisClient::$fail) { throw new RuntimeException('Redis unavailable'); }
RedisClient::$deletes++;
unset(RedisClient::$store[$key], RedisClient::$ttls[$key]);
return 1;
}
}
final class TelegramTestQuery
{
public function __construct(private string $name) {}
public function lockForUpdate()
{
if (Configurations::$transactions === 0) {
throw new RuntimeException('Row lock requested outside a transaction.');
}
Configurations::$locks++;
return $this;
}
public function first()
{
$row = Configurations::$rows[$this->name] ?? null;
return $row === null ? null : clone $row;
}
public function firstOrFail() { return $this->first() ?? throw new RuntimeException('Missing fixture.'); }
public function delete() { unset(Configurations::$rows[$this->name]); }
}
final class TelegramTestWhereInQuery
{
public function __construct(private array $names) {}
public function get($columns = ['*'])
{
return array_values(array_filter(
Configurations::$rows,
fn ($row) => in_array($row->name, $this->names, true)
));
}
}
final class TelegramTestResponse
{
public int $status = 200;
public array $payload = [];
public function withJson($payload, $status = 200)
{
$result = clone $this;
$result->status = $status;
$result->payload = $payload;
return $result;
}
}
final class TelegramTestStream
{
public int $bytesRequested = 0;
public function __construct(private string $body, private bool $knownSize = true) {}
public function getSize() { return $this->knownSize ? strlen($this->body) : null; }
public function isSeekable() { return true; }
public function rewind() {}
public function read($bytes) { $this->bytesRequested = $bytes; return substr($this->body, 0, $bytes); }
}
final class TelegramTestRequest
{
public function __construct(private string $secret, public TelegramTestStream $stream, private array $payload = []) {}
public function getHeaderLine($name) { return $this->secret; }
public function getBody() { return $this->stream; }
public function getParsedBody() { return $this->payload; }
}
require dirname(__DIR__) . '/app/Services/Config.php';
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/Ticket/TicketWriteResult.php';
require dirname(__DIR__) . '/app/Services/Ticket/TicketEvent.php';
require dirname(__DIR__) . '/app/Services/Ticket/TicketTelegramNotificationResult.php';
require dirname(__DIR__) . '/app/Services/TicketTelegramNotifier.php';
require dirname(__DIR__) . '/app/Controllers/Admin/TelegramController.php';
require dirname(__DIR__) . '/app/Controllers/TelegramWebhookController.php';
$assert = function ($condition, $message) {
if (!$condition) { fwrite(STDERR, $message . PHP_EOL); exit(1); }
};
$expectRejected = function ($callback, $message) use ($assert) {
$rejected = false;
try { $callback(); } catch (Throwable $exception) { $rejected = true; }
$assert($rejected, $message);
};
$state = function () {
return json_decode(Configurations::$rows['ticket_telegram_binding']->value ?? '{}', true);
};
$setState = function ($value) {
Configurations::$rows['ticket_telegram_binding'] = new Configurations('ticket_telegram_binding', json_encode($value));
};
$configCacheKey = 'ticket_telegram_config_snapshot:v1';
$clearConfigCache = function () use ($configCacheKey) {
unset(RedisClient::$store[$configCacheKey], RedisClient::$ttls[$configCacheKey]);
};
$update = function ($code, $chatId = '123456') {
return ['message' => ['chat' => ['id' => $chatId, 'type' => 'private'],
'from' => ['id' => $chatId, 'is_bot' => false], 'text' => '/start ' . $code]];
};
$ticketEvent = function (string $kind = 'created', int $messageId = 42): TicketEvent {
$root = new Ticket();
$root->id = 42;
$root->userid = 7;
$root->title = '<b>Example</b>';
$root->content = 'Initial body';
$root->rootid = 0;
$root->datetime = 1793604000;
$root->status = 1;
$root->ticket_type = 'technical';
$root->priority = 'high';
$root->instance_id = 55;
$message = clone $root;
$message->id = $messageId;
$message->content = "<i>Body</i>\nSecond line";
$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'];
User::$users = [
1 => new User(1, 1),
2 => new User(2, 0),
3 => new User(3, 1),
7 => new User(7, 0, 1, 'customer', 'owner-secret@example.test', '+15550001111'),
];
CloudInstance::$instances = [55 => new CloudInstance(55, 7, 'vm-support')];
$expectRejected(fn () => TicketTelegramNotifier::createBinding(2), 'Ordinary whitelisted user can issue binding codes.');
$expectRejected(fn () => TicketTelegramNotifier::createBinding(3), 'Non-super administrator can issue binding codes.');
$binding = TicketTelegramNotifier::createBinding(1);
$assert((string) Configurations::$rows[TicketTelegramConfig::MIGRATION_MARKER]->value === '1'
&& !str_contains(Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value, $System_Config['telegram_token'])
&& !str_contains(Configurations::$rows[TicketTelegramConfig::WEBHOOK_SECRET]->value, $System_Config['telegram_request_token']),
'Legacy Telegram settings were not migrated once as encrypted database values.');
TicketTelegramConfig::publicValues();
$cachedSnapshot = json_decode(RedisClient::$store[$configCacheKey] ?? '', true);
$assert(is_array($cachedSnapshot) && (RedisClient::$ttls[$configCacheKey] ?? 0) === 60
&& str_starts_with($cachedSnapshot[TicketTelegramConfig::BOT_TOKEN] ?? '', 'sbox:telegram:v1:')
&& str_starts_with($cachedSnapshot[TicketTelegramConfig::WEBHOOK_SECRET] ?? '', 'sbox:telegram:v1:')
&& !str_contains(RedisClient::$store[$configCacheKey] ?? '', $System_Config['telegram_token'])
&& !str_contains(RedisClient::$store[$configCacheKey] ?? '', $System_Config['telegram_request_token']),
'Redis snapshot did not contain only encrypted raw Telegram configuration with a 60-second TTL.');
$queriesBeforeCacheHit = Configurations::$queries;
$redisGetsBeforeCacheHit = RedisClient::$gets;
TicketTelegramConfig::publicValues();
$assert(Configurations::$queries === $queriesBeforeCacheHit
&& RedisClient::$gets === $redisGetsBeforeCacheHit + 1,
'Warm Telegram configuration cache queried the database or loaded the snapshot more than once.');
$clearConfigCache();
RedisClient::$fail = true;
$queriesBeforeFallback = Configurations::$queries;
$assert(TicketTelegramConfig::publicValues()['configured']
&& Configurations::$queries > $queriesBeforeFallback,
'Redis failure did not fall back to the Telegram configuration database rows.');
RedisClient::$fail = false;
TicketTelegramConfig::publicValues();
$expectRejected(fn () => TicketTelegramCredentialCipher::decrypt(
Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value,
'webhook_secret'
), 'Purpose-separated Telegram ciphertext was accepted as another credential type.');
$assert(preg_match('/^[a-f0-9]{48}$/D', $binding['code']) === 1 && $binding['expires_in'] === 300,
'Binding code entropy/TTL changed.');
$assert($state()['pending_hash'] === hash('sha256', $binding['code'])
&& !str_contains(Configurations::$rows['ticket_telegram_binding']->value, $binding['code']),
'Plain binding code is persisted.');
$pendingState = $state();
Configurations::$failWrites = true;
$expectRejected(fn () => TicketTelegramNotifier::createBinding(1),
'A failed binding-code state write still returned an unusable code.');
Configurations::$failWrites = false;
$assert($state() === $pendingState,
'A failed binding-code state write changed the active pending code.');
foreach (['group', 'supergroup', 'channel'] as $type) {
$group = $update($binding['code']);
$group['message']['chat']['type'] = $type;
$assert(!TicketTelegramNotifier::handleUpdate($group), 'A non-private chat consumed the binding code.');
}
$forwarded = $update($binding['code']);
$forwarded['message']['forward_origin'] = ['type' => 'user'];
$assert(!TicketTelegramNotifier::handleUpdate($forwarded), 'Forwarded binding command was accepted.');
$bot = $update($binding['code']);
$bot['message']['from']['is_bot'] = true;
$assert(!TicketTelegramNotifier::handleUpdate($bot), 'A bot consumed the binding code.');
$mismatched = $update($binding['code']);
$mismatched['message']['from']['id'] = '654321';
$assert(!TicketTelegramNotifier::handleUpdate($mismatched), 'Mismatched sender/chat accepted.');
Configurations::$failWrites = true;
$expectRejected(fn () => TicketTelegramNotifier::handleUpdate($update($binding['code'])),
'A failed binding state write still reported success.');
Configurations::$failWrites = false;
$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.');
$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'
&& str_contains(BotApi::$calls[0][1]['text'], '绑定成功'),
'Successful administrator binding did not receive a private confirmation.');
$assert(!TicketTelegramNotifier::handleUpdate($update($binding['code'], '654321'))
&& $state()['chat_id'] === '123456'
&& count(BotApi::$calls) === 1, 'Replayed binding token changed the recipient or sent another confirmation.');
$assert(Configurations::$locks >= 3 && Configurations::$transactions === 0,
'Binding issuance/consumption did not use transaction row locks.');
$binding = TicketTelegramNotifier::createBinding(1);
$expired = $state();
$expired['pending_expires_at'] = time() - 1;
$setState($expired);
$assert(!TicketTelegramNotifier::handleUpdate($update($binding['code'])), 'Expired binding token was accepted.');
$binding = TicketTelegramNotifier::createBinding(1);
User::$users[1]->is_admin = 0;
$assert(!TicketTelegramNotifier::handleUpdate($update($binding['code'])), 'Downgraded issuer completed a binding.');
User::$users[1]->is_admin = 1;
$binding = TicketTelegramNotifier::createBinding(1);
BotApi::$fail = true;
$assert(TicketTelegramNotifier::handleUpdate($update($binding['code'])),
'A failed Telegram confirmation changed a committed binding into a webhook failure.');
BotApi::$fail = false;
$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())
=== TicketTelegramNotificationResult::Sent,
'Eligible administrator was not notified.');
$alertText = BotApi::$calls[0][1]['text'];
$assert(BotApi::$calls[0][1]['chat_id'] === '123456'
&& str_starts_with($alertText, '🆕 新工单 #42')
&& str_contains($alertText, '用户:customer(UID 7)')
&& str_contains($alertText, '分类:技术支持')
&& str_contains($alertText, '优先级:高')
&& str_contains($alertText, '关联实例:vm-support')
&& str_contains($alertText, '附件:2 个')
&& str_contains($alertText, '/admin/ticket/42/view')
&& str_contains($alertText, '直接回复本消息即可回复用户')
&& !str_contains($alertText, '<b>')
&& !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())
=== TicketTelegramNotificationResult::Sent
&& 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))
=== TicketTelegramNotificationResult::Failed,
'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))
=== TicketTelegramNotificationResult::Failed
&& 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.' . $delivery->binding_generation
. '.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.');
$originalBindingState = $state();
$newGeneration = bin2hex(random_bytes(16));
$setState([
'bound_admin_id' => 1,
'chat_id' => '123456',
'binding_generation' => $newGeneration,
]);
$newBindingDelivery = new TicketTelegramDelivery();
$newBindingDelivery->binding_generation = $newGeneration;
$newBindingDelivery->bound_admin_id = 1;
$newBindingDelivery->chat_id = '123456';
$newBindingDelivery->ticket_id = 42;
$newBindingDelivery->ticket_message_id = 99;
$newBindingDelivery->event_kind = 'user_reply';
$newBindingDelivery->telegram_message_id = 1100;
$newBindingDelivery->state = 'sent';
$newBindingDelivery->content_hash = str_repeat('a', 64);
$newBindingDelivery->created_at = time();
$newBindingDelivery->sent_at = time();
$newBindingDelivery->updated_at = time();
$newBindingDelivery->save();
$commandsBeforeRebind = count(TicketThreadService::$commands);
$assert(TicketTelegramNotifier::handleUpdate($ticketReply(508, 'old binding', '123456', 1000))
&& count(TicketThreadService::$commands) === $commandsBeforeRebind,
'An old binding generation still authorized its Telegram notification.');
$assert(TicketTelegramNotifier::handleUpdate($ticketReply(501, 'new binding', '123456', 1100)),
'A new binding could not reuse a Telegram update identifier.');
$newBindingCommand = TicketThreadService::$commands[count(TicketThreadService::$commands) - 1] ?? null;
$assert($newBindingCommand !== null
&& $newBindingCommand->requestKey === 'telegram.' . $newGeneration . '.update.501',
'Telegram idempotency did not include the active binding generation.');
$setState($originalBindingState);
$commandsBeforeUnsafeReplies = count(TicketThreadService::$commands);
$unknownReply = $ticketReply(509, 'unknown notification', '123456', 999999);
$viaBotReply = $ticketReply(510);
$viaBotReply['message']['via_bot'] = ['id' => 99];
$mediaReply = $ticketReply(511);
$mediaReply['message']['photo'] = [['file_id' => 'not-accepted']];
$overflowReply = $ticketReply(512);
$overflowReply['update_id'] = (string) PHP_INT_MAX . '0';
$assert(TicketTelegramNotifier::handleUpdate($unknownReply)
&& !TicketTelegramNotifier::handleUpdate($viaBotReply)
&& !TicketTelegramNotifier::handleUpdate($mediaReply)
&& !TicketTelegramNotifier::handleUpdate($overflowReply)
&& count(TicketThreadService::$commands) === $commandsBeforeUnsafeReplies,
'Unknown, via-bot, media or overflowing Telegram updates reached the ticket workflow.');
User::$users[1]->is_admin = 0;
$assert(!TicketTelegramNotifier::handleUpdate($ticketReply(513)),
'A downgraded administrator replied through Telegram.');
User::$users[1]->is_admin = 1;
$fallbackEvent = $ticketEvent('user_reply', 44);
$fallbackEvent->result->root->userid = 999;
$fallbackEvent->result->root->instance_id = 999;
$fallbackEvent->result->message->content = str_repeat('测', 5000);
$assert(TicketTelegramNotifier::notify($fallbackEvent)
=== TicketTelegramNotificationResult::Sent,
'A missing user/instance projection suppressed the Telegram notification.');
$fallbackText = BotApi::$calls[count(BotApi::$calls) - 1][1]['text'] ?? '';
$assert(str_contains($fallbackText, '用户:UID 999')
&& !str_contains($fallbackText, '关联实例:')
&& mb_strlen($fallbackText, 'UTF-8') <= 4096,
'Telegram notification fallback or length limit is invalid.');
$closedEvent = $ticketEvent('user_reply', 45);
$closedEvent->result->root->status = 0;
$assert(TicketTelegramNotifier::notify($closedEvent)
=== TicketTelegramNotificationResult::Sent,
'Closed ticket update notification was not sent.');
$closedNotification = BotApi::$calls[count(BotApi::$calls) - 1][1]['text'] ?? '';
$assert(str_contains($closedNotification, '工单已关闭,请在管理后台查看')
&& !str_contains($closedNotification, '直接回复本消息'),
'Closed ticket notification still advertises direct Telegram replies.');
$stale = new TicketTelegramDelivery();
$stale->binding_generation = $originalBindingState['binding_generation'];
$stale->bound_admin_id = 1;
$stale->chat_id = '123456';
$stale->ticket_id = 42;
$stale->ticket_message_id = 46;
$stale->event_kind = 'user_reply';
$stale->telegram_message_id = null;
$stale->state = 'dispatching';
$stale->content_hash = str_repeat('b', 64);
$stale->created_at = time() - 60;
$stale->sent_at = null;
$stale->updated_at = time() - 60;
$stale->save();
$callsBeforeStale = count(BotApi::$calls);
$assert(TicketTelegramNotifier::notify($ticketEvent('user_reply', 46))
=== TicketTelegramNotificationResult::Failed
&& $stale->state === 'unknown'
&& count(BotApi::$calls) === $callsBeforeStale,
'A stale dispatching delivery was replayed or left permanently unresolved.');
$calls = count(BotApi::$calls);
foreach ([['bound_admin_id' => 1, 'chat_id' => '-100123456'],
['bound_admin_id' => 2, 'chat_id' => '123456'],
['bound_admin_id' => 1, 'chat_id' => ['unexpected']]] as $unsafe) {
$setState($unsafe);
$assert(TicketTelegramNotifier::notify($ticketEvent('user_reply'))
=== TicketTelegramNotificationResult::Skipped,
'Group/ordinary user/malformed recipient was notified.');
}
$setState(['bound_admin_id' => 1, 'chat_id' => '123456']);
User::$users[1]->is_admin = 0;
$assert(TicketTelegramNotifier::notify($ticketEvent('user_reply'))
=== TicketTelegramNotificationResult::Skipped,
'Downgraded administrator received alerts.');
User::$users[1]->is_admin = 1;
User::$users[1]->enable = 0;
$assert(TicketTelegramNotifier::notify($ticketEvent('user_reply'))
=== TicketTelegramNotificationResult::Skipped,
'Disabled administrator received alerts.');
User::$users[1]->enable = 1;
$System_Config['super_admin'] = '2';
$assert(TicketTelegramNotifier::notify($ticketEvent('user_reply'))
=== TicketTelegramNotificationResult::Skipped,
'Removed super-admin received alerts.');
$System_Config['super_admin'] = '1,2';
$assert(count(BotApi::$calls) === $calls, 'Rejected notification still invoked Telegram.');
$controller = new TelegramController();
Auth::$user = User::$users[1];
$secretBeforeAtomicSave = TicketTelegramConfig::runtime(true)['webhook_secret'];
$saveRequest = new TelegramTestRequest('', new TelegramTestStream(''), [
'telegram_enabled' => 'true',
'telegram_webhook_base_url' => 'https://tg.example.invalid/',
'telegram_bot_token' => '',
'telegram_rotate_webhook_secret' => 'true',
]);
$deletesBeforeSave = RedisClient::$deletes;
$saved = $controller->save($saveRequest, new TelegramTestResponse(), []);
$assert($saved->status === 200 && ($saved->payload['ret'] ?? 0) === 1
&& ($saved->payload['config']['webhook_url'] ?? '') === 'https://tg.example.invalid/telegram_callback'
&& !str_contains(json_encode($saved->payload), $System_Config['telegram_token'])
&& !str_contains(json_encode($saved->payload), $System_Config['telegram_request_token'])
&& RedisClient::$deletes > $deletesBeforeSave
&& TicketTelegramConfig::runtime(true)['webhook_secret'] !== $secretBeforeAtomicSave,
'Administrator config save failed or returned Telegram secrets.');
$validTokenCipher = Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value;
Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value = 'corrupt-ciphertext';
$invalidSavedToken = $controller->save(new TelegramTestRequest('', new TelegramTestStream(''), [
'telegram_enabled' => 'true',
'telegram_webhook_base_url' => 'https://tg.example.invalid',
'telegram_bot_token' => '',
]), new TelegramTestResponse(), []);
$assert($invalidSavedToken->status === 422 && ($invalidSavedToken->payload['ret'] ?? 1) === 0,
'Enabled configuration accepted an unreadable stored bot token.');
Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value = $validTokenCipher;
$setState(['bound_admin_id' => 1, 'chat_id' => '123456']);
$replacementToken = '987654321:' . str_repeat('B', 35);
$replaced = $controller->save(new TelegramTestRequest('', new TelegramTestStream(''), [
'telegram_enabled' => 'true',
'telegram_webhook_base_url' => 'https://tg.example.invalid',
'telegram_bot_token' => $replacementToken,
]), new TelegramTestResponse(), []);
$assert($replaced->status === 200 && !isset(Configurations::$rows[TicketTelegramConfig::BINDING])
&& !str_contains(json_encode($replaced->payload), $replacementToken)
&& !str_contains(RedisClient::$store[$configCacheKey] ?? '', $replacementToken),
'Replacing the bot token retained the old binding or exposed the new token.');
foreach ([User::$users[2], new User(1, 0), new User(1, 1, 0)] as $account) {
Auth::$user = $account;
foreach (['save', 'rotateSecret', 'bind', 'unbind', 'webhook'] as $action) {
$result = $controller->$action(null, new TelegramTestResponse(), []);
$assert($result->status === 403, 'Direct action bypass allows an ordinary/downgraded/disabled account: ' . $action);
}
}
Auth::$user = User::$users[1];
$webhook = new TelegramWebhookController();
$webhookSecret = TicketTelegramConfig::runtime(true)['webhook_secret'];
$unauthorized = new TelegramTestRequest('incorrect-secret', new TelegramTestStream('{}'));
$assert($webhook->handle($unauthorized, new TelegramTestResponse(), [])->status === 403
&& $unauthorized->stream->bytesRequested === 0, 'Webhook secret rejection occurs after processing the body.');
foreach ([true, false] as $knownSize) {
$oversized = new TelegramTestRequest($webhookSecret, new TelegramTestStream(str_repeat('x', 65537), $knownSize));
$assert($webhook->handle($oversized, new TelegramTestResponse(), [])->status === 413,
'Oversized webhook body was accepted.');
$assert($oversized->stream->bytesRequested <= 65537, 'Unknown-length webhook body was read without a limit.');
}
$badJson = new TelegramTestRequest($webhookSecret, new TelegramTestStream('{broken'));
$assert($webhook->handle($badJson, new TelegramTestResponse(), [])->status === 400, 'Malformed webhook JSON accepted.');
Configurations::$rows[TicketTelegramConfig::ENABLED]->value = 'false';
$clearConfigCache();
$disabled = new TelegramTestRequest($webhookSecret, new TelegramTestStream('{}'));
$assert($webhook->handle($disabled, new TelegramTestResponse(), [])->status === 403,
'Disabled bot still accepts webhooks.');
Configurations::$rows[TicketTelegramConfig::ENABLED]->value = 'true';
$clearConfigCache();
$assert(TicketTelegramNotifier::registerWebhook(), 'Configured HTTPS webhook registration failed.');
$registration = BotApi::$calls[count(BotApi::$calls) - 1];
$assert($registration[0] === 'setWebhook' && $registration[2] === 10
&& $registration[1]['url'] === 'https://tg.example.invalid/telegram_callback'
&& $registration[1]['secret_token'] === $webhookSecret
&& $registration[1]['allowed_updates'] === '["message"]',
'Webhook registration lost its secret, timeout or message-only update boundary.');
$expectRejected(fn () => TicketTelegramConfig::save([
'enabled' => true,
'webhook_base_url' => 'http://example.invalid',
]), 'Non-HTTPS webhook URL accepted.');
TicketTelegramConfig::publicValues();
$preRotationSnapshot = RedisClient::$store[$configCacheKey] ?? '';
$oldSecret = $webhookSecret;
$deletesBeforeRotate = RedisClient::$deletes;
$rotated = $controller->rotateSecret(null, new TelegramTestResponse(), []);
$webhookSecret = TicketTelegramConfig::runtime(true)['webhook_secret'];
// Simulate a cache-aside race repopulating the pre-rotation encrypted snapshot.
RedisClient::$store[$configCacheKey] = $preRotationSnapshot;
RedisClient::$ttls[$configCacheKey] = 60;
$queriesBeforeAuthoritativeChecks = Configurations::$queries;
$assert($rotated->status === 200 && $oldSecret !== $webhookSecret
&& RedisClient::$deletes > $deletesBeforeRotate
&& !TicketTelegramNotifier::authorizeWebhook($oldSecret)
&& TicketTelegramNotifier::authorizeWebhook($webhookSecret)
&& Configurations::$queries >= $queriesBeforeAuthoritativeChecks + 2,
'Webhook secret rotation or authoritative runtime reads accepted a stale cached secret.');
BotApi::$fail = true;
$failure = '';
try { TicketTelegramNotifier::registerWebhook(); }
catch (RuntimeException $exception) { $failure = $exception->getMessage(); }
$assert($failure !== '' && !str_contains($failure, TicketTelegramConfig::runtime(true)['bot_token']),
'SDK failure leaked the Telegram bot token.');
BotApi::$fail = false;
$clearConfigCache();
Configurations::$failQueries = true;
$failure = '';
try { TicketTelegramNotifier::registerWebhook(); }
catch (RuntimeException $exception) { $failure = $exception->getMessage(); }
Configurations::$failQueries = false;
$assert($failure === 'Telegram 配置读取失败,请检查数据库与服务器日志'
&& !str_contains($failure, 'SQLSTATE'), 'Database error details leaked through webhook registration.');
// Bad legacy values must be consumed once without trapping the administrator in a migration loop.
Configurations::$rows = [];
$clearConfigCache();
$System_Config['enable_telegram'] = 'true';
$System_Config['telegram_token'] = 'invalid legacy token';
$System_Config['telegram_request_token'] = 'short';
$System_Config['tgUrl'] = 'http://insecure.example.invalid/path';
$legacy = TicketTelegramConfig::publicValues();
$assert((string) Configurations::$rows[TicketTelegramConfig::MIGRATION_MARKER]->value === '1'
&& !$legacy['bot_token_configured'] && $legacy['webhook_base_url'] === '' && !$legacy['configured'],
'Invalid legacy Telegram values blocked or polluted the one-time migration.');
// A clean installation must not need the payload key until an administrator saves credentials.
Configurations::$rows = [];
$clearConfigCache();
CloudSecrets::$calls = 0;
unset($System_Config['enable_telegram'], $System_Config['telegram_token'],
$System_Config['telegram_request_token'], $System_Config['tgUrl']);
$fresh = TicketTelegramConfig::publicValues();
$assert(!$fresh['enabled'] && !$fresh['bot_token_configured'] && !$fresh['webhook_secret_configured']
&& CloudSecrets::$calls === 0, 'Fresh Telegram configuration unexpectedly required credential decryption.');
$routes = file_get_contents(dirname(__DIR__) . '/config/routes.php');
foreach (['config', 'secret/rotate', 'bind', 'unbind', 'webhook'] as $action) {
$matches = array_filter(explode("\n", $routes), fn ($line) => str_contains($line, "'/telegram/" . $action . "'"));
$assert(count($matches) === 1 && str_contains(reset($matches), 'new SuperAdmin()'),
'Administrator mutation route lost SuperAdmin/CSRF middleware: ' . $action);
}
$assert(str_contains($routes, '})->add(new Admin());'), 'Admin group middleware was removed.');
echo "Administrator Telegram private one-time binding, replay/expiry/downgrade and webhook boundaries passed.\n";
}