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); return self::signedHeaders( $method, $requestTarget, $body, self::agentActor($actor), $secret, $now, $nonce ); } /** Sign one already-normalized actor. Never expose this to panel input. */ private static function signedHeaders( string $method, string $requestTarget, string $body, array $actor, string $secret, ?int $now = null, ?string $nonce = null ): array { $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 { return $this->send( $method, $requestTarget, self::agentActor($actor), $payload ); } /** * Send one operation-bound recovery request with no human privileges. * * This dedicated entry point is the sole PHP constructor for the signed * system_recovery capability. The ordinary request()/headers() paths * reject that key, so controller or session actor arrays cannot smuggle * the capability across the panel-to-Agent trust boundary. */ public function systemRecoveryRequest( string $method, string $requestTarget, string $operationId, ?array $payload = null ): array { $method = strtoupper($method); self::assertOperationId($operationId); self::assertRequestTarget($requestTarget); $base = '/v1/operations/' . rawurlencode($operationId); $allowed = ($method === 'GET' && $payload === null && in_array($requestTarget, [ $base . '/inspect', $base . '/fence-resolution', ], true)) || ($method === 'POST' && $payload !== null && $requestTarget === $base . '/resolve-fence'); if (!$allowed) { throw new \InvalidArgumentException( 'System recovery request is not bound to the exact operation route' ); } return $this->send( $method, $requestTarget, self::systemRecoveryActor($operationId), $payload ); } /** Transport one request whose actor has already crossed a trusted seam. */ private function send( string $method, string $requestTarget, array $actor, ?array $payload ): array { self::assertRequestTarget($requestTarget); $body = $payload === null ? '' : json_encode( $payload === [] ? (object) [] : $payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); $signed = self::signedHeaders( $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); $transferProofs = []; 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, // Preserve every attempt: a later failed connect cannot // erase a possible send made before an internal retry. 'on_stats' => static function (\GuzzleHttp\TransferStats $stats) use (&$transferProofs): void { $context = $stats->getHandlerStats(); $error = $stats->getHandlerErrorData(); if ($error instanceof \GuzzleHttp\Exception\ConnectException) { $context = $error->getHandlerContext(); } else { $context['errno'] = $error; } $transferProofs[] = !$stats->hasResponse() && self::isUnsentGatewayTransfer($context); }, ]); } catch (\GuzzleHttp\Exception\ConnectException $exception) { $notDispatched = $exception->getRequest()->getMethod() === 'POST' && (string) $exception->getRequest()->getUri() === $this->gatewayEndpoint && self::isUnsentGatewayTransfer($exception->getHandlerContext()) && !in_array(false, $transferProofs, true); throw new CloudAgentError( '无法连接本机 Agent 网关,请检查网关服务', 502, 'agent_gateway_unreachable', true, null, false, $notDispatched ); } 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 ConnectException also represents lost responses. Only libcurl's * explicit connect failure / connect-phase timeout with complete zero * HTTP-transfer counters proves this request never reached the Gateway. * Missing statistics (including the PHP stream handler) fail closed. */ private static function isUnsentGatewayTransfer(array $context): bool { if (!in_array($context['errno'] ?? null, [7, 28], true) || ($context['url'] ?? null) !== CloudAgentGatewayEndpoint::URL) { return false; } foreach (['request_size', 'size_upload', 'size_download', 'header_size', 'http_code', 'redirect_count', 'connect_time'] as $field) { $value = $context[$field] ?? null; if ((!is_int($value) && !is_float($value)) || $value != 0) { return false; } } return true; } /** 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, ]; // The embedded value is the raw immutable Journal record. Normalize // its field name to the public operation response shape so the worker // can authenticate a 409 replay/conflict exactly like a 2xx response. foreach (['action', 'resource_id'] as $identityField) { if (array_key_exists($identityField, $record)) { $operation[$identityField] = $record[$identityField]; } } if (array_key_exists('request_fingerprint', $record)) { $operation['request_fingerprint'] = $record['request_fingerprint']; } elseif (array_key_exists('fingerprint', $record)) { $operation['request_fingerprint'] = $record['fingerprint']; } 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 { if (array_key_exists('system_recovery', $actor)) { throw new \InvalidArgumentException( 'System recovery capability requires its dedicated client path' ); } $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 systemRecoveryActor(string $operationId): array { self::assertOperationId($operationId); return [ 'user_id' => 0, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false, 'system_recovery' => true, 'operation_id' => $operationId, ]; } private static function assertOperationId(string $operationId): void { if (preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $operationId) !== 1) { throw new \InvalidArgumentException('Invalid Agent operation ID'); } } 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'); } } }