feat: http_request вместо http_get — методы, тело, авторизация
- HttpRequest: сборка запроса (query, JSON/form body, заголовки, Basic/Bearer), валидация метода, отбрасывание служебных заголовков - HttpRequestTool: GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS, auth в конструкторе по хосту и аргументом, allowPrivate для внутренних API - Http::request(): произвольный метод, заголовки, тело, content_type ответа; Http::headerLines() — регрессия на формат заголовков для cURL - редиректы: следуем только для GET/HEAD, остальным отдаём Location - вместо http_get; 65 тестов; живая проверка POST+Basic на локальном сервере
This commit is contained in:
1 parent
1dea787255
commit
be82b5100b
6 files changed
+756
-239
No files matched your search
+57
-13
@@ -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<int|string, string> $headers
|
||||
* @return list<string>
|
||||
*/
|
||||
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<string, string> $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,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
<?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);
|
||||
}
|
||||
|
||||
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<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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user