diff --git a/README.md b/README.md index 4d5bf6d..4773c87 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ echo $agent->ask('Который час в Москве и сколько буд - **`Tool` + `ToolRegistry`** — инструмент = 4 метода; реестр сам отдаёт схемы модели и вызывает нужный инструмент. - **`ChatClient`** — интерфейс, чтобы подменить модель заглушкой в тестах. -- **11 готовых инструментов**: время, калькулятор, погода, файлы, CSV, HTTP, +- **12 готовых инструментов**: время, калькулятор, погода, файлы, CSV, HTTP, единицы, даты, UUID, хеши и явное завершение — см. [таблицу](#инструменты). Без Composer, без фреймворка, без БД. Только PHP и расширение `curl`. @@ -58,7 +58,8 @@ src/ Agent.php цикл: вопрос → инструменты → ответ Tool.php интерфейс инструмента ToolRegistry.php набор инструментов - Http.php маленький GET для инструментов + Http.php низкоуровневый HTTP: методы, тело, лимит размера + HttpRequest.php сборка запроса: query, body, заголовки, Basic/Bearer Env.php .env без зависимостей AiException.php ошибки tools/ @@ -70,7 +71,7 @@ tools/ ReadFileTool.php чтение файла внутри корня ListDirTool.php список каталога внутри корня CsvQueryTool.php выборка из CSV с фильтром - HttpGetTool.php GET с защитой от SSRF + HttpRequestTool.php HTTP любого метода с авторизацией ConvertUnitsTool.php температура, длина, масса, скорость DateCalcTool.php разница дат и прибавление интервала UuidTool.php UUID v4 @@ -162,7 +163,7 @@ $agent = Agent::fromEnv($tools, 'Отвечай кратко.'); | `read_file` | чтение файла внутри корня | `new ReadFileTool($sandbox)` | | `list_dir` | содержимое каталога | `new ListDirTool($sandbox)` | | `csv_query` | выборка из CSV с фильтром | `new CsvQueryTool($sandbox)` | -| `http_get` | GET по публичному URL | — | +| `http_request` | любой метод, тело, Basic/Bearer | — | | `convert_units` | температура, длина, масса, скорость | — | | `date_calc` | разница дат, «+30 days» | — | | `uuid` | UUID v4 | — | @@ -185,9 +186,49 @@ $tools = (new ToolRegistry())->add( - бинарные файлы не читаются, сообщается размер; - большие файлы — через `offset` и `limit` в строках. -`http_get` закрыт от SSRF: только `http`/`https`, только публичные адреса -(`localhost`, `10.x`, `172.16–31.x`, `192.168.x`, `169.254.x`, CGNAT запрещены), -редиректы проверяются заново на каждом шаге, размер ответа ограничен. +`http_request` — любой метод с параметрами и авторизацией: + +```php +$tools->add(new HttpRequestTool( + auth: [ // креды по хосту, модель их не видит + 'api.example.com' => ['user' => 'bot', 'pass' => '***'], + 'other.example.com' => ['type' => 'bearer', 'token' => '***'], + ], +)); +``` + +Что умеет: + +- методы `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`; +- `query` — добавляется к URL, кодируется по RFC 3986; +- `body` — объект уходит как JSON (или form при `content_type: form`), + строка — как есть; +- `headers` — свои заголовки, кроме `Host`, `Content-Length`, + `Transfer-Encoding`, `Connection` (их ставит cURL); +- `auth` аргументом — для разовых запросов; аргумент важнее карты из конструктора; +- `max_chars` — ограничение ответа. + +Защита: + +- только `http`/`https`, только публичные адреса: `localhost`, `10.x`, + `172.16–31.x`, `192.168.x`, `169.254.x`, CGNAT запрещены; +- редиректы проверяются заново на каждом шаге; для `POST`/`PUT`/`DELETE` + редирект не преследуется — возвращается `Location` и предложение повторить; +- размер ответа ограничен, запрос обрывается при превышении. + +Нужен доступ к своим внутренним API — создайте инструмент с флагом: + +```php +new HttpRequestTool(allowPrivate: true, auth: ['10.10.10.84' => ['user' => 'admin', 'pass' => '***']]); +``` + +Флаг снимает **все** проверки адреса, кроме схемы: инструмент станет ходить +куда угодно, включая `localhost`. Это осознанный компромисс для внутренних +сервисов; в публичном сценарии оставляйте `false`. + +Осторожно с кредами в конструкторе: они добавляются к **каждому** запросу +на этот хост, включая редиректы внутри него. Если это нежелательно — передавайте +`auth` аргументом на конкретный вызов. `convert_units` отвечает каноническими кодами (`5 км` → `5 km`), понимает и русские названия единиц. @@ -332,9 +373,10 @@ curl http://10.10.10.77:8080/v1/models php tests/run.php ``` -55 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента, +65 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента, настройки (tool_choice, подтверждение вызовов, история), finish, файловая -песочница, CSV, единицы, даты, uuid/хеши и защита http_get от SSRF +песочница, CSV, единицы, даты, uuid/хеши, сборка HTTP-запроса (методы, тело, +заголовки, Basic/Bearer) и защита от SSRF (успех, ошибка инструмента, лимит раундов, история). Сеть не нужна — модель подменяется `FakeClient` из `tests/run.php`. diff --git a/src/Http.php b/src/Http.php index 750d522..76cba95 100644 --- a/src/Http.php +++ b/src/Http.php @@ -7,9 +7,9 @@ namespace AiSdk; /** * Минимальный HTTP-клиент без зависимостей. * - * get() — простой GET с редиректами (используется инструментами вроде погоды). - * request() — низкоуровневый вариант: без авто-редиректов, с лимитом размера - * и заголовком Location. На нём строится http_get с защитой от SSRF. + * get() — простой GET с редиректами (инструменты вроде погоды). + * request() — низкоуровневый вызов: метод, заголовки, тело, лимит размера. + * На нём построен http_request, включая защиту от SSRF. */ final class Http { @@ -23,16 +23,44 @@ final class Http return [$response['status'], $response['body']]; } + /** + * Привести заголовки к формату cURL: список строк "Имя: значение". + * + * Принимает и карту ['X-Trace' => 'abc'], и уже готовый список строк. + * Пустой список заменяется на Accept по умолчанию. + * + * @param array $headers + * @return list + */ + public static function headerLines(array $headers): array + { + if ($headers === []) { + return ['Accept: */*']; + } + + $lines = []; + + foreach ($headers as $name => $value) { + $lines[] = is_int($name) ? (string) $value : $name . ': ' . $value; + } + + return $lines; + } + /** * @param bool $follow следовать редиректам автоматически * @param int $maxBytes предел тела ответа; больше — обрезаем и обрываем загрузку - * @return array{status: int, body: string, location: string|null, truncated: bool} + * @param array $headers + * @return array{status: int, body: string, location: string|null, content_type: string|null, truncated: bool} */ public static function request( string $url, float $timeout = 10.0, bool $follow = false, int $maxBytes = 262144, + string $method = 'GET', + array $headers = [], + ?string $body = null, ): array { $ch = curl_init($url); @@ -40,15 +68,18 @@ final class Http throw new AiException('не удалось создать cURL-дескриптор'); } - $body = ''; + $body = $body ?? ''; + $response = ''; $truncated = false; $location = null; + $contentType = null; $limit = max(1024, $maxBytes); $verify = Env::bool('AI_VERIFY_SSL', true); $options = [ CURLOPT_RETURNTRANSFER => false, + CURLOPT_CUSTOMREQUEST => strtoupper($method), CURLOPT_TIMEOUT_MS => (int) round($timeout * 1000), CURLOPT_CONNECTTIMEOUT_MS => 5000, CURLOPT_FOLLOWLOCATION => $follow, @@ -56,30 +87,42 @@ final class Http CURLOPT_SSL_VERIFYPEER => $verify, CURLOPT_SSL_VERIFYHOST => $verify ? 2 : 0, CURLOPT_USERAGENT => 'ai-sdk/1.0 (+https://example.local)', - CURLOPT_HTTPHEADER => ['Accept: */*'], - CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$body, &$truncated, $limit): int { - $room = $limit - strlen($body); + CURLOPT_HTTPHEADER => self::headerLines($headers), + CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$response, &$truncated, $limit): int { + $room = $limit - strlen($response); if (strlen($chunk) > $room) { - $body .= substr($chunk, 0, $room); + $response .= substr($chunk, 0, $room); $truncated = true; return 0; // прерываем загрузку } - $body .= $chunk; + $response .= $chunk; return strlen($chunk); }, - CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$location): int { - if (stripos($line, 'location:') === 0) { + CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$location, &$contentType): 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)); } return strlen($line); }, ]; + if ($body !== '') { + $options[CURLOPT_POSTFIELDS] = $body; + } + + if (strtoupper($method) === 'HEAD') { + $options[CURLOPT_NOBODY] = true; + } + $caInfo = Env::get('AI_CAINFO', '') ?? ''; if ($caInfo !== '') { @@ -101,8 +144,9 @@ final class Http return [ 'status' => $status, - 'body' => $body, + 'body' => $response, 'location' => $location, + 'content_type' => $contentType, 'truncated' => $truncated, ]; } diff --git a/src/HttpRequest.php b/src/HttpRequest.php new file mode 100644 index 0000000..5392d50 --- /dev/null +++ b/src/HttpRequest.php @@ -0,0 +1,214 @@ + $headers + */ + private function __construct( + public readonly string $method, + public readonly string $url, + public readonly array $headers, + public readonly ?string $body, + ) { + } + + /** + * @param array $query + * @param array $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); + } + + private 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, '/'); + } + + /** + * @param array $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 $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); + } +} diff --git a/tests/run.php b/tests/run.php index 1553249..18a6f43 100644 --- a/tests/run.php +++ b/tests/run.php @@ -17,6 +17,8 @@ require dirname(__DIR__) . '/bootstrap.php'; use AiSdk\Agent; use AiSdk\ChatClient; use AiSdk\ChatResult; +use AiSdk\Http; +use AiSdk\HttpRequest; use AiSdk\Tool; use AiSdk\ToolRegistry; use AiSdk\Tools\CalculatorTool; @@ -26,7 +28,7 @@ use AiSdk\Tools\DateCalcTool; use AiSdk\Tools\FileSandbox; use AiSdk\Tools\FinishTool; use AiSdk\Tools\HashTool; -use AiSdk\Tools\HttpGetTool; +use AiSdk\Tools\HttpRequestTool; use AiSdk\Tools\ListDirTool; use AiSdk\Tools\ReadFileTool; use AiSdk\Tools\TimeTool; @@ -79,6 +81,17 @@ function assertContains(string $needle, string $haystack, string $message = ''): } } +function assertThrows(callable $fn, string $message = ''): void +{ + try { + $fn(); + } catch (Throwable) { + return; + } + + throw new RuntimeException($message !== '' ? $message : 'ожидалось исключение'); +} + /** * Модель-заглушка: отдаёт ответы по очереди и запоминает все запросы. */ @@ -906,23 +919,112 @@ test('hash_text: известные значения', function (): void { }); // --------------------------------------------------------------------------- -// http_get: защита от SSRF (без сети) +// http_request: сборка запроса (без сети) // --------------------------------------------------------------------------- -test('http_get: localhost запрещён', function (): void { - assertContains('локальному адресу', (new HttpGetTool())->handle(['url' => 'http://localhost/x'])); +test('http_request: query добавляется к URL', function (): void { + $request = HttpRequest::build('get', 'https://example.com/search', ['q' => 'кот', 'page' => 2]); + + assertSame('GET', $request->method); + assertContains('q=%D0%BA%D0%BE%D1%82', $request->url); + assertContains('page=2', $request->url); }); -test('http_get: приватные адреса запрещены', function (): void { - $tool = new HttpGetTool(); +test('http_request: JSON-тело и Content-Type', function (): void { + $request = HttpRequest::build('POST', 'https://example.com/orders', body: ['sku' => 'A-1']); + + assertSame('{"sku":"A-1"}', $request->body); + assertSame('application/json', $request->headers['Content-Type']); + assertSame('POST', $request->method); +}); + +test('http_request: form-тело', function (): void { + $request = HttpRequest::build( + 'POST', + 'https://example.com/login', + body: ['u' => 'a', 'p' => 'b'], + contentType: 'form', + ); + + assertSame('u=a&p=b', $request->body); + assertSame('application/x-www-form-urlencoded', $request->headers['Content-Type']); +}); + +test('http_request: Basic-авторизация', function (): void { + $request = HttpRequest::build( + 'GET', + 'https://example.com/me', + auth: ['user' => 'bot', 'pass' => 'secret'], + ); + + assertSame('Basic ' . base64_encode('bot:secret'), $request->headers['Authorization']); +}); + +test('http_request: Bearer-авторизация', function (): void { + $request = HttpRequest::build( + 'GET', + 'https://example.com/me', + auth: ['type' => 'bearer', 'token' => 'abc'], + ); + + assertSame('Bearer abc', $request->headers['Authorization']); +}); + +test('http_request: запрещённые заголовки отбрасываются', function (): void { + $request = HttpRequest::build( + 'GET', + 'https://example.com', + headers: ['Host' => 'evil', 'X-Ok' => '1'], + ); + + assertTrue(!isset($request->headers['Host']), 'Host должен отбрасываться'); + assertSame('1', $request->headers['X-Ok']); +}); + +test('http_request: неизвестный метод отвергается', function (): void { + assertThrows(static fn () => HttpRequest::build('TRACE', 'https://example.com')); +}); + +test('http_request: без схемы подставляется https', function (): void { + assertSame('https://example.com/x', HttpRequest::build('GET', 'example.com/x')->url); +}); + +test('http: заголовки превращаются в строки cURL', function (): void { + // Регрессия: ассоциативный массив, отданный в cURL напрямую, + // молча терял и Content-Type, и Authorization. + assertSame(['X-Ok: 1'], Http::headerLines(['X-Ok' => '1'])); + assertSame(['Accept: */*'], Http::headerLines([])); + assertSame(['Accept: */*'], Http::headerLines(['Accept: */*'])); +}); + +// --------------------------------------------------------------------------- +// http_request: защита от SSRF (без сети) +// --------------------------------------------------------------------------- + +test('http_request: localhost запрещён', function (): void { + assertContains('локальному адресу', (new HttpRequestTool())->handle(['url' => 'http://localhost/x'])); +}); + +test('http_request: приватные адреса запрещены', function (): void { + $tool = new HttpRequestTool(); assertContains('приватному адресу', $tool->handle(['url' => 'http://127.0.0.1/x'])); assertContains('приватному адресу', $tool->handle(['url' => 'http://10.0.0.5/x'])); assertContains('приватному адресу', $tool->handle(['url' => 'http://192.168.1.10/x'])); }); -test('http_get: только http и https', function (): void { - assertContains('только http и https', (new HttpGetTool())->handle(['url' => 'ftp://example.com/x'])); +test('http_request: только http и https', function (): void { + assertContains('только http и https', (new HttpRequestTool())->handle(['url' => 'ftp://example.com/x'])); +}); + +test('http_request: allowPrivate снимает блокировку внутренней сети', function (): void { + // Порт закрыт: проверяем именно то, что SSRF-отказ больше не выдаётся. + $result = (new HttpRequestTool(allowPrivate: true))->handle(['url' => 'http://127.0.0.1:9/x']); + + assertTrue( + !str_contains($result, 'приватному адресу'), + 'с allowPrivate адрес не должен блокироваться: ' . $result + ); }); // --------------------------------------------------------------------------- diff --git a/tools/HttpGetTool.php b/tools/HttpGetTool.php deleted file mode 100644 index eb3938d..0000000 --- a/tools/HttpGetTool.php +++ /dev/null @@ -1,209 +0,0 @@ - 'object', - 'properties' => [ - 'url' => [ - 'type' => 'string', - 'description' => 'Полный адрес, например https://api.example.com/status.', - ], - 'max_chars' => [ - 'type' => 'integer', - 'description' => 'Сколько символов вернуть, по умолчанию ' . $this->defaultChars . ', максимум 20000.', - ], - ], - 'required' => ['url'], - 'additionalProperties' => false, - ]; - } - - public function handle(array $args): string - { - $url = trim((string) ($args['url'] ?? '')); - $maxChars = (int) ($args['max_chars'] ?? $this->defaultChars); - $maxChars = max(200, min($maxChars, 20000)); - - if ($url === '') { - return 'Не указан URL.'; - } - - try { - $current = $this->normalize($url); - $response = null; - - for ($hop = 0; $hop <= self::MAX_REDIRECTS; $hop++) { - $this->assertPublic($current); - $response = Http::request($current, self::TIMEOUT, false, self::MAX_BYTES); - - $isRedirect = $response['status'] >= 300 && $response['status'] < 400; - - if (!$isRedirect || $response['location'] === null) { - break; - } - - $current = $this->normalize($this->absolute($current, $response['location'])); - } - } catch (\Throwable $e) { - return 'Ошибка: ' . $e->getMessage(); - } - - if ($response === null) { - return 'Не удалось получить ответ.'; - } - - if ($response['status'] >= 400) { - return 'HTTP ' . $response['status'] . ' для ' . $current; - } - - $text = trim($response['body']); - - if ($text === '') { - return 'Пустой ответ (HTTP ' . $response['status'] . ') для ' . $current . '.'; - } - - $truncated = $response['truncated'] || mb_strlen($text) > $maxChars; - $text = mb_substr($text, 0, $maxChars); - - return 'HTTP ' . $response['status'] . ', ' . $current - . ($truncated ? ' (обрезано)' : '') - . ":\n" . $text; - } - - private function normalize(string $url): string - { - $url = trim($url); - - // Схему не подменяем: пусть assertPublic сам скажет, что ftp не годится. - if (preg_match('#^[a-z][a-z0-9+.-]*://#i', $url) === 1) { - return $url; - } - - return 'https://' . ltrim($url, '/'); - } - - private function absolute(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; - } - - $dir = rtrim(dirname($parts['path'] ?? '/'), '/'); - - return $origin . $dir . '/' . $location; - } - - private function assertPublic(string $url): void - { - $parts = parse_url($url); - - if ($parts === false || !isset($parts['scheme'], $parts['host'])) { - throw new \RuntimeException('некорректный URL'); - } - - $scheme = strtolower((string) $parts['scheme']); - - if (!in_array($scheme, ['http', 'https'], true)) { - throw new \RuntimeException('разрешены только http и https'); - } - - $host = strtolower((string) $parts['host']); - - if ($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); - } - - $ips = $resolved; - } - - foreach ($ips as $ip) { - if (!$this->isPublicIp($ip)) { - throw new \RuntimeException('запрос к приватному адресу запрещён: ' . $host); - } - } - } - - private 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'); - - if ($long !== false && $cgnat !== false && ($long & 0xFFC00000) === ($cgnat & 0xFFC00000)) { - return false; - } - } - - return true; - } -} diff --git a/tools/HttpRequestTool.php b/tools/HttpRequestTool.php new file mode 100644 index 0000000..0d7aeec --- /dev/null +++ b/tools/HttpRequestTool.php @@ -0,0 +1,324 @@ +> креды по хосту (в нижнем регистре) */ + private readonly array $auth; + + /** + * @param array> $auth креды по хосту: + * ['api.example.com' => ['user' => 'bot', 'pass' => '***']] + * или ['api.example.com' => ['type' => 'bearer', 'token' => '***']] + */ + public function __construct( + array $auth = [], + private readonly bool $allowPrivate = false, + private readonly int $defaultChars = 4000, + ) { + $normalized = []; + + foreach ($auth as $host => $credentials) { + $normalized[strtolower((string) $host)] = $credentials; + } + + $this->auth = $normalized; + } + + public function name(): string + { + return 'http_request'; + } + + public function description(): string + { + return 'Выполнить HTTP-запрос: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS. ' + . 'query добавляется к URL, body-объект уходит как JSON (или form при content_type), ' + . 'auth — Basic (user/pass) или Bearer (token). ' + . 'По умолчанию только публичные адреса.'; + } + + public function parameters(): array + { + return [ + 'type' => 'object', + 'properties' => [ + 'url' => ['type' => 'string', 'description' => 'Полный адрес, например https://api.example.com/orders.'], + 'method' => [ + 'type' => 'string', + 'enum' => HttpRequest::METHODS, + 'description' => 'HTTP-метод, по умолчанию GET.', + ], + 'query' => [ + 'type' => 'object', + 'description' => 'Параметры строки запроса, например {"page": 2}.', + ], + 'body' => [ + 'type' => ['object', 'string'], + 'description' => 'Тело запроса: объект уйдёт как JSON или form, строка — как есть.', + ], + 'content_type' => [ + 'type' => 'string', + 'enum' => ['json', 'form', 'text'], + 'description' => 'Как кодировать body при отправке. По умолчанию json.', + ], + 'headers' => [ + 'type' => 'object', + 'description' => 'Дополнительные заголовки, например {"X-Trace": "abc"}.', + ], + 'auth' => [ + 'type' => 'object', + 'description' => 'Basic: {"user": "...", "pass": "..."} или Bearer: {"type": "bearer", "token": "..."}.', + ], + 'max_chars' => [ + 'type' => 'integer', + 'description' => 'Сколько символов ответа вернуть, по умолчанию ' . $this->defaultChars . '.', + ], + ], + 'required' => ['url'], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $rawUrl = trim((string) ($args['url'] ?? '')); + + if ($rawUrl === '') { + return 'Не указан URL.'; + } + + $maxChars = (int) ($args['max_chars'] ?? $this->defaultChars); + $maxChars = max(200, min($maxChars, 20000)); + + $body = $args['body'] ?? null; + + if (is_string($body) && strlen($body) > self::MAX_BODY) { + return 'Тело запроса слишком большое (максимум ' . self::MAX_BODY . ' байт).'; + } + + try { + $request = HttpRequest::build( + method: (string) ($args['method'] ?? 'GET'), + url: $rawUrl, + query: is_array($args['query'] ?? null) ? $args['query'] : [], + body: $body, + contentType: (string) ($args['content_type'] ?? 'json'), + headers: is_array($args['headers'] ?? null) ? $args['headers'] : [], + auth: $this->resolveAuth($rawUrl, $args['auth'] ?? null), + ); + } catch (\InvalidArgumentException $e) { + return $e->getMessage(); + } + + if (strlen((string) $request->body) > self::MAX_BODY) { + return 'Тело запроса слишком большое (максимум ' . self::MAX_BODY . ' байт).'; + } + + try { + $url = $request->url; + $response = null; + + for ($hop = 0; $hop <= self::MAX_REDIRECTS; $hop++) { + $this->assertAllowed($url); + + $response = Http::request( + $url, + self::TIMEOUT, + false, + self::MAX_BYTES, + $request->method, + $request->headers, + $request->body, + ); + + $isRedirect = in_array($response['status'], [301, 302, 303, 307, 308], true); + + // Тело POST/PUT/DELETE при редиректе терять нельзя — отдаём как есть. + if (!$isRedirect || $response['location'] === null) { + break; + } + + if (!in_array($request->method, ['GET', 'HEAD'], true)) { + return 'Редирект ' . $response['status'] . ' на ' . $response['location'] + . '. Повтори запрос по этому адресу, если он нужен.'; + } + + $url = $this->normalize($this->absolute($url, $response['location'])); + } + } catch (\Throwable $e) { + return 'Ошибка: ' . $e->getMessage(); + } + + if ($response === null) { + return 'Не удалось получить ответ.'; + } + + return $this->format($request->method, $url, $response, $maxChars); + } + + /** + * @param array{status: int, body: string, content_type: string|null, truncated: bool} $response + */ + private function format(string $method, string $url, array $response, int $maxChars): string + { + $head = 'HTTP ' . $method . ' ' . $response['status'] . ' — ' . $url; + + if ($response['content_type'] !== null) { + $head .= ' [' . $response['content_type'] . ']'; + } + + $text = trim($response['body']); + + if ($text === '') { + return $head . ' — пустой ответ.'; + } + + $truncated = $response['truncated'] || mb_strlen($text) > $maxChars; + $text = mb_substr($text, 0, $maxChars); + + return $head . ($truncated ? ' (обрезано)' : '') . ":\n" . $text; + } + + /** + * Креды: аргумент инструмента важнее карты из конструктора. + * + * @return array|null + */ + private function resolveAuth(string $url, mixed $argAuth): ?array + { + if (is_array($argAuth) && $argAuth !== []) { + return array_map(static fn (mixed $value): string => (string) $value, $argAuth); + } + + $host = strtolower((string) (parse_url($url, PHP_URL_HOST) ?? '')); + + return $this->auth[$host] ?? null; + } + + private function assertAllowed(string $url): void + { + $parts = parse_url($url); + + if ($parts === false || !isset($parts['scheme'], $parts['host'])) { + throw new \RuntimeException('некорректный URL'); + } + + $scheme = strtolower((string) $parts['scheme']); + + if (!in_array($scheme, ['http', 'https'], true)) { + throw new \RuntimeException('разрешены только http и https'); + } + + if ($this->allowPrivate) { + return; + } + + $host = strtolower((string) $parts['host']); + + if ($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); + } + + $ips = $resolved; + } + + foreach ($ips as $ip) { + if (!$this->isPublicIp($ip)) { + throw new \RuntimeException('запрос к приватному адресу запрещён: ' . $host); + } + } + } + + private 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'); + + if ($long !== false && $cgnat !== false && ($long & 0xFFC00000) === ($cgnat & 0xFFC00000)) { + return false; + } + } + + return true; + } + + private function normalize(string $url): string + { + $url = trim($url); + + if (preg_match('#^[a-z][a-z0-9+.-]*://#i', $url) === 1) { + return $url; + } + + return 'https://' . ltrim($url, '/'); + } + + private function absolute(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; + } + + $dir = rtrim(dirname($parts['path'] ?? '/'), '/'); + + return $origin . $dir . '/' . $location; + } +}