You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudAgentClient.php

415 lines
16 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Services\Config;
use GuzzleHttp\Client;
/** Signed PHP-to-Agent client transported by the local outbound-connection gateway. */
final class CloudAgentClient
{
private Client $client;
private string $gatewayEndpoint;
private string $gatewaySecret;
public function __construct(
private readonly string $agentId,
private readonly string $apiSecret,
?Client $client = null,
private readonly float $timeoutSeconds = 20.0,
?string $gatewayEndpoint = null,
?string $gatewaySecret = null
) {
if (preg_match('/^[1-9][0-9]{0,18}$/D', $agentId) !== 1
|| strlen($apiSecret) < 32 || strlen($apiSecret) > 256
|| preg_match('/^[\x21-\x7e]+$/D', $apiSecret) !== 1
|| $timeoutSeconds < 1 || $timeoutSeconds > 900) {
throw new \InvalidArgumentException('Invalid Agent client configuration');
}
$gatewayEndpoint ??= (string) Config::get(
'cloud_agent_gateway_url',
CloudAgentGatewayEndpoint::URL
);
$gatewaySecret ??= (string) Config::get('cloud_agent_gateway_secret', '');
$this->gatewayEndpoint = CloudAgentGatewayEndpoint::normalize(
$gatewayEndpoint
);
if (strlen($gatewaySecret) < 32
|| str_contains($gatewaySecret, "\0")
|| str_contains($gatewaySecret, "\r")
|| str_contains($gatewaySecret, "\n")) {
throw new \InvalidArgumentException('Invalid Agent gateway secret');
}
$this->gatewaySecret = $gatewaySecret;
$this->client = $client ?? new Client([
'connect_timeout' => 3,
'timeout' => $timeoutSeconds,
'http_errors' => false,
'allow_redirects' => false,
]);
}
public static function canonical(
string $method,
string $requestTarget,
string $bodyDigest,
string $timestamp,
string $nonce,
string $actor
): string {
return strtoupper($method) . "\n" . $requestTarget . "\n"
. strtolower($bodyDigest) . "\n" . $timestamp . "\n"
. $nonce . "\n" . $actor;
}
public static function headers(
string $method,
string $requestTarget,
string $body,
array $actor,
string $secret,
?int $now = null,
?string $nonce = null
): array {
self::assertRequestTarget($requestTarget);
$actor = self::agentActor($actor);
$encodedActor = rtrim(strtr(base64_encode(json_encode(
$actor,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
)), '+/', '-_'), '=');
$timestamp = (string) ($now ?? time());
$nonce ??= bin2hex(random_bytes(16));
if (preg_match('/^[a-f0-9]{32}$/D', $nonce) !== 1) {
throw new \InvalidArgumentException('Agent nonce must be 16 random bytes in hex');
}
$digest = hash('sha256', $body);
$signature = hash_hmac('sha256', self::canonical(
$method,
$requestTarget,
$digest,
$timestamp,
$nonce,
$encodedActor
), $secret);
return [
'X-Virt-Timestamp' => $timestamp,
'X-Virt-Nonce' => $nonce,
'X-Virt-Content-SHA256' => $digest,
'X-Virt-Actor' => $encodedActor,
'X-Virt-Signature' => $signature,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
}
/** Sign a local PHP-to-gateway request without exposing a panel user actor. */
public static function gatewayHeaders(
string $method,
string $requestTarget,
string $body,
string $secret,
?int $now = null,
?string $nonce = null
): array {
$actor = rtrim(strtr(base64_encode(json_encode(
['service' => 'php-panel'],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
)), '+/', '-_'), '=');
$timestamp = (string) ($now ?? time());
$nonce ??= bin2hex(random_bytes(16));
if (preg_match('/^[a-f0-9]{32}$/D', $nonce) !== 1
|| strlen($secret) < 32) {
throw new \InvalidArgumentException('Invalid gateway signing parameters');
}
$digest = hash('sha256', $body);
return [
'X-Virt-Timestamp' => $timestamp,
'X-Virt-Nonce' => $nonce,
'X-Virt-Content-SHA256' => $digest,
'X-Virt-Actor' => $actor,
'X-Virt-Signature' => hash_hmac('sha256', self::canonical(
$method,
$requestTarget,
$digest,
$timestamp,
$nonce,
$actor
), $secret),
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
}
public function request(
string $method,
string $requestTarget,
array $actor,
?array $payload = null
): array {
self::assertRequestTarget($requestTarget);
$body = $payload === null ? '' : json_encode(
$payload === [] ? (object) [] : $payload,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
$signed = self::headers(
$method,
$requestTarget,
$body,
$actor,
$this->apiSecret
);
$transportId = bin2hex(random_bytes(16));
$envelope = json_encode([
'agent_id' => $this->agentId,
'type' => 'request',
'id' => $transportId,
'method' => strtoupper($method),
'request_target' => $requestTarget,
'body' => $body,
'headers' => [
'X-Virt-Timestamp' => $signed['X-Virt-Timestamp'],
'X-Virt-Nonce' => $signed['X-Virt-Nonce'],
'X-Virt-Content-SHA256' => $signed['X-Virt-Content-SHA256'],
'X-Virt-Actor' => $signed['X-Virt-Actor'],
'X-Virt-Signature' => $signed['X-Virt-Signature'],
],
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
try {
$response = $this->client->request('POST',
$this->gatewayEndpoint, [
'headers' => self::gatewayHeaders(
'POST',
CloudAgentGatewayEndpoint::PATH,
$envelope,
$this->gatewaySecret
),
'body' => $envelope,
'allow_redirects' => false,
'http_errors' => false,
'proxy' => '',
'timeout' => $this->timeoutSeconds,
]);
} catch (\GuzzleHttp\Exception\ConnectException $exception) {
throw new CloudAgentError(
'无法连接本机 Agent 网关,请检查网关服务',
502,
'agent_gateway_unreachable',
true
);
} catch (\Throwable $exception) {
throw new CloudAgentError(
'Agent 网关请求失败;本次任务将结束且不会自动重发',
502,
'agent_transport_error',
true
);
}
$status = $response->getStatusCode();
$maximum = 2 * 1024 * 1024;
$stream = $response->getBody();
$reported = $stream->getSize();
if ($reported !== null && $reported > $maximum) {
throw new CloudAgentError('宿主机 Agent 响应过大', 502,
'agent_response_too_large', true, $status);
}
$raw = '';
while (!$stream->eof()) {
$remaining = $maximum + 1 - strlen($raw);
if ($remaining <= 0) {
throw new CloudAgentError('宿主机 Agent 响应过大', 502,
'agent_response_too_large', true, $status);
}
$chunk = $stream->read(min(65536, $remaining));
if ($chunk === '' && !$stream->eof()) {
throw new CloudAgentError('宿主机 Agent 返回了无效响应',
502, 'agent_invalid_response', true, $status);
}
$raw .= $chunk;
}
if (strlen($raw) > $maximum) {
throw new CloudAgentError('宿主机 Agent 响应过大', 502,
'agent_response_too_large', true, $status);
}
$result = json_decode($raw, true);
if (!is_array($result) || ($result !== [] && array_is_list($result))) {
throw new CloudAgentError('宿主机 Agent 返回了无效响应', 502,
'agent_invalid_response', true, $status);
}
if ($status < 200 || $status >= 300) {
$operation = self::operationResponse($result);
if ($operation !== null) {
return $operation;
}
$operation = self::operationFromErrorEnvelope($result);
if ($operation !== null) {
return $operation;
}
throw self::responseError($status, $result);
}
return $result;
}
/** A journal-backed failure is data for the durable worker, not transport failure. */
private static function operationResponse(array $payload): ?array
{
$operationId = $payload['operation_id'] ?? null;
$status = $payload['status'] ?? null;
if (!is_string($operationId)
|| preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $operationId) !== 1
|| !is_string($status)
|| !in_array($status,
['reserved', 'dispatching', 'succeeded', 'failed'],
true)
|| !is_bool($payload['replayed'] ?? null)
|| !is_bool($payload['retryable'] ?? null)) {
return null;
}
$causeCode = self::operationCauseCode($payload['cause_code'] ?? null);
if ($causeCode === null) {
unset($payload['cause_code']);
} else {
$payload['cause_code'] = $causeCode;
}
return $payload;
}
/** Convert a 409 error envelope carrying its durable record to worker form. */
private static function operationFromErrorEnvelope(array $payload): ?array
{
$error = $payload['error'] ?? null;
$record = is_array($error) ? ($error['operation'] ?? null) : null;
if (!is_array($record) || array_is_list($record)) {
return null;
}
$operationId = $record['operation_id'] ?? null;
$status = $record['status'] ?? null;
if (!is_string($operationId)
|| preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $operationId) !== 1
|| !is_string($status)
|| !in_array($status,
['reserved', 'dispatching', 'succeeded', 'failed'],
true)) {
return null;
}
$operation = [
'operation_id' => $operationId,
'status' => $status,
'replayed' => false,
'retryable' => ($error['retryable'] ?? false) === true,
];
if (array_key_exists('result', $record)) {
$operation['result'] = $record['result'];
}
$causeCode = self::operationCauseCode($record['cause_code'] ?? null);
if ($causeCode === null && !array_key_exists('cause_code', $record)) {
// Admission failures such as resource_operation_blocked are
// represented by the authenticated outer envelope while the
// embedded journal record retains its own terminal error. Keep
// both facts instead of replacing the record error with the
// envelope code.
$causeCode = self::operationCauseCode($error['code'] ?? null);
}
if ($causeCode !== null) {
$operation['cause_code'] = $causeCode;
}
if (is_array($record['error'] ?? null)) {
$operation['error'] = $record['error'];
} elseif (is_string($error['code'] ?? null)) {
$operation['error'] = ['code' => $error['code']];
}
return $operation;
}
private static function operationCauseCode(mixed $value): ?string
{
return is_string($value)
&& strlen($value) <= 64
&& preg_match('/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/D', $value) === 1
? $value : null;
}
private static function responseError(int $status, array $payload): CloudAgentError
{
$error = is_array($payload['error'] ?? null) ? $payload['error'] : [];
$code = is_string($error['code'] ?? null)
&& preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $error['code']) === 1
? $error['code'] : 'agent_http_error';
[$message, $panelStatus, $retryable] = match ($status) {
400, 422 => ['Agent 拒绝了请求参数', 422, false],
401 => ['Agent API 身份验证失败,请重新核对密钥', 502, false],
403 => $code === 'gateway_forbidden'
? ['Agent 网关身份验证失败,请重新核对网关密钥', 502, false]
: ['Agent 拒绝了未授权的操作请求', 403, false],
404 => ['Agent 上的目标资源不存在', 404, false],
409 => ['Agent 拒绝冲突或重复的操作请求', 409, false],
501 => ['当前 Agent 不支持此项功能', 501, false],
503 => ['宿主机 Agent 或虚拟化后端暂不可用', 503, true],
default => ['宿主机 Agent 操作未成功', 502, $status >= 500],
};
$strictNotDispatched = count($payload) === 1
&& array_key_exists('error', $payload)
&& count($error) === 4
&& array_diff_key($error, array_flip([
'code', 'message', 'retryable', 'dispatch_state',
])) === []
&& is_string($error['message'] ?? null)
&& ($error['dispatch_state'] ?? null) === 'not_dispatched';
// Only an exact explicit dispatch_state contract may authorize a
// terminal safe-to-resubmit failure or refund. In particular,
// replayed_request and gateway_replayed_request are ambiguous because
// the first request carrying that nonce may already have dispatched.
$safeValidationFailure = $strictNotDispatched
&& ($error['retryable'] ?? null) === false
&& !in_array($code,
['replayed_request', 'gateway_replayed_request'], true)
&& (
in_array($status, [400, 413, 422, 501], true)
|| ($status === 401 && $code === 'unauthorized')
|| $status === 403
|| ($status === 404 && in_array($code,
['not_found', 'gateway_route_not_found'], true))
|| ($status === 405 && $code === 'method_not_allowed')
);
$safePreDispatchFailure = $strictNotDispatched
&& ($error['retryable'] ?? null) === false
&& $status >= 500 && $status <= 504
&& !in_array($code,
['replayed_request', 'gateway_replayed_request'], true);
return new CloudAgentError($message, $panelStatus, $code,
$retryable, $status, $safeValidationFailure,
$safePreDispatchFailure);
}
private static function agentActor(array $actor): array
{
$result = [
'user_id' => max(0, (int) ($actor['user_id'] ?? 0)),
'is_admin' => ($actor['is_admin'] ?? false) === true,
'is_super_admin' => ($actor['is_super_admin'] ?? false) === true,
'can_manage' => ($actor['can_manage'] ?? false) === true,
];
if (isset($actor['operation_id'])) {
$operationId = $actor['operation_id'];
if (!is_string($operationId)
|| preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $operationId) !== 1) {
throw new \InvalidArgumentException('Invalid Agent operation ID');
}
$result['operation_id'] = $operationId;
}
return $result;
}
private static function assertRequestTarget(string $requestTarget): void
{
if (($requestTarget !== '/v1' && !str_starts_with($requestTarget, '/v1/'))
|| strlen($requestTarget) > 2048
|| preg_match('/[\x00-\x20\x7f]/', $requestTarget) === 1
|| str_contains($requestTarget, '\\')
|| str_contains($requestTarget, '#')
|| str_contains(strtolower($requestTarget), '%0a')
|| str_contains(strtolower($requestTarget), '%0d')) {
throw new \InvalidArgumentException('Invalid Agent request target');
}
}
}