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

+22 -24
View File
@@ -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<string, mixed>} $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;
}
/**
* Быстрый старт: агент с инструментами по умолчанию.
*/
}
+13 -6
View File
@@ -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'];
-248
View File
@@ -1,248 +0,0 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Разобранный 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);
}
}
+15 -3
View File
@@ -68,7 +68,9 @@ final class HttpTransport
* @param bool $follow следовать редиректам автоматически
* @param int $maxBytes предел тела ответа; больше — обрезаем и обрываем загрузку
* @param array<string, string> $headers
* @return array{status: int, body: string, location: string|null, content_type: string|null, truncated: bool}
* @param list<string> $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,
];
}
+139
View File
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Повтор запроса к модели при временных сбоях.
*
* Повторяется:
* - HTTP 408, 425, 429, 500, 502, 503, 504, 529 — перегрузка и лимиты;
* - сетевая ошибка (соединение сброшено, DNS и т.п.).
*
* Не повторяется:
* - таймаут: модель просто долго думает, повтор утроит ожидание;
* - 400/401/403/404 — ошибка в запросе или ключе, повтор не поможет.
*
* Пауза растёт экспоненциально (base, 2·base, 4·base...) со случайным
* разбросом, чтобы параллельные клиенты не били в API одновременно.
* Retry-After от сервера важнее расчёта; если сервер просит ждать дольше
* maxDelay — повтора нет, сразу возвращается ответ с ошибкой.
*
* new AiClient(..., retry: new Retry(maxRetries: 3, baseDelay: 0.5));
* new AiClient(..., retry: Retry::none());
*/
final class Retry
{
public const RETRYABLE_STATUS = [408, 425, 429, 500, 502, 503, 504, 529];
/** CURLE_OPERATION_TIMEDOUT */
private const CURL_TIMEOUT = 28;
/** @var \Closure(float): void */
private readonly \Closure $sleep;
/**
* @param int $maxRetries повторов сверх первой попытки (0 — без повторов)
* @param float $baseDelay пауза перед первым повтором, секунды
* @param float $maxDelay верхняя граница паузы, секунды
* @param (\Closure(float): void)|null $sleep как ждать; подменяется в тестах
*/
public function __construct(
public readonly int $maxRetries = 2,
public readonly float $baseDelay = 1.0,
public readonly float $maxDelay = 30.0,
?\Closure $sleep = null,
) {
$this->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()));
}
}