From 835730d8d8439232150612ff653b8dceb546031b Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Fri, 13 Nov 2026 10:01:28 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D1=8B=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D0=BE=D0=B2,=20?= =?UTF-8?q?=D0=B7=D0=B0=D1=89=D0=B8=D1=82=D0=B0=20SSRF=20=D0=B8=20shell,?= =?UTF-8?q?=20=D1=83=D0=BF=D1=80=D0=BE=D1=89=D0=B5=D0=BD=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Безопасность: - ShellTool: при allowlist запрещены метасимволы (; & | ` $ < > ( ) и перевод строки) — склейкой команд allowlist больше не обходится - UrlGuard: проверка AAAA и IPv6 (loopback, ULA, link-local, mapped, NAT64, 6to4, 2001:db8), закрепление адресов через CURLOPT_RESOLVE против DNS rebinding; ограничение с HTTP-прокси описано в документации Надёжность: - Retry: повтор при 408/425/429/5xx и обрыве связи, Retry-After, экспоненциальная пауза; таймаут не повторяется. AI_MAX_RETRIES=2 - калькулятор и convert_units больше не выдают мусор на больших числах Упрощение: - Timeout — одна функция вместо объекта с неиспользуемым состоянием - JsonQueryTool: разбор пути через preg_split вместо ручного цикла - CsvQueryTool: ошибки через исключения вместо array|string - ReplaceInFileTool: убран лишний replaceOnce() - Agent: общий record() для трассировки и хука - HttpRequest перенесён из ядра в tools/Support - удалены осиротевшие докблоки и неиспользуемые импорты Тесты: 116 -> 149, включая AiClient по настоящему HTTP против поддельного сервера (tests/stub/llm-server.php). --- .env.example | 4 + README.md | 18 ++- docs/providers.md | 2 + docs/reference.md | 5 +- docs/tools.md | 18 ++- examples/10-http.php | 2 +- src/Agent.php | 46 +++--- src/AiClient.php | 19 ++- src/HttpTransport.php | 18 ++- src/Retry.php | 139 +++++++++++++++++ tests/cases/client.php | 207 +++++++++++++++++++++++++ tests/cases/files.php | 37 +++++ tests/cases/http.php | 105 ++++++++++++- tests/cases/retry.php | 174 +++++++++++++++++++++ tests/cases/shell.php | 31 ++++ tests/cases/support.php | 27 ++-- tests/cases/tools.php | 9 ++ tests/stub/llm-server.php | 93 +++++++++++ tests/support.php | 27 ---- tools/CalculatorTool.php | 12 +- tools/ConvertUnitsTool.php | 12 +- tools/CsvQueryTool.php | 198 ++++++++++------------- tools/FileSandbox.php | 5 - tools/FindFilesTool.php | 6 - tools/HttpRequestTool.php | 18 +-- tools/JsonQueryTool.php | 46 +----- tools/ListDirTool.php | 2 - tools/ReadFileTool.php | 2 - tools/ReplaceInFileTool.php | 21 +-- tools/SearchFilesTool.php | 4 - tools/ShellTool.php | 55 ++++++- {src => tools/Support}/HttpRequest.php | 2 +- tools/Support/Number.php | 28 ++++ tools/Support/Timeout.php | 39 ++--- tools/Support/UrlGuard.php | 156 ++++++++++++++++--- 35 files changed, 1216 insertions(+), 371 deletions(-) create mode 100644 src/Retry.php create mode 100644 tests/cases/client.php create mode 100644 tests/cases/retry.php create mode 100644 tests/stub/llm-server.php rename {src => tools/Support}/HttpRequest.php (99%) create mode 100644 tools/Support/Number.php diff --git a/.env.example b/.env.example index 8972e32..dfa794b 100644 --- a/.env.example +++ b/.env.example @@ -15,6 +15,10 @@ AI_API_KEY= # Таймаут одного запроса к модели, секунды. AI_TIMEOUT=30 +# Повторы при 429/5xx и обрыве связи (не при таймауте). 0 — без повторов. +# Пауза растёт: ~1 с, ~2 с, ...; Retry-After от сервера учитывается. +AI_MAX_RETRIES=2 + AI_TEMPERATURE=0.7 AI_MAX_TOKENS=1000 diff --git a/README.md b/README.md index 0f2c6e4..66a6917 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ - **`LoggingClient`** — декоратор: пишет каждый запрос, ответ, токены и время. - **`AgentHooks`** — колбэки хода: шаг, начало и конец инструмента, остановка. - **`Cost`** — оценка стоимости по токенам и тарифу провайдера. +- **`Retry`** — повтор запроса к модели при 429/5xx и обрыве связи, + с учётом `Retry-After`. - **18 готовых инструментов**: время, калькулятор, погода, файлы (чтение, запись, поиск), CSV, HTTP, единицы, даты, UUID, хеши, JSON, явное завершение и команды оболочки — см. [таблицу](docs/tools.md). @@ -48,10 +50,10 @@ src/ AgentHooks.php колбэки хода: шаг, инструмент, остановка LoggingClient.php декоратор: логи запросов и ответов Cost.php оценка стоимости по токенам и тарифу + Retry.php повторы при 429/5xx и обрыве связи Tool.php интерфейс инструмента ToolRegistry.php набор инструментов HttpTransport.php низкоуровневый HTTP: методы, тело, лимит размера - HttpRequest.php сборка запроса: query, body, заголовки, Basic/Bearer Env.php .env без зависимостей AiException.php ошибки tools/ @@ -74,7 +76,8 @@ tools/ DateCalcTool.php разница дат и прибавление интервала UuidTool.php UUID v4 HashTool.php sha256/sha1/md5 - Support/ помощники: Bytes, FileWalker, UrlGuard, AtomicWriter, Timeout + Support/ помощники: HttpRequest, UrlGuard, FileWalker, AtomicWriter, + Timeout, Bytes, Number examples/ 01-chat.php простой вопрос 02-tools.php агент с тремя инструментами @@ -92,6 +95,7 @@ examples/ 14-hooks.php прогресс в консоли и остановка через хуки tests/run.php раннер тестов tests/support.php помощники, заглушки, FakeClient +tests/stub/ поддельный сервер модели для тестов AiClient tests/cases/ тесты по темам (agent, files, http, shell, ...) docs/ инструменты, примеры, провайдеры, справочник ``` @@ -275,12 +279,14 @@ echo $agent->ask('«Не приходит SMS с кодом, второй ден php tests/run.php ``` -116 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента +149 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента (включая ошибку инструмента и лимит раундов), настройки, хуки, finish, файлы и песочница (включая свободный режим), CSV, единицы, даты, uuid/хеши, -сборка HTTP-запроса, защита от SSRF, оболочка (таймаут от модели, allowlist), -стоимость и накопление usage. Сеть не нужна — модель подменяется -`FakeClient` из `tests/support.php`. +сборка HTTP-запроса, защита от SSRF (IPv6, закрепление адресов против DNS +rebinding), оболочка (таймаут от модели, allowlist и попытки его обойти), +повторы при 429/5xx, стоимость и накопление usage. Внешняя сеть не нужна — модель +подменяется `FakeClient` из `tests/support.php`, а `AiClient` проверяется по +настоящему HTTP против поддельного сервера `tests/stub/llm-server.php`. ## Проверка без модели diff --git a/docs/providers.md b/docs/providers.md index e745ad6..f6f30e3 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -27,6 +27,8 @@ mistral-nemo и т.п.). | `HTTP 404` / `model not found` | модель не загружена | `AI_MODEL` = имя из `/v1/models` | | `HTTP 400 unknown field 'thinking'` | провайдер не DeepSeek | `AI_DISABLE_THINKING=false` | | Инструменты не вызываются | модель или сборка не умеют tools | qwen3 / llama 3.1+; llama.cpp должен быть с `--jinja` | +| `HTTP 429` / `503` после паузы | лимит или перегрузка не прошли за все повторы | `AI_MAX_RETRIES` больше; если сервер просит ждать дольше 30 с (`Retry-After`), повтора нет | +| Ответ ждали в 3 раза дольше `AI_TIMEOUT` | не ошибка: таймаут не повторяется, но 5xx и обрыв связи — да | `AI_MAX_RETRIES=0`, если важна предсказуемая задержка | Проверить сервер до всякого кода: diff --git a/docs/reference.md b/docs/reference.md index 9cfa1af..e141787 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -6,7 +6,6 @@ | Нужно | Куда добавить | |---|---| -| Повторы при 429/5xx | цикл в `AiClient::chat()` вокруг `post()` | | Стриминг ответа | `stream: true` + чтение чанков (сложнее, отдельный метод) | | Логирование запросов в БД | обёртка над `ChatClient` (декоратор), 20 строк | | Память между запусками | сохранить `$agent->messages()` в JSON/БД | @@ -56,6 +55,10 @@ $result = $client->chat($messages, $tools = [], $options = []); // options: tool_choice, parallel_tool_calls, temperature, max_tokens $result->text; $result->toolCalls; $result->usage; +// Повторы при 429/5xx и обрыве связи (по умолчанию 2, AI_MAX_RETRIES) +$client = new AiClient($key, retry: new Retry(maxRetries: 3, baseDelay: 0.5, maxDelay: 30.0)); +$client = new AiClient($key, retry: Retry::none()); + // Расход и стоимость $agent->usage(); // [prompt_tokens, completion_tokens] за диалог $cost = (new Cost())->withRate('model', input: 0.07, output: 0.28); diff --git a/docs/tools.md b/docs/tools.md index 4e846eb..79de9e8 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -109,7 +109,15 @@ $tools->add(new HttpRequestTool( Защита: - только `http`/`https`, только публичные адреса: `localhost`, `10.x`, - `172.16–31.x`, `192.168.x`, `169.254.x`, CGNAT запрещены; + `172.16–31.x`, `192.168.x`, `169.254.x`, CGNAT запрещены; то же для IPv6 + (`::1`, `fc00::/7`, `fe80::/10`, IPv4-mapped, NAT64 и 6to4 с приватным + адресом внутри); +- проверяются все адреса хоста (A и AAAA), и cURL подключается ровно к ним + (`CURLOPT_RESOLVE`), не резолвя имя второй раз — так DNS rebinding не + подменит адрес между проверкой и запросом; +- **исключение — HTTP-прокси** (`HTTP_PROXY`/`HTTPS_PROXY`): имя резолвит + прокси, и «внутренняя сеть» — это сеть прокси. Если агент ходит через + прокси, ограничивайте доступ на самом прокси; - редиректы проверяются заново на каждом шаге; для `POST`/`PUT`/`DELETE` редирект не преследуется — возвращается `Location` и предложение повторить; - размер ответа ограничен, запрос обрывается при превышении. @@ -168,8 +176,12 @@ $tools->add(new ShellTool( Чего не делает: - **не изолирует**: команда имеет права процесса PHP; -- `allow` — грубый фильтр по первому слову, а не песочница: - `php -r '...'` через него пройдёт; +- `allow` — фильтр по первому слову, а не песочница. При заданном `allow` + запрещены метасимволы `;` `&` `|` `$` `<` `>` `(` `)`, обратная кавычка и + перевод строки, поэтому + `git status; rm -rf ~` не пройдёт. Но разрешённая программа сама умеет + исполнять код: `php -r '...'`, `git -c core.pager=...`, `find -exec`, + `npm run` — такие в `allow` не кладите; - у `cmd` ограничение длины команды ~8 КБ. Нужна настоящая изоляция — запускайте агента в контейнере, а не надейтесь diff --git a/examples/10-http.php b/examples/10-http.php index 902a59f..324f910 100644 --- a/examples/10-http.php +++ b/examples/10-http.php @@ -17,7 +17,7 @@ declare(strict_types=1); require dirname(__DIR__) . '/bootstrap.php'; -use AiSdk\HttpRequest; +use AiSdk\Tools\Support\HttpRequest; use AiSdk\Tools\HttpRequestTool; // 1. Сборка запроса — то же, что делает инструмент внутри. diff --git a/src/Agent.php b/src/Agent.php index deb2bb6..23f897b 100644 --- a/src/Agent.php +++ b/src/Agent.php @@ -230,22 +230,14 @@ final class Agent $this->hooks?->toolStart($call['name'], $call['arguments']); - if ($this->toolApproval !== null && !$this->approve($call['name'], $call['arguments'])) { + if (!$this->approve($call['name'], $call['arguments'])) { $blocked = true; $output = 'Вызов инструмента "' . $call['name'] . '" отклонён оператором.'; } else { $output = $this->tools->execute($call['name'], $call['arguments']); } - $this->trace[] = [ - 'name' => $call['name'], - 'arguments' => $call['arguments'], - 'output' => $output, - 'ms' => (int) round((microtime(true) - $started) * 1000), - 'blocked' => $blocked, - ]; - - $this->hooks?->toolEnd($this->trace[count($this->trace) - 1]); + $this->record($call, $output, (int) round((microtime(true) - $started) * 1000), $blocked); return [ 'role' => 'tool', @@ -254,6 +246,25 @@ final class Agent ]; } + /** + * Записать вызов в трассировку и сообщить хуку. + * + * @param array{id: string, name: string, arguments: array} $call + */ + private function record(array $call, string $output, int $ms, bool $blocked): void + { + $step = [ + 'name' => $call['name'], + 'arguments' => $call['arguments'], + 'output' => $output, + 'ms' => $ms, + 'blocked' => $blocked, + ]; + + $this->trace[] = $step; + $this->hooks?->toolEnd($step); + } + /** * Выполнить пачку вызовов. Если среди них был finish — вернуть его * результат: ход на этом заканчивается. @@ -280,16 +291,7 @@ final class Agent if ($this->isFinishCall($call)) { $this->hooks?->toolStart($call['name'], $call['arguments']); $finished = $this->finishResult($call); - - $this->trace[] = [ - 'name' => $call['name'], - 'arguments' => $call['arguments'], - 'output' => $finished, - 'ms' => 0, - 'blocked' => false, - ]; - - $this->hooks?->toolEnd($this->trace[count($this->trace) - 1]); + $this->record($call, $finished, 0, false); $this->messages[] = [ 'role' => 'tool', @@ -459,10 +461,6 @@ final class Agent return $result; } - - /** - * Быстрый старт: агент с инструментами по умолчанию. - */ } diff --git a/src/AiClient.php b/src/AiClient.php index b59db31..c2c29fc 100644 --- a/src/AiClient.php +++ b/src/AiClient.php @@ -19,6 +19,8 @@ final class AiClient implements ChatClient * false — только для локальной отладки. * @param string $caInfo путь к своему CA-бандлу (cacert.pem). Пусто — * системные сертификаты PHP/OpenSSL. + * @param Retry $retry повторы при 429/5xx и обрыве связи; + * Retry::none() — отключить */ public function __construct( private readonly string $apiKey, @@ -30,6 +32,7 @@ final class AiClient implements ChatClient private readonly array $extraBody = [], private readonly bool $verifySsl = true, private readonly string $caInfo = '', + private readonly Retry $retry = new Retry(), ) { } @@ -59,6 +62,7 @@ final class AiClient implements ChatClient extraBody: $extraBody, verifySsl: Env::bool('AI_VERIFY_SSL', true), caInfo: Env::get('AI_CAINFO', '') ?? '', + retry: new Retry(maxRetries: max(0, Env::int('AI_MAX_RETRIES', 2))), ); } @@ -83,19 +87,22 @@ final class AiClient implements ChatClient $body = array_merge($body, $this->extraBody); + $payload = (string) json_encode( + $body, + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE + ); + // Транспорт живёт в Http: TLS, CAINFO, таймауты и ошибки — в одном месте. - $response = HttpTransport::request( + // Retry повторяет запрос при 429/5xx и обрыве связи. + $response = $this->retry->run(fn (): array => HttpTransport::request( url: rtrim($this->baseUrl, '/') . '/chat/completions', timeout: $this->timeout, follow: false, maxBytes: 1048576, method: 'POST', headers: $this->requestHeaders(), - body: (string) json_encode( - $body, - JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE - ), - ); + body: $payload, + )); $status = $response['status']; $raw = $response['body']; diff --git a/src/HttpTransport.php b/src/HttpTransport.php index 18b5faa..3f0dce7 100644 --- a/src/HttpTransport.php +++ b/src/HttpTransport.php @@ -68,7 +68,9 @@ final class HttpTransport * @param bool $follow следовать редиректам автоматически * @param int $maxBytes предел тела ответа; больше — обрезаем и обрываем загрузку * @param array $headers - * @return array{status: int, body: string, location: string|null, content_type: string|null, truncated: bool} + * @param list $resolve строки CURLOPT_RESOLVE ("host:port:ip"): подключаться + * к заранее проверенным адресам без повторного DNS (см. UrlGuard::pin) + * @return array{status: int, body: string, location: string|null, content_type: string|null, retry_after: string|null, truncated: bool} */ public static function request( string $url, @@ -78,6 +80,7 @@ final class HttpTransport string $method = 'GET', array $headers = [], ?string $body = null, + array $resolve = [], ): array { $ch = curl_init($url); @@ -90,6 +93,7 @@ final class HttpTransport $truncated = false; $location = null; $contentType = null; + $retryAfter = null; $limit = max(1024, $maxBytes); $verify = Env::bool('AI_VERIFY_SSL', true); @@ -119,13 +123,15 @@ final class HttpTransport return strlen($chunk); }, - CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$location, &$contentType): int { + CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$location, &$contentType, &$retryAfter): int { $lower = strtolower($line); if (str_starts_with($lower, 'location:')) { $location = trim(substr($line, 9)); } elseif (str_starts_with($lower, 'content-type:')) { $contentType = trim(substr($line, 13)); + } elseif (str_starts_with($lower, 'retry-after:')) { + $retryAfter = trim(substr($line, 12)); } return strlen($line); @@ -140,6 +146,10 @@ final class HttpTransport $options[CURLOPT_NOBODY] = true; } + if ($resolve !== []) { + $options[CURLOPT_RESOLVE] = $resolve; + } + $caInfo = Env::get('AI_CAINFO', '') ?? ''; if ($caInfo !== '') { @@ -158,7 +168,8 @@ final class HttpTransport if ($errno !== 0 && !($truncated && $errno === 23)) { throw new AiException( 'HTTP-ошибка: ' . ($error !== '' ? $error : 'код ' . $errno) - . self::tlsHint($error, $verify) + . self::tlsHint($error, $verify), + $errno, // код cURL: по нему Retry отличает таймаут от обрыва связи ); } @@ -167,6 +178,7 @@ final class HttpTransport 'body' => $response, 'location' => $location, 'content_type' => $contentType, + 'retry_after' => $retryAfter, 'truncated' => $truncated, ]; } diff --git a/src/Retry.php b/src/Retry.php new file mode 100644 index 0000000..bc6f4a4 --- /dev/null +++ b/src/Retry.php @@ -0,0 +1,139 @@ +sleep = $sleep ?? static function (float $seconds): void { + usleep((int) round($seconds * 1_000_000)); + }; + } + + public static function none(): self + { + return new self(maxRetries: 0); + } + + /** + * Выполнить попытку, повторяя её при временных сбоях. + * + * @template T of array{status: int, retry_after?: string|null} + * @param \Closure(): T $attempt + * @return T последний ответ — успешный или с ошибкой, если повторы кончились + * @throws AiException сетевая ошибка последней попытки + */ + public function run(\Closure $attempt): array + { + for ($try = 0; ; $try++) { + $canRetry = $try < $this->maxRetries; + + try { + $response = $attempt(); + } catch (AiException $e) { + if (!$canRetry || $e->getCode() === self::CURL_TIMEOUT) { + throw $e; + } + + ($this->sleep)($this->backoff($try)); + + continue; + } + + if (!$canRetry || !in_array($response['status'], self::RETRYABLE_STATUS, true)) { + return $response; + } + + $delay = $this->delay($try, $response['retry_after'] ?? null); + + if ($delay === null) { + return $response; + } + + ($this->sleep)($delay); + } + } + + /** + * Пауза перед повтором номер $try + 1 или null — не повторять, + * потому что сервер просит ждать дольше maxDelay. + */ + public function delay(int $try, ?string $retryAfter): ?float + { + $requested = self::parseRetryAfter($retryAfter); + + if ($requested === null) { + return $this->backoff($try); + } + + return $requested > $this->maxDelay ? null : $requested; + } + + private function backoff(int $try): float + { + $delay = $this->baseDelay * (2 ** $try); + $jitter = 0.5 + mt_rand() / mt_getrandmax() * 0.5; + + return min($this->maxDelay, $delay * $jitter); + } + + /** + * Retry-After бывает числом секунд или HTTP-датой. + */ + private static function parseRetryAfter(?string $value): ?float + { + $value = trim((string) $value); + + if ($value === '') { + return null; + } + + if (is_numeric($value)) { + return max(0.0, (float) $value); + } + + $time = strtotime($value); + + return $time === false ? null : max(0.0, (float) ($time - time())); + } +} diff --git a/tests/cases/client.php b/tests/cases/client.php new file mode 100644 index 0000000..aa0d933 --- /dev/null +++ b/tests/cases/client.php @@ -0,0 +1,207 @@ + ['pipe', 'r'], 1 => ['file', $state . '/server.log', 'w'], 2 => ['file', $state . '/server.log', 'a']], + $pipes, + null, + ['STUB_STATE_DIR' => $state] + getenv(), + ); + + if (!is_resource($process)) { + return null; + } + + // Ждём, пока сервер начнёт принимать соединения. + for ($i = 0; $i < 100; $i++) { + $socket = @fsockopen('127.0.0.1', $port, $errno, $error, 0.1); + + if ($socket !== false) { + fclose($socket); + + return $server = ['url' => 'http://127.0.0.1:' . $port, 'state' => $state]; + } + + usleep(50_000); + } + + return null; +} + +/** + * Клиент на сценарий поддельного сервера. Паузы повторов — миллисекунды. + */ +function stubClient(string $scenario, int $retries = 2): AiClient +{ + $server = stubServer(); + + if ($server === null) { + throw new RuntimeException('не удалось запустить встроенный сервер PHP'); + } + + return new AiClient( + apiKey: 'test-key', + model: 'stub', + baseUrl: $server['url'] . '/' . $scenario, + timeout: 5.0, + retry: new Retry(maxRetries: $retries, baseDelay: 0.01), + ); +} + +function stubCalls(string $scenario): int +{ + return (int) @file_get_contents(stubServer()['state'] . '/' . $scenario . '.count'); +} + +test('client: текстовый ответ и usage', function (): void { + $result = stubClient('ok')->chat([['role' => 'user', 'content' => 'привет']]); + + assertSame('привет', $result->text); + assertSame(false, $result->hasToolCalls()); + assertSame(11, $result->usage['prompt_tokens']); +}); + +test('client: tool_calls разбираются, аргументы из JSON-строки', function (): void { + $result = stubClient('tools')->chat([['role' => 'user', 'content' => '2+2?']]); + + assertSame(true, $result->hasToolCalls()); + assertSame('call_42', $result->toolCalls[0]['id']); + assertSame('calculator', $result->toolCalls[0]['name']); + assertSame(['expression' => '2+2'], $result->toolCalls[0]['arguments']); + assertSame('call_42', $result->assistantMessage['tool_calls'][0]['id']); +}); + +test('client: в запросе модель, ключ и инструменты', function (): void { + $tools = (new ToolRegistry())->add(new CalculatorTool()); + $result = stubClient('echo')->chat([['role' => 'user', 'content' => 'x']], $tools->definitions(), [ + 'tool_choice' => 'calculator', + 'parallel_tool_calls' => false, + ]); + + $sent = json_decode($result->text, true); + + assertSame('stub', $sent['model']); + assertSame('calculator', $sent['tools'][0]['function']['name']); + assertSame(['type' => 'function', 'function' => ['name' => 'calculator']], $sent['tool_choice']); + assertSame(false, $sent['parallel_tool_calls']); +}); + +test('client: 503 повторяется и запрос проходит со второго раза', function (): void { + $result = stubClient('flaky')->chat([['role' => 'user', 'content' => 'x']]); + + assertSame('со второго раза', $result->text); + assertSame(2, stubCalls('flaky')); +}); + +test('client: повторы кончились — понятная ошибка с HTTP-кодом', function (): void { + $client = stubClient('down', retries: 2); + $message = ''; + + try { + $client->chat([['role' => 'user', 'content' => 'x']]); + } catch (AiException $e) { + $message = $e->getMessage(); + } + + assertContains('HTTP 503', $message); + assertSame(3, stubCalls('down'), 'первая попытка + 2 повтора'); +}); + +test('client: 401 не повторяется', function (): void { + $client = stubClient('bad-key'); + $message = ''; + + try { + $client->chat([['role' => 'user', 'content' => 'x']]); + } catch (AiException $e) { + $message = $e->getMessage(); + } + + assertContains('HTTP 401: Invalid API key', $message); + assertSame(1, stubCalls('bad-key')); +}); + +test('client: не-JSON ответ — понятная ошибка', function (): void { + $client = stubClient('garbage'); + + assertThrows(static fn () => $client->chat([['role' => 'user', 'content' => 'x']])); +}); + +test('client: агент целиком по HTTP — инструмент, затем ответ', function (): void { + // Сервер всегда отвечает tool_calls: агент упрётся в maxRounds и + // попросит ответ без инструментов — это тоже проверка цикла по сети. + $agent = new Agent( + client: stubClient('tools'), + tools: (new ToolRegistry())->add(new CalculatorTool()), + maxRounds: 1, + ); + + $agent->ask('2+2?'); + + assertSame('2+2 = 4', $agent->trace()[0]['output']); + assertTrue($agent->usage()['prompt_tokens'] >= 22, 'usage копится за все запросы'); +}); + +// Остановить сервер до того, как run.php удалит tests/tmp +// (на Windows открытый лог не даёт удалить каталог). +stubServer(stop: true); diff --git a/tests/cases/files.php b/tests/cases/files.php index c3e8a1a..b84fac6 100644 --- a/tests/cases/files.php +++ b/tests/cases/files.php @@ -133,6 +133,28 @@ test('csv_query: неизвестная колонка — понятная ош assertContains('name, city', $result); }); +test('csv_query: ошибки ввода — текстом, а не исключением', function (): void { + $dir = testDir(); + file_put_contents($dir . '/people.csv', "name,city\nИван,Тула\n"); + file_put_contents($dir . '/empty.csv', ''); + $tool = new CsvQueryTool(new FileSandbox($dir)); + + assertContains('Фильтр должен быть', $tool->handle(['path' => 'people.csv', 'where' => 'city'])); + assertContains('Нет колонки "age"', $tool->handle(['path' => 'people.csv', 'columns' => 'name, age'])); + assertContains('заголовок', $tool->handle(['path' => 'empty.csv'])); + assertContains('Путь не найден', $tool->handle(['path' => 'nope.csv'])); +}); + +test('csv_query: лимит считает строки без заголовка', function (): void { + $dir = testDir(); + file_put_contents($dir . '/n.csv', "n\n1\n2\n3\n4\n"); + + $result = (new CsvQueryTool(new FileSandbox($dir)))->handle(['path' => 'n.csv', 'limit' => 2]); + + assertContains('2 из 4 строк', $result); + assertTrue(!str_contains($result, '3'), 'лишняя строка: ' . $result); +}); + // --------------------------------------------------------------------------- // Запись и правка файлов // --------------------------------------------------------------------------- @@ -227,6 +249,21 @@ test('replace_in_file: несколько совпадений требуют al assertContains('Найдено совпадений: 2', $result); }); +test('replace_in_file: all заменяет все и сообщает сколько', function (): void { + $dir = testDir(); + file_put_contents($dir . '/code.txt', "x\nx\nx\n"); + + $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'code.txt', + 'search' => 'x', + 'replace' => 'y', + 'all' => true, + ]); + + assertContains('Заменено вхождений: 3', $result); + assertSame("y\ny\ny\n", file_get_contents($dir . '/code.txt')); +}); + test('replace_in_file: не найдено — понятная ошибка', function (): void { $dir = testDir(); file_put_contents($dir . '/code.txt', 'abc'); diff --git a/tests/cases/http.php b/tests/cases/http.php index 83ff126..d1a7c80 100644 --- a/tests/cases/http.php +++ b/tests/cases/http.php @@ -4,10 +4,12 @@ declare(strict_types=1); // Тесты: http. Запускаются из tests/run.php. +use AiSdk\AiException; use AiSdk\HttpTransport; -use AiSdk\HttpRequest; +use AiSdk\Tools\Support\HttpRequest; use AiSdk\Tool; use AiSdk\Tools\HttpRequestTool; +use AiSdk\Tools\Support\UrlGuard; // --------------------------------------------------------------------------- // http_request: сборка запроса (без сети) @@ -118,4 +120,105 @@ test('http_request: allowPrivate снимает блокировку внутр ); }); +// --------------------------------------------------------------------------- +// UrlGuard: IPv6, закрепление адресов (DNS rebinding) +// --------------------------------------------------------------------------- + +/** + * UrlGuard с подменённым DNS: хост → заданные адреса. + * + * @param array> $dns + */ +function guardWithDns(array $dns): UrlGuard +{ + return new UrlGuard(resolver: static fn (string $host): array => $dns[$host] ?? []); +} + +test('url_guard: публичный хост закрепляется на проверенных адресах', function (): void { + $guard = guardWithDns(['api.example.com' => ['93.184.216.34', '2606:2800:220:1::1']]); + + assertSame( + ['api.example.com:443:93.184.216.34,[2606:2800:220:1::1]'], + $guard->pin('https://api.example.com/v1') + ); + assertSame( + ['api.example.com:8080:93.184.216.34,[2606:2800:220:1::1]'], + $guard->pin('http://api.example.com:8080/') + ); +}); + +test('url_guard: один приватный адрес среди публичных — отказ', function (): void { + $guard = guardWithDns([ + 'mixed.example' => ['93.184.216.34', '127.0.0.1'], + 'v6.example' => ['93.184.216.34', '::1'], + ]); + + assertThrows(static fn () => $guard->pin('https://mixed.example/')); + assertThrows(static fn () => $guard->pin('https://v6.example/')); +}); + +test('url_guard: хост без адресов — отказ', function (): void { + assertThrows(static fn () => guardWithDns([])->pin('https://nowhere.example/')); +}); + +test('url_guard: приватные и служебные IPv6 запрещены', function (): void { + foreach ([ + '::1', // loopback + '::ffff:127.0.0.1', // IPv4-mapped + 'fc00::1', // ULA + 'fe80::1', // link-local + '64:ff9b::7f00:1', // NAT64 → 127.0.0.1 + '64:ff9b::a00:5', // NAT64 → 10.0.0.5 + '2002:7f00:1::1', // 6to4 → 127.0.0.1 + '2001:db8::1', // документационный + ] as $ip) { + assertTrue(!UrlGuard::isPublicIp($ip), 'должен быть запрещён: ' . $ip); + } + + assertTrue(UrlGuard::isPublicIp('2606:4700::1111'), 'публичный IPv6'); + assertTrue(UrlGuard::isPublicIp('64:ff9b::808:808'), 'NAT64 → 8.8.8.8 — публичный'); + assertTrue(!UrlGuard::isPublicIp('100.64.1.1'), 'CGNAT'); +}); + +test('url_guard: IPv6-литерал в URL проверяется', function (): void { + $tool = new HttpRequestTool(); + + assertContains('приватному адресу', $tool->handle(['url' => 'http://[::1]/x'])); + assertContains('приватному адресу', $tool->handle(['url' => 'http://[::ffff:127.0.0.1]/x'])); +}); + +test('url_guard: *.localhost запрещён', function (): void { + assertContains('локальному адресу', (new HttpRequestTool())->handle(['url' => 'http://app.localhost/'])); +}); + +test('http: cURL подключается к закреплённому адресу, а не резолвит имя', function (): void { + // Имя в зоне .invalid не резолвится никогда. Если cURL пошёл + // по закреплённому 127.0.0.1, ошибка будет про соединение, а не про DNS. + // Прокси из окружения резолвит имена сам, поэтому для теста его обходим. + $noProxy = getenv('NO_PROXY'); + putenv('NO_PROXY=pinned.invalid'); + + try { + $control = ''; + $pinned = ''; + + try { + HttpTransport::request('http://pinned.invalid:9/', 2.0); + } catch (AiException $e) { + $control = $e->getMessage(); + } + + try { + HttpTransport::request('http://pinned.invalid:9/', 2.0, resolve: ['pinned.invalid:9:127.0.0.1']); + } catch (AiException $e) { + $pinned = $e->getMessage(); + } + } finally { + putenv($noProxy === false ? 'NO_PROXY' : 'NO_PROXY=' . $noProxy); + } + + assertContains('resolve', $control, 'без закрепления имя должно не резолвиться'); + assertTrue($pinned !== '' && stripos($pinned, 'resolve') === false, 'имя не должно резолвиться: ' . $pinned); +}); + diff --git a/tests/cases/retry.php b/tests/cases/retry.php new file mode 100644 index 0000000..6b44ec5 --- /dev/null +++ b/tests/cases/retry.php @@ -0,0 +1,174 @@ + $sleeps + */ +function recordingRetry(array &$sleeps, int $maxRetries = 2, float $maxDelay = 30.0): Retry +{ + return new Retry( + maxRetries: $maxRetries, + baseDelay: 1.0, + maxDelay: $maxDelay, + sleep: static function (float $seconds) use (&$sleeps): void { + $sleeps[] = $seconds; + }, + ); +} + +/** + * Попытка, которая по очереди отдаёт заготовленные ответы или бросает исключения. + * + * @param list|\Throwable> $script + */ +function scriptedAttempt(array $script, int &$calls): \Closure +{ + return static function () use (&$script, &$calls): array { + $calls++; + $next = array_shift($script); + + if ($next instanceof \Throwable) { + throw $next; + } + + return $next + ['body' => '', 'retry_after' => null]; + }; +} + +test('retry: 429 и 503 повторяются, потом успех', function (): void { + $sleeps = []; + $calls = 0; + + $response = recordingRetry($sleeps)->run(scriptedAttempt([ + ['status' => 429], + ['status' => 503], + ['status' => 200], + ], $calls)); + + assertSame(200, $response['status']); + assertSame(3, $calls); + assertSame(2, count($sleeps)); + assertTrue($sleeps[0] >= 0.5 && $sleeps[0] <= 1.0, 'первая пауза 0.5–1 с: ' . $sleeps[0]); + assertTrue($sleeps[1] >= 1.0 && $sleeps[1] <= 2.0, 'вторая пауза 1–2 с: ' . $sleeps[1]); +}); + +test('retry: повторы кончились — возвращается последний ответ с ошибкой', function (): void { + $sleeps = []; + $calls = 0; + + $response = recordingRetry($sleeps, maxRetries: 1)->run(scriptedAttempt([ + ['status' => 500], + ['status' => 502], + ['status' => 200], + ], $calls)); + + assertSame(502, $response['status']); + assertSame(2, $calls); +}); + +test('retry: 400, 401 и 404 не повторяются', function (): void { + foreach ([400, 401, 404] as $status) { + $sleeps = []; + $calls = 0; + + $response = recordingRetry($sleeps)->run(scriptedAttempt([['status' => $status], ['status' => 200]], $calls)); + + assertSame($status, $response['status']); + assertSame(1, $calls, 'HTTP ' . $status); + } +}); + +test('retry: Retry-After важнее расчёта', function (): void { + $sleeps = []; + $calls = 0; + + recordingRetry($sleeps)->run(scriptedAttempt([ + ['status' => 429, 'retry_after' => '7'], + ['status' => 200], + ], $calls)); + + assertSame([7.0], $sleeps); +}); + +test('retry: Retry-After больше maxDelay — не ждём, отдаём ошибку', function (): void { + $sleeps = []; + $calls = 0; + + $response = recordingRetry($sleeps, maxDelay: 10.0)->run(scriptedAttempt([ + ['status' => 429, 'retry_after' => '120'], + ['status' => 200], + ], $calls)); + + assertSame(429, $response['status']); + assertSame(1, $calls); + assertSame([], $sleeps); +}); + +test('retry: Retry-After в виде HTTP-даты', function (): void { + $delay = (new Retry())->delay(0, gmdate('D, d M Y H:i:s', time() + 5) . ' GMT'); + + assertTrue($delay !== null && $delay >= 3.0 && $delay <= 5.0, 'пауза ~5 с: ' . var_export($delay, true)); +}); + +test('retry: обрыв связи повторяется', function (): void { + $sleeps = []; + $calls = 0; + + $response = recordingRetry($sleeps)->run(scriptedAttempt([ + new AiException('HTTP-ошибка: Connection reset', 56), + ['status' => 200], + ], $calls)); + + assertSame(200, $response['status']); + assertSame(2, $calls); +}); + +test('retry: таймаут не повторяется', function (): void { + $sleeps = []; + $calls = 0; + $retry = recordingRetry($sleeps); + $attempt = scriptedAttempt([ + new AiException('HTTP-ошибка: Operation timed out', 28), + ['status' => 200], + ], $calls); + + assertThrows(static fn () => $retry->run($attempt)); + + assertSame(1, $calls); +}); + +test('retry: сетевая ошибка после всех повторов пробрасывается', function (): void { + $sleeps = []; + $calls = 0; + $retry = recordingRetry($sleeps, maxRetries: 2); + $attempt = scriptedAttempt([ + new AiException('reset', 56), + new AiException('reset', 56), + new AiException('reset', 56), + ], $calls); + + assertThrows(static fn () => $retry->run($attempt)); + + assertSame(3, $calls); +}); + +test('retry: Retry::none() — одна попытка', function (): void { + $calls = 0; + + $response = Retry::none()->run(scriptedAttempt([['status' => 503], ['status' => 200]], $calls)); + + assertSame(503, $response['status']); + assertSame(1, $calls); +}); + +test('retry: пауза не превышает maxDelay', function (): void { + assertTrue((new Retry(baseDelay: 10.0, maxDelay: 15.0))->delay(5, null) <= 15.0); +}); diff --git a/tests/cases/shell.php b/tests/cases/shell.php index 95ea883..6ea6524 100644 --- a/tests/cases/shell.php +++ b/tests/cases/shell.php @@ -54,4 +54,35 @@ test('shell: пустая команда не запускается', function assertContains('Пустая команда', (new ShellTool(tmpDir: __DIR__ . '/tmp'))->handle(['command' => ' '])); }); +test('shell: allowlist нельзя обойти склейкой команд', function (): void { + $tool = new ShellTool(allow: ['echo'], tmpDir: __DIR__ . '/tmp'); + + foreach ([ + 'echo ok; whoami', + 'echo ok && whoami', + 'echo ok || whoami', + 'echo ok | whoami', + 'echo ok & whoami', + 'echo `whoami`', + 'echo $(whoami)', + 'echo ok > out.txt', + 'echo ok < in.txt', + "echo ok\nwhoami", + "echo ok\r\nwhoami", + 'echo (whoami)', + ] as $command) { + $result = $tool->handle(['command' => $command]); + + assertContains('Команда отклонена', $result, $command); + assertTrue(!str_contains($result, 'exit:'), 'команда не должна запускаться: ' . $command); + } +}); + +test('shell: без allowlist метасимволы разрешены', function (): void { + $result = (new ShellTool(tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'echo a && echo b']); + + assertContains('exit: 0', $result); + assertContains('b', $result); +}); + diff --git a/tests/cases/support.php b/tests/cases/support.php index 6e4a678..4cb4e00 100644 --- a/tests/cases/support.php +++ b/tests/cases/support.php @@ -10,32 +10,37 @@ use AiSdk\Cost; use AiSdk\ToolRegistry; use AiSdk\Tools\HttpRequestTool; use AiSdk\Tools\ShellTool; +use AiSdk\Tools\CalculatorTool; +use AiSdk\Tools\Support\Number; use AiSdk\Tools\Support\Timeout; test('timeout: значение модели в пределах максимума', function (): void { - $timeout = Timeout::from(['timeout' => 5], 10.0, 60.0); - - assertSame(5.0, $timeout->seconds); - assertSame(false, $timeout->clamped()); + assertSame(5.0, Timeout::seconds(['timeout' => 5], 10.0, 60.0)); }); test('timeout: без параметра берётся значение по умолчанию', function (): void { - assertSame(10.0, Timeout::from([], 10.0, 60.0)->seconds); + assertSame(10.0, Timeout::seconds([], 10.0, 60.0)); }); test('timeout: больше максимума урезается', function (): void { - $timeout = Timeout::from(['timeout' => 999], 10.0, 60.0); - - assertSame(60.0, $timeout->seconds); - assertSame(true, $timeout->clamped()); + assertSame(60.0, Timeout::seconds(['timeout' => 999], 10.0, 60.0)); }); test('timeout: меньше секунды поднимается до одной', function (): void { - assertSame(1.0, Timeout::from(['timeout' => 0.1], 10.0, 60.0)->seconds); + assertSame(1.0, Timeout::seconds(['timeout' => 0.1], 10.0, 60.0)); }); test('timeout: нечисловое значение игнорируется', function (): void { - assertSame(10.0, Timeout::from(['timeout' => 'abc'], 10.0, 60.0)->seconds); + assertSame(10.0, Timeout::seconds(['timeout' => 'abc'], 10.0, 60.0)); +}); + +test('number: большие числа не превращаются в мусор', function (): void { + assertSame('4', Number::format(4.0)); + assertSame('0.3333333333', Number::format(1 / 3)); + assertSame('-2.5', Number::format(-2.5)); + assertSame('0', Number::format(-0.0)); + assertContains('E+28', Number::format(9.0 ** 30)); + assertContains('E+28', (new CalculatorTool())->handle(['expression' => '9^30'])); }); test('tools: timeout есть в схемах run_command и http_request', function (): void { diff --git a/tests/cases/tools.php b/tests/cases/tools.php index 396d23f..649d864 100644 --- a/tests/cases/tools.php +++ b/tests/cases/tools.php @@ -240,4 +240,13 @@ test('json_query: битый JSON', function (): void { assertContains('Некорректный JSON', $result); }); +test('json_query: варианты записи пути', function (): void { + $json = '{"data":{"items":[{"id":42},{"id":7}]}}'; + $tool = new JsonQueryTool(); + + assertSame('$.data.items[1].id = 7', $tool->handle(['json' => $json, 'path' => '$.data.items[1].id'])); + assertSame('data[items][0][id] = 42', $tool->handle(['json' => $json, 'path' => 'data[items][0][id]'])); + assertContains('Не закрыта', $tool->handle(['json' => $json, 'path' => 'data.items[0'])); +}); + diff --git a/tests/stub/llm-server.php b/tests/stub/llm-server.php new file mode 100644 index 0000000..d077bc0 --- /dev/null +++ b/tests/stub/llm-server.php @@ -0,0 +1,93 @@ +.count. + */ + +$scenario = explode('/', trim((string) parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'))[0] ?? ''; +$stateDir = (string) getenv('STUB_STATE_DIR'); +$counter = $stateDir . '/' . preg_replace('/[^a-z-]/', '', $scenario) . '.count'; +$calls = (int) @file_get_contents($counter) + 1; +file_put_contents($counter, (string) $calls); + +header('Content-Type: application/json'); + +/** + * @param array $message + */ +function reply(array $message): void +{ + echo json_encode([ + 'choices' => [['message' => $message + ['role' => 'assistant']]], + 'usage' => ['prompt_tokens' => 11, 'completion_tokens' => 3], + ], JSON_UNESCAPED_UNICODE); +} + +function fail(int $status, string $message): void +{ + http_response_code($status); + echo json_encode(['error' => ['message' => $message]]); +} + +switch ($scenario) { + case 'ok': + reply(['content' => 'привет']); + break; + + case 'tools': + reply([ + 'content' => null, + 'tool_calls' => [[ + 'id' => 'call_42', + 'type' => 'function', + 'function' => ['name' => 'calculator', 'arguments' => '{"expression":"2+2"}'], + ]], + ]); + break; + + case 'flaky': + if ($calls === 1) { + header('Retry-After: 0'); + fail(503, 'перегружен'); + break; + } + + reply(['content' => 'со второго раза']); + break; + + case 'down': + fail(503, 'перегружен'); + break; + + case 'bad-key': + fail(401, 'Invalid API key'); + break; + + case 'garbage': + header('Content-Type: text/html'); + echo '502 Bad Gateway'; + break; + + case 'echo': + reply(['content' => (string) file_get_contents('php://input')]); + break; + + default: + fail(404, 'нет сценария ' . $scenario); +} diff --git a/tests/support.php b/tests/support.php index d1bae3d..73e87d3 100644 --- a/tests/support.php +++ b/tests/support.php @@ -4,34 +4,8 @@ declare(strict_types=1); // Общие помощники и заглушки для тестов. -use AiSdk\Agent; use AiSdk\ChatClient; use AiSdk\ChatResult; -use AiSdk\HttpTransport; -use AiSdk\HttpRequest; -use AiSdk\LoggingClient; -use AiSdk\Tool; -use AiSdk\ToolRegistry; -use AiSdk\Tools\CalculatorTool; -use AiSdk\Tools\ConvertUnitsTool; -use AiSdk\Tools\CsvQueryTool; -use AiSdk\Tools\DateCalcTool; -use AiSdk\Tools\FileSandbox; -use AiSdk\Tools\FindFilesTool; -use AiSdk\Tools\JsonQueryTool; -use AiSdk\Tools\FinishTool; -use AiSdk\Tools\HashTool; -use AiSdk\Tools\HttpRequestTool; -use AiSdk\Tools\ListDirTool; -use AiSdk\Tools\ReadFileTool; -use AiSdk\Tools\ReplaceInFileTool; -use AiSdk\Tools\SearchFilesTool; -use AiSdk\Tools\ShellTool; -use AiSdk\Tools\TimeTool; -use AiSdk\Tools\WriteFileTool; -use AiSdk\Tools\UuidTool; - - /** * Тесты SDK: без сети, без модели и без API-ключа. @@ -45,7 +19,6 @@ use AiSdk\Tools\UuidTool; require dirname(__DIR__) . '/bootstrap.php'; - mb_internal_encoding('UTF-8'); $passed = 0; diff --git a/tools/CalculatorTool.php b/tools/CalculatorTool.php index e55b7d6..3abc6f8 100644 --- a/tools/CalculatorTool.php +++ b/tools/CalculatorTool.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace AiSdk\Tools; use AiSdk\Tool; +use AiSdk\Tools\Support\Number; /** * Арифметика без eval(): рекурсивный спуск по выражению. @@ -77,7 +78,7 @@ final class CalculatorTool implements Tool return 'Результат не является числом (деление на ноль?).'; } - return $expression . ' = ' . $this->format($value); + return $expression . ' = ' . Number::format($value); } private function parseExpression(): float @@ -178,13 +179,4 @@ final class CalculatorTool implements Tool { return $this->source[$this->position] ?? ''; } - - private function format(float $value): string - { - if (abs($value - round($value)) < 1e-9) { - return (string) (int) round($value); - } - - return rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.'); - } } diff --git a/tools/ConvertUnitsTool.php b/tools/ConvertUnitsTool.php index 45fba97..1b24351 100644 --- a/tools/ConvertUnitsTool.php +++ b/tools/ConvertUnitsTool.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace AiSdk\Tools; use AiSdk\Tool; +use AiSdk\Tools\Support\Number; /** * Перевод единиц: температура, длина, масса, скорость. @@ -96,7 +97,7 @@ final class ConvertUnitsTool implements Tool . 'Доступно: c, f, k, mm, cm, m, km, in, ft, yd, mi, mg, g, kg, t, oz, lb, mps, kmh, mph, kn.'; } - return $this->format($value) . ' ' . $from . ' = ' . $this->format($result) . ' ' . $to; + return Number::format($value, 6) . ' ' . $from . ' = ' . Number::format($result, 6) . ' ' . $to; } private function convert(float $value, string $from, string $to): ?float @@ -137,13 +138,4 @@ final class ConvertUnitsTool implements Tool return self::ALIASES[$unit] ?? $unit; } - - private function format(float $value): string - { - if (abs($value - round($value)) < 1e-9) { - return (string) (int) round($value); - } - - return rtrim(rtrim(number_format($value, 6, '.', ''), '0'), '.'); - } } diff --git a/tools/CsvQueryTool.php b/tools/CsvQueryTool.php index 664e7bd..5a99dbc 100644 --- a/tools/CsvQueryTool.php +++ b/tools/CsvQueryTool.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace AiSdk\Tools; use AiSdk\Tool; +use AiSdk\Tools\Support\Bytes; /** * Выборка из CSV-файла внутри песочницы. @@ -54,156 +55,107 @@ final class CsvQueryTool implements Tool { $path = (string) ($args['path'] ?? ''); $limit = (int) ($args['limit'] ?? 20); + $limit = $limit < 1 ? 20 : min($limit, self::MAX_ROWS); $delimiter = (string) ($args['delimiter'] ?? ','); $delimiter = $delimiter !== '' ? $delimiter[0] : ','; - if ($limit < 1) { - $limit = 20; - } - - $limit = min($limit, self::MAX_ROWS); - try { - $file = $this->sandbox->resolve($path); + [$header, $rows] = $this->read($path, $delimiter); + $columns = $this->columnIndexes($header, (string) ($args['columns'] ?? '')); + $filter = $this->parseWhere($header, (string) ($args['where'] ?? '')); } catch (\RuntimeException $e) { return $e->getMessage(); } - if (!is_file($file)) { - return 'Это не файл: ' . $path; + $table = [array_map(static fn (int $i): string => $header[$i], $columns)]; + + foreach ($rows as $row) { + if ($filter !== null && !$this->matches($row, $filter)) { + continue; + } + + $table[] = array_map(fn (int $i): string => $this->cell($row[$i] ?? ''), $columns); + + if (count($table) > $limit) { + break; + } } - $size = filesize($file); + $found = count($table) - 1; - if ($size !== false && $size > self::MAX_BYTES) { - return 'CSV слишком большой: ' . round($size / 1048576, 1) . ' МБ (максимум 5 МБ).'; + if ($found === 0) { + return 'Подходящих строк нет (всего строк: ' . count($rows) . ').'; + } + + return 'CSV ' . $path . ': ' . $found . ' из ' . count($rows) . " строк\n" . $this->render($table); + } + + /** + * Заголовок и строки файла. + * + * @return array{0: list, 1: list>} + * @throws \RuntimeException + */ + private function read(string $path, string $delimiter): array + { + $file = $this->sandbox->resolve($path); + + if (!is_file($file)) { + throw new \RuntimeException('Это не файл: ' . $path); + } + + $size = (int) filesize($file); + + if ($size > self::MAX_BYTES) { + throw new \RuntimeException('CSV слишком большой: ' . Bytes::human($size) . ' (максимум 5 МБ).'); } $handle = fopen($file, 'rb'); if ($handle === false) { - return 'Не удалось открыть файл.'; + throw new \RuntimeException('Не удалось открыть файл.'); } - $header = fgetcsv($handle, 0, $delimiter); - - if ($header === false || $header === [null] || $header === []) { - fclose($handle); - - return 'Не удалось прочитать заголовок CSV.'; - } - - $header = array_map(static fn ($name): string => trim((string) $name), $header); - - $requested = $this->requestedColumns($header, (string) ($args['columns'] ?? '')); - - if (is_string($requested)) { - fclose($handle); - - return $requested; - } - - $filter = $this->parseWhere($header, (string) ($args['where'] ?? '')); - - if (is_string($filter)) { - fclose($handle); - - return $filter; - } - - $allRows = $this->readRows($handle, $delimiter); - fclose($handle); - - $total = count($allRows); - $rows = $this->pickRows($allRows, $header, $requested, $filter, $limit); - - if ($rows === []) { - return 'Подходящих строк нет (всего строк: ' . $total . ').'; - } - - $table = [array_map(static fn (int $i): string => $header[$i], $requested)]; - $table = array_merge($table, $rows); - - return 'CSV ' . $path . ': ' . count($rows) . ' из ' . $total . " строк\n" . $this->render($table); - } - - /** - * @param resource $handle - * @return list> - */ - private function readRows($handle, string $delimiter): array - { $rows = []; while (($row = fgetcsv($handle, 0, $delimiter)) !== false) { $rows[] = array_map(static fn ($cell): string => trim((string) $cell), $row); } - return $rows; - } + fclose($handle); - /** - * @param list> $allRows - * @param list $header - * @param list $requested - * @param array{index: int, value: string, contains: bool}|null $filter - * @return list> - */ - private function pickRows(array $allRows, array $header, array $requested, ?array $filter, int $limit): array - { - $rows = []; + $header = array_shift($rows); - foreach ($allRows as $row) { - if ($filter !== null && !$this->matches($row, $header, $filter)) { - continue; - } - - $picked = []; - - foreach ($requested as $index) { - $picked[] = $this->cell($row[$index] ?? ''); - } - - $rows[] = $picked; - - if (count($rows) >= $limit) { - break; - } + if ($header === null || $header === ['']) { + throw new \RuntimeException('Не удалось прочитать заголовок CSV.'); } - return $rows; + return [$header, $rows]; } + /** * @param list $header - * @return list|string индексы колонок или текст ошибки + * @return list индексы нужных колонок (пусто в запросе — все) + * @throws \RuntimeException */ - private function requestedColumns(array $header, string $columns): array|string + private function columnIndexes(array $header, string $columns): array { if (trim($columns) === '') { return array_keys($header); } - $wanted = array_map('trim', explode(',', $columns)); - $indexes = []; - - foreach ($wanted as $name) { - $index = array_search($name, $header, true); - - if ($index === false) { - return 'Нет колонки "' . $name . '". Есть: ' . implode(', ', $header) . '.'; - } - - $indexes[] = (int) $index; - } - - return $indexes; + return array_map( + fn (string $name): int => $this->columnIndex($header, trim($name)), + explode(',', $columns), + ); } /** * @param list $header - * @return array{index: int, value: string, contains: bool}|string|null + * @return array{index: int, value: string, contains: bool}|null + * @throws \RuntimeException */ - private function parseWhere(array $header, string $where): array|string|null + private function parseWhere(array $header, string $where): ?array { $where = trim($where); @@ -212,29 +164,36 @@ final class CsvQueryTool implements Tool } if (preg_match('/^([^=~]+)([=~])(.*)$/u', $where, $match) !== 1) { - return 'Фильтр должен быть вида "колонка=значение" или "колонка~значение".'; - } - - $column = trim($match[1]); - $index = array_search($column, $header, true); - - if ($index === false) { - return 'Нет колонки "' . $column . '". Есть: ' . implode(', ', $header) . '.'; + throw new \RuntimeException('Фильтр должен быть вида "колонка=значение" или "колонка~значение".'); } return [ - 'index' => (int) $index, + 'index' => $this->columnIndex($header, trim($match[1])), 'value' => trim($match[3]), 'contains' => $match[2] === '~', ]; } /** - * @param list $row * @param list $header + * @throws \RuntimeException + */ + private function columnIndex(array $header, string $name): int + { + $index = array_search($name, $header, true); + + if ($index === false) { + throw new \RuntimeException('Нет колонки "' . $name . '". Есть: ' . implode(', ', $header) . '.'); + } + + return (int) $index; + } + + /** + * @param list $row * @param array{index: int, value: string, contains: bool} $filter */ - private function matches(array $row, array $header, array $filter): bool + private function matches(array $row, array $filter): bool { $cell = $row[$filter['index']] ?? ''; @@ -254,6 +213,7 @@ final class CsvQueryTool implements Tool : $value; } + /** * @param list> $table */ diff --git a/tools/FileSandbox.php b/tools/FileSandbox.php index d940153..b626f4e 100644 --- a/tools/FileSandbox.php +++ b/tools/FileSandbox.php @@ -112,11 +112,6 @@ final class FileSandbox return $realDirectory . DIRECTORY_SEPARATOR . $name; } - /** - * Атомарная запись: сначала во временный файл рядом, потом rename. - * Так при сбое не остаётся полузаписанный файл. - */ - /** * Путь для показа пользователю (относительно корня, если внутри него). */ diff --git a/tools/FindFilesTool.php b/tools/FindFilesTool.php index 0f1b969..753268a 100644 --- a/tools/FindFilesTool.php +++ b/tools/FindFilesTool.php @@ -13,7 +13,6 @@ use AiSdk\Tools\Support\FileWalker; */ final class FindFilesTool implements Tool { - public function __construct( private readonly FileSandbox $sandbox, private readonly int $defaultLimit = 100, @@ -99,9 +98,4 @@ final class FindFilesTool implements Tool return 'Найдено ' . count($found) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n" . implode("\n", $found); } - - /** - * @param callable(string): void $onFile - */ - } diff --git a/tools/HttpRequestTool.php b/tools/HttpRequestTool.php index b5fbfe4..90dd94a 100644 --- a/tools/HttpRequestTool.php +++ b/tools/HttpRequestTool.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace AiSdk\Tools; use AiSdk\HttpTransport; -use AiSdk\HttpRequest; +use AiSdk\Tools\Support\HttpRequest; use AiSdk\Tools\Support\Timeout; use AiSdk\Tools\Support\UrlGuard; use AiSdk\Tool; @@ -122,7 +122,7 @@ final class HttpRequestTool implements Tool $maxChars = (int) ($args['max_chars'] ?? $this->defaultChars); $maxChars = max(200, min($maxChars, 20000)); - $timeout = Timeout::from($args, $this->timeout, $this->maxTimeout); + $timeout = Timeout::seconds($args, $this->timeout, $this->maxTimeout); $body = $args['body'] ?? null; @@ -153,16 +153,19 @@ final class HttpRequestTool implements Tool $response = null; for ($hop = 0; $hop <= self::MAX_REDIRECTS; $hop++) { - $this->guard->assertAllowed($url); + // Проверка и запрос идут на одни и те же адреса: cURL не + // резолвит имя второй раз (защита от DNS rebinding). + $pinned = $this->guard->pin($url); $response = HttpTransport::request( $url, - $timeout->seconds, + $timeout, false, self::MAX_BYTES, $request->method, $request->headers, $request->body, + $pinned, ); $isRedirect = in_array($response['status'], [301, 302, 303, 307, 308], true); @@ -228,11 +231,4 @@ final class HttpRequestTool implements Tool return $this->auth[$host] ?? null; } - - - - } - - - diff --git a/tools/JsonQueryTool.php b/tools/JsonQueryTool.php index 80673d4..1f5935f 100644 --- a/tools/JsonQueryTool.php +++ b/tools/JsonQueryTool.php @@ -105,55 +105,17 @@ final class JsonQueryTool implements Tool } /** - * data.items[0].id -> ['data','items','0','id'] + * data.items[0].id -> ['data', 'items', '0', 'id']. Ведущий "$." допускается. * * @return list */ private function tokenize(string $path): array { - $path = trim($path); - $path = preg_replace('/^\$?\.?/', '', $path) ?? $path; - - $tokens = []; - $buffer = ''; - $length = strlen($path); - - for ($i = 0; $i < $length; $i++) { - $char = $path[$i]; - - if ($char === '.') { - if ($buffer !== '') { - $tokens[] = $buffer; - $buffer = ''; - } - - continue; - } - - if ($char === '[') { - if ($buffer !== '') { - $tokens[] = $buffer; - $buffer = ''; - } - - $end = strpos($path, ']', $i); - - if ($end === false) { - throw new \InvalidArgumentException('Не закрыта квадратная скобка в path.'); - } - - $tokens[] = substr($path, $i + 1, $end - $i - 1); - $i = $end; - - continue; - } - - $buffer .= $char; + if (substr_count($path, '[') !== substr_count($path, ']')) { + throw new \InvalidArgumentException('Не закрыта квадратная скобка в path.'); } - if ($buffer !== '') { - $tokens[] = $buffer; - } + $tokens = preg_split('/[.\[\]]+/', ltrim(trim($path), '$'), -1, PREG_SPLIT_NO_EMPTY) ?: []; if ($tokens === []) { throw new \InvalidArgumentException('Пустой path.'); diff --git a/tools/ListDirTool.php b/tools/ListDirTool.php index 7aaf764..780b93f 100644 --- a/tools/ListDirTool.php +++ b/tools/ListDirTool.php @@ -99,6 +99,4 @@ final class ListDirTool implements Tool return $text; } - } - diff --git a/tools/ReadFileTool.php b/tools/ReadFileTool.php index 7ff2b11..4824fbd 100644 --- a/tools/ReadFileTool.php +++ b/tools/ReadFileTool.php @@ -129,6 +129,4 @@ final class ReadFileTool implements Tool return 'Файл ' . $path . ', строки ' . $from . '–' . $to . ' из ' . $total . ":\n" . $text; } - } - diff --git a/tools/ReplaceInFileTool.php b/tools/ReplaceInFileTool.php index 693c4b3..7fc0676 100644 --- a/tools/ReplaceInFileTool.php +++ b/tools/ReplaceInFileTool.php @@ -90,9 +90,8 @@ final class ReplaceInFileTool implements Tool return 'Найдено совпадений: ' . $count . '. Уточни search или передай all: true.'; } - $updated = $all - ? str_replace($search, $replace, $content) - : $this->replaceOnce($content, $search, $replace); + // Здесь совпадение либо одно, либо all: true — str_replace подходит в обоих случаях. + $updated = str_replace($search, $replace, $content); try { AtomicWriter::write($file, $updated); @@ -100,23 +99,9 @@ final class ReplaceInFileTool implements Tool return $e->getMessage(); } - return 'Заменено вхождений: ' . ($all ? $count : 1) + return 'Заменено вхождений: ' . $count . ', файл ' . $this->sandbox->relative($file) . ': ' . strlen($updated) . ' Б.'; } - - /** - * Заменить только первое вхождение, не трогая остальные. - */ - private function replaceOnce(string $content, string $search, string $replace): string - { - $position = strpos($content, $search); - - if ($position === false) { - return $content; - } - - return substr_replace($content, $replace, $position, strlen($search)); - } } diff --git a/tools/SearchFilesTool.php b/tools/SearchFilesTool.php index 27d59ef..100491f 100644 --- a/tools/SearchFilesTool.php +++ b/tools/SearchFilesTool.php @@ -184,8 +184,4 @@ final class SearchFilesTool implements Tool return $matches; } - - /** - * @param callable(string): void $onFile - */ } diff --git a/tools/ShellTool.php b/tools/ShellTool.php index 9e4413e..a8282f9 100644 --- a/tools/ShellTool.php +++ b/tools/ShellTool.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace AiSdk\Tools; use AiSdk\Tool; +use AiSdk\Tools\Support\Number; use AiSdk\Tools\Support\Timeout; /** @@ -19,11 +20,38 @@ use AiSdk\Tools\Support\Timeout; * - ограничение вывода, чтобы не раздувать контекст; * - необязательный allowlist по первой команде. * + * Allowlist ограничивает только программу, а не то, что она сделает. + * Поэтому при заданном allowlist запрещены метасимволы оболочки (; & | ` $ + * < > ( ) и перевод строки) — иначе «git status; rm -rf ~» прошла бы как git. + * Но и разрешённая программа может исполнять код сама: php -r, git -c + * core.pager=..., find -exec, npm run. Не кладите такие в allowlist, + * если модели нельзя доверять. + * * Чего здесь НЕТ: изоляции, песочницы, ограничения файловой системы. * Команда может делать всё, что может пользователь процесса. */ final class ShellTool implements Tool { + /** + * Символы, которыми в bash, sh, cmd и PowerShell склеивают команды, + * подставляют вывод или перенаправляют его. Ключ — символ, значение — + * как назвать его в отказе. + */ + private const META = [ + ';' => '«;»', + '&' => '«&»', + '|' => '«|»', + '`' => '«`»', + '$' => '«$»', + '<' => '«<»', + '>' => '«>»', + '(' => '«(»', + ')' => '«)»', + "\n" => 'перевода строки', + "\r" => 'возврата каретки', + "\0" => 'нулевого байта', + ]; + private readonly ?string $workdir; private readonly string $shellName; private readonly string $tmpDir; @@ -91,12 +119,17 @@ final class ShellTool implements Tool return 'Пустая команда.'; } + if ($this->allow !== [] && ($meta = $this->findMeta($command)) !== null) { + return 'Команда отклонена: при включённом allowlist нельзя использовать символ ' . $meta . '. ' + . 'Разрешена одна простая команда без ; & | ` $ < > ( ) и перевода строки.'; + } + if (!$this->isAllowed($command)) { return 'Команда не разрешена: "' . $this->firstWord($command) . '". ' . 'Разрешены: ' . implode(', ', $this->allow) . '.'; } - $timeout = Timeout::from($args, $this->timeout, $this->maxTimeout); + $timeout = Timeout::seconds($args, $this->timeout, $this->maxTimeout); try { $commandLine = $this->commandLine($command); @@ -119,7 +152,7 @@ final class ShellTool implements Tool [$outFile, $errFile] = $files; try { - $run = $this->run($commandLine, $cwd, $outFile, $errFile, $timeout->seconds); + $run = $this->run($commandLine, $cwd, $outFile, $errFile, $timeout); } catch (\RuntimeException $e) { return $e->getMessage(); } finally { @@ -129,7 +162,7 @@ final class ShellTool implements Tool @unlink($errFile); } - return $this->format($command, $stdout, $stderr, $run['timedOut'], $run['overflow'], $run['exitCode'], $timeout->seconds); + return $this->format($command, $stdout, $stderr, $run['timedOut'], $run['overflow'], $run['exitCode'], $timeout); } /** @@ -279,6 +312,20 @@ final class ShellTool implements Tool return false; } + /** + * Первый запрещённый метасимвол в команде (в читаемом виде) или null. + */ + private function findMeta(string $command): ?string + { + foreach (self::META as $char => $label) { + if (str_contains($command, (string) $char)) { + return $label; + } + } + + return null; + } + private function firstWord(string $command): string { $parts = preg_split('/\s+/', trim($command)); @@ -311,7 +358,7 @@ final class ShellTool implements Tool $lines = ['$ ' . $command]; $lines[] = match (true) { - $timedOut => 'exit: таймаут ' . Timeout::format($timeout) . ' с (процесс завершён)', + $timedOut => 'exit: таймаут ' . Number::format($timeout, 1) . ' с (процесс завершён)', $overflow => 'exit: вывод превысил лимит, процесс завершён', default => 'exit: ' . $exitCode, }; diff --git a/src/HttpRequest.php b/tools/Support/HttpRequest.php similarity index 99% rename from src/HttpRequest.php rename to tools/Support/HttpRequest.php index af9b8fc..325ed3d 100644 --- a/src/HttpRequest.php +++ b/tools/Support/HttpRequest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace AiSdk; +namespace AiSdk\Tools\Support; /** * Разобранный HTTP-запрос: метод, URL, заголовки, тело. diff --git a/tools/Support/Number.php b/tools/Support/Number.php new file mode 100644 index 0000000..a272229 --- /dev/null +++ b/tools/Support/Number.php @@ -0,0 +1,28 @@ += 1e15) { + return (string) $value; + } + + $text = rtrim(rtrim(number_format($value, $decimals, '.', ''), '0'), '.'); + + return $text === '-0' ? '0' : $text; + } +} diff --git a/tools/Support/Timeout.php b/tools/Support/Timeout.php index c3b532b..f0f9836 100644 --- a/tools/Support/Timeout.php +++ b/tools/Support/Timeout.php @@ -5,52 +5,33 @@ declare(strict_types=1); namespace AiSdk\Tools\Support; /** - * Таймаут действия, который может попросить сама модель (параметр timeout). + * Таймаут, который может попросить сама модель (аргумент timeout). * - * Значение модели применяется как есть, но в пределах жёсткого максимума - * инструмента: модель не может «повесить» процесс навсегда. Если она попросила - * больше максимума — применяется максимум, и это видно в {@see self::clamped()}. + * Значение модели применяется, но в пределах [1, max]: модель не может + * «повесить» процесс навсегда. */ final class Timeout { - private function __construct( - public readonly float $seconds, - public readonly ?float $requested, - public readonly float $max, - ) { - } - /** * @param array $arguments аргументы вызова от модели */ - public static function from(array $arguments, float $default, float $max): self + public static function seconds(array $arguments, float $default, float $max): float { - $max = max(1.0, $max); - $raw = $arguments['timeout'] ?? null; - $requested = is_numeric($raw) ? (float) $raw : null; + $requested = $arguments['timeout'] ?? null; + $seconds = is_numeric($requested) ? (float) $requested : $default; - return new self(max(1.0, min($max, $requested ?? $default)), $requested, $max); + return max(1.0, min(max(1.0, $max), $seconds)); } /** - * Модель попросила значение, которое пришлось урезать. + * Описание аргумента timeout для схемы инструмента. */ - public function clamped(): bool - { - return $this->requested !== null && abs($this->requested - $this->seconds) > 0.001; - } - public static function parameterDescription(float $default, float $max): string { return sprintf( 'Сколько секунд ждать (по умолчанию %s, максимум %s; больше — будет урезано).', - self::format($default), - self::format($max), + Number::format($default, 1), + Number::format($max, 1), ); } - - public static function format(float $seconds): string - { - return rtrim(rtrim(number_format($seconds, 1, '.', ''), '0'), '.'); - } } diff --git a/tools/Support/UrlGuard.php b/tools/Support/UrlGuard.php index f6ba829..ab5b685 100644 --- a/tools/Support/UrlGuard.php +++ b/tools/Support/UrlGuard.php @@ -7,20 +7,54 @@ namespace AiSdk\Tools\Support; /** * Защита от SSRF: пропускает только публичные http/https-адреса. * - * Проверяются схема, имя хоста и все A-записи. `localhost`, `.local`, - * `metadata`, приватные диапазоны и CGNAT запрещены. Флаг allowPrivate - * снимает проверку адреса (оставляя проверку схемы) — для внутренних API. + * Проверяются схема, имя хоста и все адреса хоста — A и AAAA. `localhost`, + * `.local`, `metadata`, приватные и служебные диапазоны (IPv4 и IPv6, включая + * CGNAT, NAT64 и 6to4 с приватным адресом внутри) запрещены. + * + * Проверенные адреса возвращаются в формате CURLOPT_RESOLVE: cURL подключится + * ровно к ним и не станет резолвить имя повторно. Без этого злоумышленник с + * коротким TTL отдал бы при проверке публичный IP, а при запросе — 127.0.0.1 + * (DNS rebinding). + * + * Ограничение: при HTTP_PROXY/HTTPS_PROXY имя резолвит прокси, CURLOPT_RESOLVE + * не действует, а «внутренняя сеть» — это сеть прокси. В такой схеме доступ + * ограничивают на самом прокси. + * + * Флаг allowPrivate снимает проверку адреса (оставляя проверку схемы) — для + * внутренних API. */ final class UrlGuard { - public function __construct(private readonly bool $allowPrivate = false) - { + /** @var \Closure(string): list */ + private readonly \Closure $resolver; + + /** + * @param (\Closure(string): list)|null $resolver имя хоста → его IP; + * по умолчанию DNS (A + AAAA). Подменяется в тестах. + */ + public function __construct( + private readonly bool $allowPrivate = false, + ?\Closure $resolver = null, + ) { + $this->resolver = $resolver ?? self::resolveDns(...); } /** * @throws \RuntimeException если адрес недопустим */ public function assertAllowed(string $url): void + { + $this->pin($url); + } + + /** + * Проверить адрес и вернуть строки для CURLOPT_RESOLVE ("host:port:ip,ip"). + * Пустой список — закреплять нечего (IP-литерал или allowPrivate). + * + * @return list + * @throws \RuntimeException если адрес недопустим + */ + public function pin(string $url): array { $parts = parse_url($url); @@ -35,52 +69,124 @@ final class UrlGuard } if ($this->allowPrivate) { - return; + return []; } $host = strtolower((string) $parts['host']); + $literal = trim($host, '[]'); - if ($host === 'localhost' || str_ends_with($host, '.local') || str_contains($host, 'metadata')) { + if ($host === 'localhost' || str_ends_with($host, '.localhost') + || str_ends_with($host, '.local') || str_contains($host, 'metadata')) { throw new \RuntimeException('запрос к локальному адресу запрещён'); } - $ips = []; - - if (filter_var($host, FILTER_VALIDATE_IP) !== false) { - $ips[] = $host; - } else { - $resolved = @gethostbynamel($host); - - if ($resolved === false || $resolved === []) { - throw new \RuntimeException('не удалось разрешить хост: ' . $host); + // IP-литерал: резолвить нечего, проверяем как есть. + if (filter_var($literal, FILTER_VALIDATE_IP) !== false) { + if (!self::isPublicIp($literal)) { + throw new \RuntimeException('запрос к приватному адресу запрещён: ' . $host); } - $ips = $resolved; + return []; } + $ips = array_values(array_unique(array_filter( + ($this->resolver)($host), + static fn (string $ip): bool => filter_var($ip, FILTER_VALIDATE_IP) !== false, + ))); + + if ($ips === []) { + throw new \RuntimeException('не удалось разрешить хост: ' . $host); + } + + // Достаточно одного приватного адреса: cURL может выбрать именно его. foreach ($ips as $ip) { - if (!$this->isPublicIp($ip)) { + if (!self::isPublicIp($ip)) { throw new \RuntimeException('запрос к приватному адресу запрещён: ' . $host); } } + + $port = (int) ($parts['port'] ?? ($scheme === 'https' ? 443 : 80)); + $addresses = array_map( + static fn (string $ip): string => str_contains($ip, ':') ? '[' . $ip . ']' : $ip, + $ips, + ); + + return [$host . ':' . $port . ':' . implode(',', $addresses)]; } - private function isPublicIp(string $ip): bool + public static function isPublicIp(string $ip): bool { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { return false; } - // 100.64.0.0/10 (CGNAT) не покрывается флагами PHP. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) { - $long = ip2long($ip); - $cgnat = ip2long('100.64.0.0'); + // 100.64.0.0/10 (CGNAT) не покрывается флагами PHP. + return !self::inV4Range($ip, '100.64.0.0', 10); + } - if ($long !== false && $cgnat !== false && ($long & 0xFFC00000) === ($cgnat & 0xFFC00000)) { - return false; - } + $bytes = inet_pton($ip); + + if ($bytes === false || strlen($bytes) !== 16) { + return false; + } + + // 2001:db8::/32 — документационный диапазон, в интернете его нет. + if (str_starts_with($bytes, "\x20\x01\x0d\xb8")) { + return false; + } + + // NAT64 (64:ff9b::/96) и 6to4 (2002::/16) несут IPv4 внутри — + // проверяем его, иначе через шлюз можно достучаться до 127.0.0.1. + $embedded = match (true) { + str_starts_with($bytes, "\x00\x64\xff\x9b" . str_repeat("\x00", 8)) => substr($bytes, 12, 4), + str_starts_with($bytes, "\x20\x02") => substr($bytes, 2, 4), + default => null, + }; + + if ($embedded !== null) { + $v4 = inet_ntop($embedded); + + return $v4 !== false && self::isPublicIp($v4); } return true; } + + private static function inV4Range(string $ip, string $network, int $bits): bool + { + $long = ip2long($ip); + $base = ip2long($network); + + if ($long === false || $base === false) { + return false; + } + + $mask = -1 << (32 - $bits) & 0xFFFFFFFF; + + return ($long & $mask) === ($base & $mask); + } + + /** + * A-записи через gethostbynamel (работает везде), AAAA — через + * dns_get_record, если доступен. + * + * @return list + */ + private static function resolveDns(string $host): array + { + $ips = @gethostbynamel($host) ?: []; + + if (function_exists('dns_get_record')) { + $records = @dns_get_record($host, DNS_AAAA); + + foreach (is_array($records) ? $records : [] as $record) { + if (isset($record['ipv6']) && is_string($record['ipv6'])) { + $ips[] = $record['ipv6']; + } + } + } + + return $ips; + } }