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

667 lines
24 KiB
PHP

<?php
namespace App\Services\Cloud;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Minimal transport for the greenfield Go host-agent protocol.
*
* This class is deliberately separate from CloudEngineClient. It does not
* read the legacy engine URL, decrypt old database values, or fall back to
* SSH. A caller must resolve one registered agent endpoint and its
* host-local request-signing key and the registered Agent identity before
* constructing the client.
*/
final class CloudAgentClient
{
private const MAX_REQUEST_BYTES = 1 * 1024 * 1024;
private const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
/** @var list<string> */
private const SUPPORTED_OPERATION_KINDS = [
'capability_probe',
'domain_read',
'domain_observe',
'domain_power',
'seed_prepare',
'domain_preflight',
'domain_create_plan',
'domain_create_validate',
];
private ClientInterface $client;
private string $endpoint;
private string $hmacKey;
private string $agentId;
private float $timeoutSeconds;
/** @var list<string> */
private array $resolvedAddresses;
/** @var array{ca_file:string,cert_file:string,key_file:string} */
private array $tls;
private string $expectedCertificateFingerprint;
/** @var \Closure(string):string|null */
private \Closure $certificateFingerprintReader;
/**
* @param array{ca_file?:string,cert_file?:string,key_file?:string} $tls
* @param string $hmacKey decoded raw 32-byte key from a host-local secret resolver
* @param list<string> $resolvedAddresses public IPs returned by an
* explicit registry resolver; when present, requests pin DNS via Guzzle's
* resolve option and never fall back to ambient resolver results.
*/
public function __construct(
string $endpoint,
string $hmacKey,
?ClientInterface $client = null,
array $tls = [],
float $timeoutSeconds = 15.0,
string $agentId = '',
array $resolvedAddresses = [],
string $expectedCertificateFingerprint = '',
?callable $certificateFingerprintReader = null,
) {
if ($timeoutSeconds < 1 || $timeoutSeconds > 900) {
throw new \InvalidArgumentException('Agent timeout is outside the supported range');
}
$this->endpoint = self::validateEndpoint($endpoint);
$this->hmacKey = $hmacKey;
if ($agentId !== trim($agentId)) {
throw new CloudError('宿主机 Agent 身份无效', 422);
}
$this->agentId = $agentId;
if ($this->agentId !== '' && preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $this->agentId) !== 1) {
throw new CloudError('宿主机 Agent 身份无效', 422);
}
// An empty key is allowed only so health() can be used while an
// agent is enrolling. Every protected method still fails closed in
// signedHeaders() until a host-local key is supplied.
if ($hmacKey !== '' && strlen($hmacKey) !== 32) {
throw new CloudError('宿主机 Agent 请求签名密钥无效', 503);
}
$this->timeoutSeconds = $timeoutSeconds;
$this->tls = self::validateTls($tls);
$this->resolvedAddresses = self::validateResolvedAddresses($resolvedAddresses);
if ($expectedCertificateFingerprint !== trim($expectedCertificateFingerprint)
|| ($expectedCertificateFingerprint !== ''
&& preg_match('/^[0-9a-f]{64}$/D', $expectedCertificateFingerprint) !== 1)) {
throw new CloudError('宿主机 Agent 客户端证书指纹无效', 503);
}
$this->expectedCertificateFingerprint = $expectedCertificateFingerprint;
$this->certificateFingerprintReader = \Closure::fromCallable(
$certificateFingerprintReader ?? [self::class, 'certificateFingerprint'],
);
$clientOptions = [
'connect_timeout' => 3,
'timeout' => $timeoutSeconds,
'http_errors' => false,
'allow_redirects' => false,
'proxy' => '',
'verify' => $this->tls['ca_file'] !== '' ? $this->tls['ca_file'] : true,
];
if ($this->tls['cert_file'] !== '' && $this->tls['key_file'] !== '') {
$clientOptions['cert'] = $this->tls['cert_file'];
$clientOptions['ssl_key'] = $this->tls['key_file'];
}
$resolve = $this->resolveOption();
if ($resolve !== []) {
$clientOptions['resolve'] = $resolve;
}
$this->client = $client ?? new Client($clientOptions);
}
/**
* The client contains raw signing material and live transport state.
* It must never cross a cache, queue, session, or other serialization
* boundary; resolve a fresh client from the Agent registry instead.
*/
public function __serialize(): array
{
throw new \LogicException('Cloud Agent clients must not be serialized');
}
/** @param array<string,mixed> $data */
public function __unserialize(array $data): void
{
throw new \LogicException('Cloud Agent clients must not be unserialized');
}
/**
* Go's auth.Verifier signs this exact newline-delimited representation.
*/
public static function canonical(
string $method,
string $path,
string $body,
string $timestamp,
string $nonce,
string $actor,
): string {
return self::canonicalDigest(
$method,
$path,
hash('sha256', $body),
$timestamp,
$nonce,
$actor,
);
}
public static function canonicalDigest(
string $method,
string $path,
string $digest,
string $timestamp,
string $nonce,
string $actor,
): string {
return strtoupper($method) . "\n" . $path . "\n" . $digest . "\n"
. $timestamp . "\n" . $nonce . "\n" . $actor;
}
public static function canonicalForAgent(
string $method,
string $path,
string $digest,
string $timestamp,
string $nonce,
string $agentId,
string $actor,
): string {
if ($agentId === '') {
return self::canonicalDigest($method, $path, $digest, $timestamp, $nonce, $actor);
}
return strtoupper($method) . "\n" . $path . "\n" . $digest . "\n"
. $timestamp . "\n" . $nonce . "\n" . $agentId . "\n" . $actor;
}
/**
* Build headers for the Go auth.Verifier. The request hash and identity
* headers are outside the signed body so the agent can bind a durable
* operation without creating a circular digest. The enrolled agent ID is
* included in the canonical HMAC envelope and sent as a separate header.
*/
public static function signedHeaders(
string $method,
string $path,
string $body,
array $actor,
string $hmacKey,
?int $now = null,
?string $nonce = null,
?string $operationId = null,
?string $idempotencyKey = null,
string $agentId = '',
): array {
// The caller passes decoded raw bytes. A base64 file value (44
// characters for a 32-byte key) is deliberately rejected so PHP and
// Go cannot silently sign the same request with different material.
if (strlen($hmacKey) !== 32) {
throw new CloudError('宿主机 Agent 请求签名密钥无效', 503);
}
$encodedActor = rtrim(strtr(base64_encode(json_encode(
$actor,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES,
)), '+/', '-_'), '=');
if ($encodedActor === '' || strlen($encodedActor) > 8192) {
throw new CloudError('宿主机 Agent 调用身份无效', 422);
}
$timestamp = (string) ($now ?? time());
$nonce ??= bin2hex(random_bytes(16));
if (preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $nonce) !== 1) {
throw new \InvalidArgumentException('Agent request nonce is invalid');
}
$headers = [
'X-Cloud-Timestamp' => $timestamp,
'X-Cloud-Nonce' => $nonce,
'X-Cloud-Actor' => $encodedActor,
'X-Cloud-Signature' => hash_hmac(
'sha256',
self::canonicalForAgent(
$method,
$path,
hash('sha256', $body),
$timestamp,
$nonce,
$agentId,
$encodedActor,
),
$hmacKey,
),
'X-Cloud-Request-Hash' => hash('sha256', $body),
'Content-Type' => 'application/json',
'Accept' => 'application/json',
];
if ($agentId !== '') {
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $agentId) !== 1) {
throw new CloudError('宿主机 Agent 身份无效', 422);
}
$headers['X-Cloud-Agent-ID'] = $agentId;
}
if ($operationId !== null) {
self::assertOperationID($operationId);
$headers['X-Cloud-Request-ID'] = $operationId;
}
if ($idempotencyKey !== null) {
self::assertIdempotencyKey($idempotencyKey);
$headers['X-Cloud-Idempotency-Key'] = $idempotencyKey;
}
return $headers;
}
/**
* Liveness is intentionally callable before the agent has request-signing
* material. It is still HTTPS-only and does not disclose response text.
*/
public function health(): array
{
return $this->request('GET', '/v1/health', [], null, null, null, false);
}
public function capabilities(array $actor): array
{
return $this->request('GET', '/v1/capabilities', $actor);
}
public function agentTest(array $actor): array
{
return $this->request('POST', '/v1/agent/test', $actor, []);
}
/**
* Submit one idempotent operation. IDs are UUIDs generated by the new
* control plane; the agent remains the final authority for its journal.
*/
public function operation(
string $operationId,
string $idempotencyKey,
string $kind,
string $target,
array $payload,
array $actor,
): array {
self::assertOperationID($operationId);
self::assertIdempotencyKey($idempotencyKey);
if (!in_array($kind, self::SUPPORTED_OPERATION_KINDS, true)) {
throw new CloudError('宿主机 Agent 操作类型无效', 422);
}
if ($target !== '' && ($target !== trim($target) || strlen($target) > 128
|| preg_match('/[\x00-\x1F\x7F]/', $target) === 1)) {
throw new CloudError('宿主机 Agent 操作目标无效', 422);
}
return $this->request(
'POST',
'/v1/operations',
$actor,
[
'operation_id' => $operationId,
'idempotency_key' => $idempotencyKey,
'kind' => $kind,
'target' => $target,
'payload' => $payload === [] ? (object) [] : $payload,
],
$operationId,
$idempotencyKey,
);
}
public function getOperation(string $operationId, array $actor): array
{
self::assertOperationID($operationId);
return $this->request(
'GET',
'/v1/operations/' . rawurlencode($operationId),
$actor,
null,
$operationId,
);
}
public function reconcile(string $operationId, array $actor): array
{
self::assertOperationID($operationId);
return $this->request(
'POST',
'/v1/operations/' . rawurlencode($operationId) . '/reconcile',
$actor,
[],
$operationId,
);
}
/**
* @param array<string,mixed> $actor
* @param array<string,mixed>|null $payload
*/
private function request(
string $method,
string $path,
array $actor = [],
?array $payload = null,
?string $operationId = null,
?string $idempotencyKey = null,
bool $sign = true,
): array {
$method = strtoupper($method);
self::assertMethod($method);
self::assertPath($path);
if (!$sign && !($method === 'GET' && $path === '/v1/health')) {
throw new CloudError('宿主机 Agent 受保护请求必须签名', 503);
}
if ($sign && ($this->tls['ca_file'] === '' || $this->tls['cert_file'] === '' || $this->tls['key_file'] === '')) {
throw new CloudError('宿主机 Agent mTLS 尚未配置', 503);
}
if ($sign && $this->agentId === '') {
throw new CloudError('宿主机 Agent 身份尚未配置', 503);
}
if ($operationId !== null) {
self::assertOperationID($operationId);
}
if ($idempotencyKey !== null) {
self::assertIdempotencyKey($idempotencyKey);
}
$body = $payload === null ? '' : json_encode(
$payload === [] ? (object) [] : $payload,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
);
if (strlen($body) > self::MAX_REQUEST_BYTES) {
throw new CloudError('宿主机 Agent 请求过大', 413);
}
$headers = $sign
? self::signedHeaders(
$method,
$path,
$body,
$actor,
$this->hmacKey,
null,
null,
$operationId,
$idempotencyKey,
$this->agentId,
)
: ['Accept' => 'application/json'];
if ($body === '') {
unset($headers['Content-Type']);
}
$this->assertCertificateFingerprint();
$requestOptions = [
'headers' => $headers,
'body' => $body,
'connect_timeout' => 3,
'timeout' => $this->timeoutSeconds,
'http_errors' => false,
'allow_redirects' => false,
'proxy' => '',
// Keep these explicit for injected clients too, so a test can
// assert that production requests carry the intended mTLS
// material without opening a real socket.
'verify' => $this->tls['ca_file'] !== '' ? $this->tls['ca_file'] : true,
...(($this->tls['cert_file'] !== '' && $this->tls['key_file'] !== '') ? [
'cert' => $this->tls['cert_file'],
'ssl_key' => $this->tls['key_file'],
] : []),
];
$resolve = $this->resolveOption();
if ($resolve !== []) {
$requestOptions['resolve'] = $resolve;
}
try {
$response = $this->client->request($method, $this->endpoint . $path, $requestOptions);
} catch (\Throwable $exception) {
// A timeout or connection reset does not prove a destructive
// operation failed. Callers must reconcile by operation ID.
throw new CloudError(
$operationId === null
? '宿主机 Agent 连接失败'
: '宿主机 Agent 响应不确定,请按操作编号核对结果',
502,
);
}
$status = $response->getStatusCode();
$decoded = json_decode(self::readResponseBody($response), true);
if (!is_array($decoded)) {
throw new CloudError('宿主机 Agent 响应格式无效', 502);
}
if ($status < 200 || $status >= 300) {
// Keep only a durable operation envelope. Never pass through the
// agent's arbitrary error text, host paths, or command output.
if ($operationId !== null
&& ($decoded['operation_id'] ?? null) === $operationId
&& is_string($decoded['status'] ?? null)
&& in_array($decoded['status'], [
'pending', 'running', 'succeeded', 'failed', 'uncertain',
], true)) {
$safe = [
'operation_id' => $operationId,
'status' => $decoded['status'],
];
if (isset($decoded['version'])
&& is_int($decoded['version'])
&& $decoded['version'] >= 1) {
$safe['version'] = $decoded['version'];
}
if (isset($decoded['error_code'])
&& is_string($decoded['error_code'])
&& preg_match('/^[a-z][a-z0-9_.-]{0,63}$/D', $decoded['error_code']) === 1) {
$safe['error_code'] = $decoded['error_code'];
}
$safe['_agent_http_status'] = $status;
return $safe;
}
$publicStatus = in_array($status, [400, 401, 403, 404, 409, 413, 422, 501], true)
? $status : 502;
throw new CloudError('宿主机 Agent 操作未成功', $publicStatus);
}
return $decoded;
}
private static function validateEndpoint(string $endpoint): string
{
if ($endpoint !== trim($endpoint)) {
throw new CloudError('宿主机 Agent 地址无效', 422);
}
$endpoint = rtrim(trim($endpoint), '/');
if ($endpoint === '' || preg_match('/[\x00-\x20\x7F\\]/', $endpoint) === 1) {
throw new CloudError('宿主机 Agent 地址无效', 422);
}
$parts = parse_url($endpoint);
if (!is_array($parts) || ($parts['scheme'] ?? '') !== 'https'
|| !is_string($parts['host'] ?? null) || trim($parts['host']) === ''
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])
|| (($parts['path'] ?? '') !== '' && ($parts['path'] ?? '') !== '/')) {
throw new CloudError('宿主机 Agent 地址必须为不带凭据的 HTTPS 地址', 422);
}
$port = $parts['port'] ?? 443;
if (!is_int($port) || $port < 1 || $port > 65535) {
throw new CloudError('宿主机 Agent 端口无效', 422);
}
return $endpoint;
}
/**
* Bound memory used while decoding an agent response, including chunked
* responses that do not provide a Content-Length header.
*/
private static function readResponseBody(ResponseInterface $response): string
{
try {
$stream = $response->getBody();
$size = $stream->getSize();
if ($size !== null && $size > self::MAX_RESPONSE_BYTES) {
throw new CloudError('宿主机 Agent 响应过大', 502);
}
$body = '';
while (!$stream->eof() && strlen($body) <= self::MAX_RESPONSE_BYTES) {
$remaining = self::MAX_RESPONSE_BYTES + 1 - strlen($body);
$chunk = $stream->read(min(65536, $remaining));
if (!is_string($chunk)) {
throw new \RuntimeException('invalid agent response stream');
}
if ($chunk === '') {
break;
}
$body .= $chunk;
}
if (strlen($body) > self::MAX_RESPONSE_BYTES) {
throw new CloudError('宿主机 Agent 响应过大', 502);
}
return $body;
} catch (CloudError $error) {
throw $error;
} catch (\Throwable $error) {
throw new CloudError('宿主机 Agent 响应格式无效', 502);
}
}
/** @param array<string,mixed> $tls */
private static function validateTls(array $tls): array
{
$result = [];
foreach (['ca_file', 'cert_file', 'key_file'] as $key) {
$value = $tls[$key] ?? '';
if (!is_string($value) || preg_match('/[\x00-\x1F\x7F]/', $value) === 1
|| ($value !== '' && ($value[0] !== '/' || $value !== trim($value)))) {
throw new CloudError('宿主机 Agent TLS 配置无效', 503);
}
$result[$key] = $value;
}
return $result;
}
private function assertCertificateFingerprint(): void
{
if ($this->expectedCertificateFingerprint === '') {
return;
}
try {
$observed = ($this->certificateFingerprintReader)($this->tls['cert_file']);
} catch (\Throwable) {
$observed = null;
}
if (!is_string($observed)
|| preg_match('/^[0-9a-f]{64}$/D', $observed) !== 1
|| !hash_equals($this->expectedCertificateFingerprint, $observed)) {
throw new CloudError('宿主机 Agent 客户端证书指纹已变化', 503);
}
}
public static function certificateFingerprint(string $path): ?string
{
if ($path === '' || $path[0] !== '/' || trim($path) !== $path
|| preg_match('/[\x00-\x1F\x7F]/', $path) === 1
|| !function_exists('openssl_x509_read')
|| !function_exists('openssl_x509_fingerprint')) {
return null;
}
if (!CloudAgentHostClientResolver::validateCredentialPath($path, false)) {
return null;
}
$stat = @lstat($path);
if (!is_array($stat)
|| (($stat['mode'] ?? 0) & 0170000) !== 0100000
|| (($stat['mode'] ?? 0) & 0022) !== 0
|| !isset($stat['size']) || (int) $stat['size'] < 1 || (int) $stat['size'] > 1024 * 1024) {
return null;
}
$contents = @file_get_contents($path);
if (!is_string($contents) || $contents === '' || strlen($contents) > 1024 * 1024) {
return null;
}
$certificate = @openssl_x509_read($contents);
if ($certificate === false) {
return null;
}
$fingerprint = @openssl_x509_fingerprint($certificate, 'sha256');
return is_string($fingerprint) ? strtolower($fingerprint) : null;
}
/** @param list<string> $addresses */
private static function validateResolvedAddresses(array $addresses): array
{
if ($addresses === []) {
return [];
}
foreach ($addresses as $address) {
if (!is_string($address)
|| filter_var($address, FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
throw new CloudError('宿主机 Agent 主机解析到不安全地址', 422);
}
}
$unique = array_values(array_unique($addresses));
sort($unique, SORT_STRING);
return $unique;
}
/** @return array<string,string> */
private function resolveOption(): array
{
if ($this->resolvedAddresses === []) {
return [];
}
$parts = parse_url($this->endpoint);
if (!is_array($parts) || !is_string($parts['host'] ?? null)) {
throw new CloudError('宿主机 Agent 地址无效', 422);
}
$host = trim($parts['host'], '[]');
// Guzzle maps one host to one fixed address. The resolver is expected
// to return a deterministic, health-checked public endpoint; choosing
// the first unique address prevents a later ambient DNS lookup while
// keeping TLS SNI/Host bound to the registered hostname.
return [$host => $this->resolvedAddresses[0]];
}
private static function assertMethod(string $method): void
{
if (preg_match('/^[A-Z]{3,10}$/D', $method) !== 1) {
throw new CloudError('宿主机 Agent 请求方法无效', 422);
}
}
private static function assertPath(string $path): void
{
if (!str_starts_with($path, '/v1/')
|| strlen($path) > 2048
|| preg_match('/[\x00-\x20\x7F\\#]/', $path) === 1
|| str_contains($path, '//')) {
throw new CloudError('宿主机 Agent 请求路径无效', 422);
}
}
private static function assertOperationID(string $value): void
{
if (preg_match(
'/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D',
$value,
) !== 1) {
throw new CloudError('宿主机 Agent operation_id 无效', 422);
}
}
private static function assertIdempotencyKey(string $value): void
{
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/D', $value) !== 1) {
throw new CloudError('宿主机 Agent idempotency_key 无效', 422);
}
}
}