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...

468 lines
24 KiB
PHP

<?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 static function find($id) { return self::$users[(int) $id] ?? null; }
}
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 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()
{
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\Controllers {
class BaseController {}
class AdminController extends BaseController {}
}
namespace TelegramBot\Api {
final class BotApi
{
public static array $calls = [];
public static bool $fail = false;
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 true;
}
}
}
namespace {
use App\Models\Configurations;
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\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() { return Configurations::$rows[$this->name] ?? null; }
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/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]];
};
$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)];
$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.');
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.');
$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.');
$assert(!TicketTelegramNotifier::handleUpdate($update($binding['code'], '654321'))
&& $state()['chat_id'] === '123456', 'Replayed binding token changed the recipient.');
$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;
$setState(['bound_admin_id' => 1, 'chat_id' => '123456']);
$assert(TicketTelegramNotifier::notify('新工单', 42, '<b>Example</b>', 'Body'), 'Eligible administrator was not notified.');
$assert(BotApi::$calls[0][1]['chat_id'] === '123456'
&& str_starts_with(BotApi::$calls[0][1]['text'], '新工单 #42')
&& !isset(BotApi::$calls[0][1]['parse_mode']), 'Alert recipient/Chinese event label/plain-text mode is wrong.');
$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('updated', 42, 'Title', 'Body'), 'Group/ordinary user/malformed recipient was notified.');
}
$setState(['bound_admin_id' => 1, 'chat_id' => '123456']);
User::$users[1]->is_admin = 0;
$assert(!TicketTelegramNotifier::notify('updated', 42, 'Title', 'Body'), 'Downgraded administrator received alerts.');
User::$users[1]->is_admin = 1;
User::$users[1]->enable = 0;
$assert(!TicketTelegramNotifier::notify('updated', 42, 'Title', 'Body'), 'Disabled administrator received alerts.');
User::$users[1]->enable = 1;
$System_Config['super_admin'] = '2';
$assert(!TicketTelegramNotifier::notify('updated', 42, 'Title', 'Body'), '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";
}