diff --git a/web/app/Services/Cloud/CloudAgentVmGateway.php b/web/app/Services/Cloud/CloudAgentVmGateway.php new file mode 100644 index 00000000..9cecd5d3 --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentVmGateway.php @@ -0,0 +1,284 @@ + + */ + private const PANEL_TO_AGENT_KIND = [ + 'create' => null, + 'action' => 'domain_power', + 'reinstall' => null, + 'rescue' => null, + 'delete' => null, + 'network_change' => null, + 'instance_settings' => null, + 'snapshot_create' => null, + 'snapshot_restore' => null, + 'snapshot_delete' => null, + 'firewall_apply' => null, + 'service_suspend' => null, + 'service_resume' => null, + 'network_suspend' => null, + 'network_resume' => null, + 'expiry_delete' => null, + ]; + + /** @var \Closure():string */ + private \Closure $leaseOwnerFactory; + + /** + * @param callable|null $leaseOwnerFactory Returns a process-local lease + * owner. It is injected in contract tests and must not be queued or + * persisted as an authentication credential. + */ + public function __construct( + private readonly CloudAgentHostClientResolver $resolver, + private readonly CloudAgentOperationRepository $operations, + ?callable $leaseOwnerFactory = null, + private readonly int $leaseSeconds = self::LEASE_SECONDS, + ) { + if ($leaseSeconds < 1 || $leaseSeconds > 900) { + throw new \InvalidArgumentException('Agent operation lease is outside the supported range'); + } + $this->leaseOwnerFactory = \Closure::fromCallable( + $leaseOwnerFactory ?? static function (): string { + return 'php-agent-gateway-' . bin2hex(random_bytes(8)); + }, + ); + } + + /** @return array */ + public static function panelAgentKindMap(): array + { + return self::PANEL_TO_AGENT_KIND; + } + + /** + * Return the exact Agent kind for a panel kind, or fail closed when the + * Agent does not implement the panel operation yet. + */ + public static function agentKindForPanelKind(string $panelKind): string + { + if (!array_key_exists($panelKind, self::PANEL_TO_AGENT_KIND)) { + throw new CloudError('面板操作类型无效', 422); + } + $agentKind = self::PANEL_TO_AGENT_KIND[$panelKind]; + if ($agentKind === null) { + throw new CloudError('该虚拟机操作尚未由 Go Agent 实现', 501); + } + return $agentKind; + } + + /** + * Reserve and dispatch one typed VM operation. + * + * The request hash is computed over the exact `/v1/operations` JSON body + * generated by CloudAgentClient. The repository stores a redacted desired + * projection; raw Agent responses never enter the panel database. + * + * @param array $payload + * @param array $actor + * @return array + */ + public function dispatch( + int $hostId, + string $panelKind, + string $operationId, + string $idempotencyKey, + string $target, + array $payload, + array $actor, + ?string $instanceUuid = null, + ): array { + $agentKind = self::agentKindForPanelKind($panelKind); + self::assertOperationIdentity($operationId, $idempotencyKey, $target, $instanceUuid); + $payload = self::validatePayload($agentKind, $target, $payload); + $requestHash = self::requestHash($operationId, $idempotencyKey, $agentKind, $target, $payload); + + // Resolve before reserving so an operation cannot be written against + // a host whose current enrollment or key material is unusable. + $handle = $this->resolver->resolve($hostId); + $reservation = $this->operations->reserve([ + 'operation_id' => $operationId, + 'idempotency_key' => $idempotencyKey, + 'agent_id' => $handle->agentId, + 'instance_uuid' => $instanceUuid, + 'kind' => $agentKind, + 'target' => $target, + 'request_hash' => $requestHash, + 'desired' => self::journalDesired($agentKind, $payload), + ]); + if (($reservation['replay'] ?? false) === true) { + return [ + 'record' => $reservation['record'], + 'replayed' => true, + 'panel_kind' => $panelKind, + 'agent_kind' => $agentKind, + ]; + } + + $leaseOwner = ($this->leaseOwnerFactory)(); + if (!is_string($leaseOwner) || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $leaseOwner) !== 1) { + throw new CloudError('面板 Agent 操作租约身份无效', 503); + } + $claimResult = $this->operations->claim( + $operationId, + $leaseOwner, + $this->leaseSeconds, + ); + $claim = $claimResult['claim'] ?? null; + if (!$claim instanceof CloudAgentOperationClaim) { + throw new CloudError('面板 Agent 操作未能取得租约', 503); + } + + try { + $response = $handle->operation( + $operationId, + $idempotencyKey, + $agentKind, + $target, + $payload, + $actor, + ); + $envelope = CloudAgentOperationEnvelope::fromResponse( + $response, + $operationId, + $idempotencyKey, + $requestHash, + $agentKind, + $target, + ); + if ($envelope->status === 'succeeded') { + $record = $this->operations->finalize( + $claim, + 'succeeded', + $envelope->result, + '', + $envelope->commitBoundary, + ); + } elseif ($envelope->status === 'failed') { + $record = $this->operations->finalize( + $claim, + 'failed', + $envelope->result, + $envelope->errorCode, + $envelope->commitBoundary, + ); + } else { + $record = $this->operations->markUncertain( + $claim, + $envelope->errorCode !== '' ? $envelope->errorCode : 'agent_operation_incomplete', + $envelope->commitBoundary, + ); + } + } catch (CloudAgentOperationException $error) { + // A database CAS failure must not be converted into a transport + // result. The caller must surface it and reconcile by operation ID. + throw $error; + } catch (CloudError $error) { + // A timeout, reset, or incomplete envelope does not prove whether + // the host acted. Keep the row uncertain and never replay blindly. + try { + $record = $this->operations->markUncertain($claim, 'agent_transport_uncertain'); + } catch (CloudAgentOperationException) { + throw $error; + } + throw new CloudError('宿主机 Agent 响应不确定,请按操作编号核对结果', $error->httpStatus); + } catch (\Throwable $error) { + try { + $record = $this->operations->markUncertain($claim, 'agent_response_invalid'); + } catch (CloudAgentOperationException) { + throw new CloudError('宿主机 Agent 响应无效,请按操作编号核对结果', 502); + } + throw new CloudError('宿主机 Agent 响应无效,请按操作编号核对结果', 502); + } + + return [ + 'record' => $record, + 'replayed' => false, + 'panel_kind' => $panelKind, + 'agent_kind' => $agentKind, + ]; + } + + /** @param array $payload @return array */ + private static function validatePayload(string $agentKind, string $target, array $payload): array + { + if ($agentKind !== 'domain_power') { + throw new CloudError('宿主机 Agent 操作映射无效', 501); + } + $keys = array_keys($payload); + sort($keys, SORT_STRING); + if ($keys !== ['action', 'uuid'] + || !is_string($payload['uuid'] ?? null) + || $payload['uuid'] !== $target + || preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $target) !== 1 + || !is_string($payload['action'] ?? null) + || !CloudOperationCatalog::isPowerAction($payload['action'])) { + throw new CloudError('电源操作参数无效', 422); + } + return ['uuid' => $target, 'action' => $payload['action']]; + } + + /** @param array $payload */ + private static function requestHash( + string $operationId, + string $idempotencyKey, + string $kind, + string $target, + array $payload, + ): string { + $body = json_encode([ + 'operation_id' => $operationId, + 'idempotency_key' => $idempotencyKey, + 'kind' => $kind, + 'target' => $target, + 'payload' => $payload === [] ? (object) [] : $payload, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + return hash('sha256', $body); + } + + /** @param array $payload @return array */ + private static function journalDesired(string $kind, array $payload): array + { + if ($kind === 'domain_power') { + return ['uuid' => $payload['uuid'], 'action' => $payload['action']]; + } + throw new CloudError('宿主机 Agent 操作 journal 映射无效', 501); + } + + private static function assertOperationIdentity( + string $operationId, + string $idempotencyKey, + string $target, + ?string $instanceUuid, + ): 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', $operationId) !== 1 + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/D', $idempotencyKey) !== 1 + || $target !== trim($target) + || strlen($target) > 128 + || preg_match('/[\x00-\x1F\x7F]/', $target) === 1 + || ($instanceUuid !== null + && preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $instanceUuid) !== 1)) { + throw new CloudError('面板 Agent 操作身份无效', 422); + } + } +} diff --git a/web/tests/CloudAgentVmGatewayContractTest.php b/web/tests/CloudAgentVmGatewayContractTest.php new file mode 100644 index 00000000..4df6a913 --- /dev/null +++ b/web/tests/CloudAgentVmGatewayContractTest.php @@ -0,0 +1,53 @@ +"), + 'Gateway map does not explicitly cover panel kind: ' . $kind); + $assert(str_contains($catalog, "'{$kind}' =>"), + 'CloudOperationCatalog no longer contains panel kind: ' . $kind); +} + +$assert(str_contains($gateway, "'action' => 'domain_power'"), + 'The supported power-action mapping is missing.'); +$assert(str_contains($gateway, "'create' => null") + && str_contains($gateway, "'snapshot_create' => null") + && str_contains($gateway, "'delete' => null"), + 'Unsupported VM operations must fail closed instead of being aliased.'); +foreach ([ + 'CloudEngineClient', 'CloudJobService', 'CloudWorkerService', + 'ssh', 'SSH', 'shell_exec', 'exec(', 'curl_exec', +] as $forbidden) { + $assert(!str_contains($gateway, $forbidden), + 'Gateway contains a forbidden legacy transport reference: ' . $forbidden); +} +foreach ([ + 'CloudAgentHostClientResolver', 'CloudAgentOperationRepository', + 'CloudAgentOperationEnvelope', 'requestHash(', 'idempotency_key', + 'operation_id', 'markUncertain', 'CloudError', +] as $required) { + $assert(str_contains($gateway, $required), + 'Gateway is missing required typed operation boundary: ' . $required); +} + +fwrite(STDOUT, "Cloud Agent VM gateway contract passed.\n");