diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 6da00b9a..b830efb0 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -12,6 +12,11 @@ use App\Services\Auth; use App\Services\AdminCsrf; use App\Services\Config; use App\Services\Cloud\CloudAccess; +use App\Services\Cloud\CloudAgentHostClientResolverFactory; +use App\Services\Cloud\CloudAgentObservationService; +use App\Services\Cloud\CloudAgentOperationException; +use App\Services\Cloud\CloudAgentOperationRepository; +use App\Services\Cloud\CloudAgentOperationStatusService; use App\Services\Cloud\CloudDeploymentPageService; use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudError; @@ -57,6 +62,19 @@ final class CloudApiController return $response->withJson($value, $status)->withHeader('Cache-Control', 'no-store'); } + /** + * Build the request-local Agent observation seam. The factory reads only + * the fresh Agent registry and root-only key directory; no legacy engine + * client is constructed on this page-facing path. + */ + private function agentObservationService(): CloudAgentObservationService + { + return new CloudAgentObservationService( + CloudAgentHostClientResolverFactory::fromConfig(), + new CloudAgentOperationRepository(), + ); + } + private function userIsoImportAllowed(array $actor, bool $throw = false): bool { $user = User::where('id', $actor['user_id'])->first(); @@ -388,7 +406,15 @@ final class CloudApiController public function job($request, $response, $args) { $actor = $this->actor($request); - $query = CloudJob::where('id', $args['id']); + $id = (string) ($args['id'] ?? ''); + // Fresh Go Agent operations use UUID identities. Keep the historical + // numeric CloudJob path unchanged while allowing the browser to poll + // an Agent-backed operation through the same endpoint shape. + if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $id) === 1) { + return $this->json($response, + CloudAgentOperationStatusService::forActor($id, $actor)); + } + $query = CloudJob::where('id', $id); if (!$actor['is_admin']) { $query->where('user_id', $actor['user_id']); } @@ -881,7 +907,8 @@ final class CloudApiController $live = []; // Detail pages use the runtime cache by default, so opening a VM does // not wait for a potentially slow/offline host. Explicit live=1 - // refreshes use a short deadline and write a valid observation through. + // refreshes use the typed Go Agent observation operation and write a + // valid observation through the same revision fence. if (($request->getQueryParams()['live'] ?? '') === '1') { try { $instance = CloudAccess::instance($args['id'], $actor); @@ -904,16 +931,21 @@ final class CloudApiController // Live state remains useful during a rolling schema // update, but an unclaimed response must not write back. } - $candidate = (new CloudEngineClient(null, 5.0))->host( + $observed = $this->agentObservationService()->observe( (int) $instance->host_id, - 'GET', - 'vms/' . rawurlencode((string) $snapshot['uuid']) . '/state', - $actor + (string) $snapshot['uuid'], + $actor, + ); + $record = is_array($observed['record'] ?? null) + ? $observed['record'] : []; + if (($record['status'] ?? null) !== 'succeeded') { + throw new CloudError('宿主机 Agent 观察结果待核对', 503); + } + $candidate = is_array($observed['observation'] ?? null) + ? $observed['observation'] : []; + $observedState = CloudInstanceRuntimeService::normalizeState( + $candidate['state'] ?? null ); - $observedState = is_array($candidate) - ? CloudInstanceRuntimeService::normalizeState( - $candidate['state'] ?? ($candidate['power_state'] ?? null) - ) : 'unknown'; if (is_array($candidate) && is_string($candidate['uuid'] ?? null) && hash_equals(strtolower((string) $snapshot['uuid']), @@ -943,7 +975,7 @@ final class CloudApiController } $live = $candidate; } - } catch (CloudError $error) { + } catch (CloudError|CloudAgentOperationException $error) { // Preserve the identity-checked runtime snapshot when the // optional live probe cannot reach the host. } diff --git a/web/app/Middleware/CloudApi.php b/web/app/Middleware/CloudApi.php index a6b31818..1e4b99c9 100644 --- a/web/app/Middleware/CloudApi.php +++ b/web/app/Middleware/CloudApi.php @@ -25,6 +25,7 @@ final class CloudApi || preg_match('#^/api/v1/admin/hosts/[0-9]+/scheduling$#D', $path) === 1 || preg_match('#^/api/v1/ssh-keys(?:/|$)#D', $path) === 1 || preg_match('#^/api/v1/(?:jobs|reinstall-jobs|rescue-jobs)/[0-9]+$#D', $path) === 1 + || preg_match('#^/api/v1/(?:jobs|reinstall-jobs|rescue-jobs)/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$#D', $path) === 1 || preg_match('#^/api/v1/vms/[0-9]+/operations$#D', $path) === 1 || preg_match('#^/api/v1/vms/[0-9]+/firewall$#D', $path) === 1 || preg_match('#^/api/v1/vms/[0-9]+/snapshots(?:/[0-9a-f]{32}(?:/restore)?)?$#D', $path) === 1 diff --git a/web/app/Services/Cloud/CloudAgentOperationStatusService.php b/web/app/Services/Cloud/CloudAgentOperationStatusService.php new file mode 100644 index 00000000..6dc0d8d5 --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentOperationStatusService.php @@ -0,0 +1,133 @@ + $actor @return array */ + public static function forActor(string $operationId, array $actor): array + { + 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) { + throw new CloudError('任务编号无效', 400); + } + try { + $row = CloudAgentOperation::where('operation_id', $operationId)->first(); + } catch (\Throwable) { + throw new CloudError('Agent 操作记录暂时不可用', 503); + } + if ($row === null || !is_string($row->instance_uuid ?? null) + || preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $row->instance_uuid) !== 1) { + throw new CloudError('任务不存在', 404); + } + try { + // Keep the tombstone visible for the terminal delete operation. + // Authorization still uses the owner on the retained instance + // row; hiding `deleted` here would make a successful/uncertain + // delete job impossible to poll after the worker marks it done. + $instance = CloudInstance::where('uuid', $row->instance_uuid)->first(); + } catch (\Throwable) { + throw new CloudError('任务所属实例暂时不可用', 503); + } + if ($instance === null || (!($actor['is_admin'] ?? false) + && (int) $instance->user_id !== (int) ($actor['user_id'] ?? 0))) { + throw new CloudError('任务不存在', 404); + } + + // Re-read through the repository so stored JSON/identity invariants + // are checked before they become a browser DTO. This also avoids + // exposing hidden lease/error-detail columns from the Eloquent row. + try { + $record = (new CloudAgentOperationRepository())->get($operationId); + } catch (CloudAgentOperationException $error) { + if ($error->errorCode === 'not_found') { + throw new CloudError('任务不存在', 404); + } + throw new CloudError('Agent 操作记录暂时不可用', 503); + } + $kind = (string) ($record['kind'] ?? ''); + $panelKind = self::panelKind($kind); + $status = CloudOperationErrorCatalog::userStatus($record['status'] ?? null); + if ($status === null) { + // The repository validates this invariant. Keep the adapter + // fail-closed if a future repository implementation returns an + // unrecognised state rather than copying it to the browser. + throw new CloudError('Agent 操作状态损坏', 503); + } + $desired = is_array($record['desired'] ?? null) ? $record['desired'] : []; + $agentAction = is_string($desired['action'] ?? null) ? $desired['action'] : null; + $panelAction = self::panelAction($agentAction); + $administrator = (bool) ($actor['is_admin'] ?? false); + $errorCode = CloudOperationErrorCatalog::publicCode($record['error_code'] ?? null); + $error = CloudOperationErrorCatalog::userMessage( + $panelKind, $status, $errorCode, false, $panelAction, + ); + if ($administrator) { + $error = CloudOperationErrorCatalog::adminSummary( + $panelKind, $status, $record['error_code'] ?? null, false, $panelAction, + ); + } + $rawResult = is_array($record['result'] ?? null) ? $record['result'] : null; + // Repository JSON validation protects the storage shape, but it is + // intentionally not a presentation allow-list. Apply the same + // result projection used by legacy job DTOs before exposing any + // Agent-produced fields to users or administrators. + $result = $rawResult === null ? null : CloudOperationErrorCatalog::result( + $rawResult, + $administrator, + $panelKind, + $status, + false, + $panelAction, + ); + $phaseValue = is_array($result) ? ($result['phase'] ?? null) : null; + $phase = $administrator + ? CloudOperationErrorCatalog::adminSummary( + $panelKind, $status, $phaseValue, false, $panelAction, + ) + : CloudOperationErrorCatalog::userPhase($phaseValue, $status, $panelKind); + return [ + 'id' => $operationId, + 'job_id' => $operationId, + 'operation_id' => $operationId, + 'instance_id' => (string) $instance->id, + 'kind' => $panelKind, + 'status' => $status, + 'error' => $error, + 'error_code' => $errorCode, + 'attempts' => max(0, (int) ($record['attempt_count'] ?? 0)), + 'created_at' => max(0, (int) ($record['created_at'] ?? 0)), + 'updated_at' => max(0, (int) ($record['updated_at'] ?? 0)), + 'action' => $panelAction, + 'kind_label' => CloudOperationCatalog::kindLabel($panelKind, $panelAction), + 'action_label' => CloudOperationCatalog::actionLabel($panelAction), + 'phase' => $phase, + 'result' => $result, + ]; + } + + private static function panelKind(string $agentKind): string + { + return $agentKind === 'domain_power' ? 'action' : $agentKind; + } + + private static function panelAction(?string $agentAction): ?string + { + if ($agentAction === 'destroy') { + return 'poweroff'; + } + return $agentAction !== null && CloudOperationCatalog::isPowerAction($agentAction) + ? $agentAction : null; + } +} diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index f5a1e63f..4c830ec0 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -19,6 +19,8 @@ $app->group('/api/v1', function () { $this->post('/invoices/{id:[0-9]+}/payments', 'App\Controllers\CloudApiController:createInvoicePayment'); foreach (['jobs', 'reinstall-jobs', 'rescue-jobs'] as $name) { $this->get('/' . $name . '/{id:[0-9]+}', 'App\Controllers\CloudApiController:job'); + $this->get('/' . $name . '/{id:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}', + 'App\Controllers\CloudApiController:job'); } $this->get('/resources', 'App\Controllers\CloudApiController:resources'); $this->map(['GET', 'POST'], '/user-isos', 'App\Controllers\CloudApiController:userIsos'); diff --git a/web/tests/CloudAgentOperationStatusServiceContractTest.php b/web/tests/CloudAgentOperationStatusServiceContractTest.php new file mode 100644 index 00000000..7b952bdb --- /dev/null +++ b/web/tests/CloudAgentOperationStatusServiceContractTest.php @@ -0,0 +1,59 @@ +instance_uuid)') + && str_contains($service, 'CloudOperationErrorCatalog::result(') + && str_contains($service, "'result' => $result"), + 'Agent status projection lost repository validation, owner lookup, or result redaction.'); +$assert(str_contains($service, "'job_id' => $operationId") + && str_contains($service, "'operation_id' => $operationId") + && str_contains($service, "'instance_id' => (string) $instance->id"), + 'Agent status DTO no longer preserves the browser job identity fields.'); + +foreach (['CloudEngineClient', 'CloudJobService', 'CloudWorkerService', 'ssh', 'SSH', 'shell_exec', 'curl_exec'] as $forbidden) { + $assert(!str_contains($service, $forbidden), + 'Agent status projection crossed a legacy transport boundary: ' . $forbidden); +} + +fwrite(STDOUT, "Cloud Agent operation status contract passed.\n");