feat: повторы запросов, защита SSRF и shell, упрощение кода

Безопасность:
- 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).
This commit is contained in:
rsgrinko committed 2026-11-13 10:01:28 +03:00
1 parent fc777e2798
commit 835730d8d8
35 files changed
+1216 -371

No files matched your search

+2 -10
View File
@@ -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'), '.');
}
}
+2 -10
View File
@@ -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'), '.');
}
}
+79 -119
View File
@@ -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<string>, 1: list<list<string>>}
* @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<list<string>>
*/
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<list<string>> $allRows
* @param list<string> $header
* @param list<int> $requested
* @param array{index: int, value: string, contains: bool}|null $filter
* @return list<list<string>>
*/
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<string> $header
* @return list<int>|string индексы колонок или текст ошибки
* @return list<int> индексы нужных колонок (пусто в запросе — все)
* @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<string> $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<string> $row
* @param list<string> $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<string> $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<list<string>> $table
*/
-5
View File
@@ -112,11 +112,6 @@ final class FileSandbox
return $realDirectory . DIRECTORY_SEPARATOR . $name;
}
/**
* Атомарная запись: сначала во временный файл рядом, потом rename.
* Так при сбое не остаётся полузаписанный файл.
*/
/**
* Путь для показа пользователю (относительно корня, если внутри него).
*/
-6
View File
@@ -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
*/
}
+7 -11
View File
@@ -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;
}
}
+4 -42
View File
@@ -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<string>
*/
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.');
-2
View File
@@ -99,6 +99,4 @@ final class ListDirTool implements Tool
return $text;
}
}
-2
View File
@@ -129,6 +129,4 @@ final class ReadFileTool implements Tool
return 'Файл ' . $path . ', строки ' . $from . '–' . $to . ' из ' . $total . ":\n" . $text;
}
}
+3 -18
View File
@@ -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));
}
}
-4
View File
@@ -184,8 +184,4 @@ final class SearchFilesTool implements Tool
return $matches;
}
/**
* @param callable(string): void $onFile
*/
}
+51 -4
View File
@@ -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,
};
+248
View File
@@ -0,0 +1,248 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools\Support;
/**
* Разобранный HTTP-запрос: метод, URL, заголовки, тело.
*
* Собирается из аргументов инструмента и умеет то, что нужно для реальных API:
* query-параметры, JSON- или form-тело, свои заголовки, Basic/Bearer авторизация.
*/
final class HttpRequest
{
public const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
/** Заголовки, которые нельзя задавать вручную: их ставит cURL. */
private const FORBIDDEN_HEADERS = [
'host',
'content-length',
'transfer-encoding',
'connection',
'expect',
];
/**
* @param array<string, string> $headers
*/
private function __construct(
public readonly string $method,
public readonly string $url,
public readonly array $headers,
public readonly ?string $body,
) {
}
/**
* @param array<string, mixed> $query
* @param array<string, mixed> $headers
* @param array{type?: string, user?: string, pass?: string, token?: string}|null $auth
*
* @throws \InvalidArgumentException
*/
public static function build(
string $method,
string $url,
array $query = [],
mixed $body = null,
string $contentType = 'json',
array $headers = [],
?array $auth = null,
): self {
$method = strtoupper(trim($method));
if (!in_array($method, self::METHODS, true)) {
throw new \InvalidArgumentException(
'Метод ' . $method . ' не поддерживается. Доступно: ' . implode(', ', self::METHODS) . '.'
);
}
$url = self::withQuery(self::normalizeUrl($url), $query);
$normalized = [];
foreach ($headers as $name => $value) {
$name = trim((string) $name);
if ($name === '' || in_array(strtolower($name), self::FORBIDDEN_HEADERS, true)) {
continue;
}
$normalized[$name] = (string) $value;
}
[$encoded, $mime] = self::encodeBody($body, $contentType);
if ($encoded !== null && !self::hasHeader($normalized, 'content-type')) {
$normalized['Content-Type'] = $mime;
}
if (!self::hasHeader($normalized, 'accept')) {
$normalized['Accept'] = '*/*';
}
$authorization = self::authorization($auth);
if ($authorization !== null) {
// Свои креденшелы важнее заголовка Authorization из аргументов.
foreach (array_keys($normalized) as $name) {
if (strtolower($name) === 'authorization') {
unset($normalized[$name]);
}
}
$normalized['Authorization'] = $authorization;
}
return new self($method, $url, $normalized, $encoded);
}
public static function normalizeUrl(string $url): string
{
$url = trim($url);
if ($url === '') {
throw new \InvalidArgumentException('Не указан URL.');
}
if (preg_match('#^[a-z][a-z0-9+.-]*://#i', $url) === 1) {
return $url;
}
return 'https://' . ltrim($url, '/');
}
/**
* Абсолютный адрес редиректа относительно текущего URL.
*
* @throws \RuntimeException если базовый адрес некорректен
*/
public static function resolveRedirect(string $base, string $location): string
{
if (preg_match('#^https?://#i', $location) === 1) {
return $location;
}
$parts = parse_url($base);
if ($parts === false || !isset($parts['scheme'], $parts['host'])) {
throw new \RuntimeException('некорректный адрес редиректа');
}
$origin = $parts['scheme'] . '://' . $parts['host']
. (isset($parts['port']) ? ':' . $parts['port'] : '');
if (str_starts_with($location, '//')) {
return $parts['scheme'] . ':' . $location;
}
if (str_starts_with($location, '/')) {
return $origin . $location;
}
$directory = rtrim(dirname($parts['path'] ?? '/'), '/');
return $origin . $directory . '/' . $location;
}
/**
* @param array<string, mixed> $query
*/
private static function withQuery(string $url, array $query): string
{
$query = array_filter($query, static fn (mixed $value): bool => $value !== null);
if ($query === []) {
return $url;
}
$separator = str_contains($url, '?') ? '&' : '?';
return $url . $separator . http_build_query($query, '', '&', PHP_QUERY_RFC3986);
}
/**
* @return array{0: string|null, 1: string} тело и mime-тип
*/
private static function encodeBody(mixed $body, string $contentType): array
{
if ($body === null || $body === '') {
return [null, self::mime($contentType)];
}
if (is_string($body)) {
return [$body, self::mime($contentType)];
}
if (!is_array($body)) {
throw new \InvalidArgumentException('body должен быть объектом или строкой.');
}
if (strtolower($contentType) === 'form') {
return [http_build_query($body), 'application/x-www-form-urlencoded'];
}
$json = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($json === false) {
throw new \InvalidArgumentException('не удалось сериализовать body в JSON');
}
return [$json, 'application/json'];
}
private static function mime(string $contentType): string
{
return match (strtolower(trim($contentType))) {
'form' => 'application/x-www-form-urlencoded',
'text' => 'text/plain; charset=utf-8',
default => 'application/json',
};
}
/**
* @param array<string, string> $headers
*/
private static function hasHeader(array $headers, string $name): bool
{
foreach (array_keys($headers) as $key) {
if (strtolower($key) === strtolower($name)) {
return true;
}
}
return false;
}
/**
* @param array{type?: string, user?: string, pass?: string, token?: string}|null $auth
*/
private static function authorization(?array $auth): ?string
{
if ($auth === null || $auth === []) {
return null;
}
$type = strtolower((string) ($auth['type'] ?? (isset($auth['token']) ? 'bearer' : 'basic')));
if ($type === 'bearer') {
$token = trim((string) ($auth['token'] ?? ''));
if ($token === '') {
throw new \InvalidArgumentException('для Bearer нужен token.');
}
return 'Bearer ' . $token;
}
$user = (string) ($auth['user'] ?? '');
$pass = (string) ($auth['pass'] ?? '');
if ($user === '' && $pass === '') {
throw new \InvalidArgumentException('для Basic нужны user и pass.');
}
return 'Basic ' . base64_encode($user . ':' . $pass);
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools\Support;
/**
* Число для ответа модели: без хвостовых нулей и без экспоненты, пока это
* возможно.
*
* Number::format(4.0) // "4"
* Number::format(1 / 3) // "0.3333333333"
* Number::format(9 ** 30) // "4.2391158275216E+28"
*/
final class Number
{
public static function format(float $value, int $decimals = 10): string
{
// Огромные числа в int не помещаются: (int) 9 ** 30 даёт мусор.
if (abs($value) >= 1e15) {
return (string) $value;
}
$text = rtrim(rtrim(number_format($value, $decimals, '.', ''), '0'), '.');
return $text === '-0' ? '0' : $text;
}
}
+10 -29
View File
@@ -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<string, mixed> $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'), '.');
}
}
+131 -25
View File
@@ -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<string> */
private readonly \Closure $resolver;
/**
* @param (\Closure(string): list<string>)|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<string>
* @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<string>
*/
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;
}
}