feat: harden php agent cutover and reconcile
parent
d8b692964b
commit
ab385f7b86
@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
|
||||
/**
|
||||
* Panel-facing power action adapter for the greenfield Agent protocol.
|
||||
*
|
||||
* Authorization and service-policy checks remain in the controller. This
|
||||
* class owns only operation identity, typed payload construction, dispatch,
|
||||
* and the browser-compatible acknowledgement shape; it has no Python/SSH or
|
||||
* legacy CloudJob dependency.
|
||||
*/
|
||||
final class CloudAgentActionService
|
||||
{
|
||||
public function __construct(private readonly CloudAgentVmGateway $gateway)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $actor
|
||||
* @return array{record:array<string,mixed>,replayed:bool,panel_kind:string,agent_kind:string,operation_id:string,idempotency_key:string,panel_action:string}
|
||||
*/
|
||||
public function dispatch(
|
||||
CloudInstance $instance,
|
||||
array $actor,
|
||||
string $panelAction,
|
||||
?string $idempotencyKey = null,
|
||||
?string $operationId = null,
|
||||
): array {
|
||||
if (!CloudOperationCatalog::isPowerAction($panelAction)) {
|
||||
throw new CloudError('操作无效', 422);
|
||||
}
|
||||
// Do not gate idempotent retries on the panel's cached status. A
|
||||
// replay may arrive after the guest has transitioned (or after a
|
||||
// previous request was fenced uncertain); the durable Agent journal
|
||||
// and host readback are the authority for the operation outcome.
|
||||
$uuid = strtolower(trim((string) $instance->uuid));
|
||||
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $uuid) !== 1) {
|
||||
throw new CloudError('虚拟机标识无效', 409);
|
||||
}
|
||||
if ($operationId !== null && $operationId !== '') {
|
||||
$operationId = CloudAgentOperationIdentity::validateUuid($operationId);
|
||||
if ($idempotencyKey === null || $idempotencyKey === '') {
|
||||
// An operation UUID does not contain, and cannot safely
|
||||
// recover, the original idempotency key. Deriving a new key
|
||||
// would make a retry look like a different Agent operation.
|
||||
throw new CloudError(
|
||||
'面板 Agent 重试必须同时提供 operation_id 和幂等键', 422);
|
||||
}
|
||||
$idempotencyKey = CloudAgentOperationIdentity::validateIdempotencyKey($idempotencyKey);
|
||||
} else {
|
||||
$idempotencyKey = $idempotencyKey === null || $idempotencyKey === ''
|
||||
? CloudAgentOperationIdentity::idempotencyKey('action')
|
||||
: CloudAgentOperationIdentity::validateIdempotencyKey($idempotencyKey);
|
||||
$operationId = CloudAgentOperationIdentity::uuidForIdempotencyKey($idempotencyKey);
|
||||
}
|
||||
|
||||
$dispatched = $this->gateway->dispatch(
|
||||
(int) $instance->host_id,
|
||||
'action',
|
||||
$operationId,
|
||||
$idempotencyKey,
|
||||
$uuid,
|
||||
['uuid' => $uuid, 'action' => $panelAction],
|
||||
$actor,
|
||||
$uuid,
|
||||
(int) $instance->id,
|
||||
);
|
||||
return $dispatched + [
|
||||
'operation_id' => $operationId,
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'panel_action' => $panelAction,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a safe journal record into the DTO consumed by the existing
|
||||
* browser poller. The record has already passed repository validation;
|
||||
* this second projection keeps the response independent of storage shape.
|
||||
*
|
||||
* @param array<string,mixed> $record
|
||||
* @param array<string,mixed> $actor
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public static function acknowledgement(
|
||||
array $record,
|
||||
CloudInstance $instance,
|
||||
array $actor,
|
||||
string $panelAction,
|
||||
string $idempotencyKey,
|
||||
): array {
|
||||
$operationId = is_string($record['operation_id'] ?? null)
|
||||
? $record['operation_id'] : '';
|
||||
CloudAgentOperationIdentity::validateUuid($operationId);
|
||||
$status = CloudOperationErrorCatalog::userStatus($record['status'] ?? null) ?? 'unknown';
|
||||
$administrator = (bool) ($actor['is_admin'] ?? false);
|
||||
$errorCode = CloudOperationErrorCatalog::publicCode($record['error_code'] ?? null);
|
||||
$rawResult = is_array($record['result'] ?? null) ? $record['result'] : null;
|
||||
$result = $rawResult === null ? null : CloudOperationErrorCatalog::result(
|
||||
$rawResult, $administrator, 'action', $status, false, $panelAction,
|
||||
);
|
||||
$phase = is_array($result) ? ($result['phase'] ?? null) : null;
|
||||
$phase = $administrator
|
||||
? CloudOperationErrorCatalog::adminSummary('action', $status, $phase, false, $panelAction)
|
||||
: CloudOperationErrorCatalog::userPhase($phase, $status, 'action');
|
||||
$error = $administrator
|
||||
? CloudOperationErrorCatalog::adminSummary('action', $status,
|
||||
$record['error_code'] ?? null, false, $panelAction)
|
||||
: CloudOperationErrorCatalog::userMessage('action', $status, $errorCode,
|
||||
false, $panelAction);
|
||||
$labels = CloudOperationCatalog::labels('action', $panelAction);
|
||||
return [
|
||||
'id' => $operationId,
|
||||
'job_id' => $operationId,
|
||||
'operation_id' => $operationId,
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'instance_id' => (string) $instance->id,
|
||||
'kind' => 'action',
|
||||
'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' => $labels['kind_label'],
|
||||
'action_label' => $labels['action_label'],
|
||||
'phase' => is_string($phase) ? mb_substr($phase, 0, 120) : null,
|
||||
'result' => $result,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* The Agent request may have reached the host, but its response did not
|
||||
* produce a complete authenticated terminal envelope. The journal row is
|
||||
* already fenced as uncertain and is safe to expose as a pollable job; the
|
||||
* caller must not replay the mutation automatically.
|
||||
*/
|
||||
final class CloudAgentDispatchUncertain extends \RuntimeException
|
||||
{
|
||||
public readonly int $httpStatus;
|
||||
|
||||
/** @param array<string,mixed> $record */
|
||||
public function __construct(
|
||||
public readonly string $operationId,
|
||||
public readonly array $record,
|
||||
int $httpStatus = 502,
|
||||
) {
|
||||
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 \InvalidArgumentException('Uncertain Agent operation id is invalid');
|
||||
}
|
||||
if ($httpStatus < 400 || $httpStatus > 599) {
|
||||
throw new \InvalidArgumentException('Uncertain Agent HTTP status is invalid');
|
||||
}
|
||||
$this->httpStatus = $httpStatus;
|
||||
parent::__construct('宿主机 Agent 响应不确定,请按操作编号核对结果');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* Resolve Go Agent transport material from root-owned files.
|
||||
*
|
||||
* The agent registry deliberately stores only public identity metadata. This
|
||||
* resolver is the panel-side bridge to the corresponding host-local secret
|
||||
* directory; no key, certificate, or private key is read from a database
|
||||
* model. Files are named by the already-validated Agent ID and are checked
|
||||
* as ordinary files before their contents are consumed.
|
||||
*/
|
||||
final class CloudAgentFileSecretResolver implements CloudAgentSecretResolver
|
||||
{
|
||||
private const AGENT_ID_PATTERN = '/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D';
|
||||
|
||||
private const MAX_KEY_FILE_BYTES = 4096;
|
||||
|
||||
private const MAX_TLS_FILE_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* @param callable|null $fileReader Optional test-only reader. It receives
|
||||
* an absolute path and returns the file bytes or null.
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly string $directory,
|
||||
?callable $fileReader = null,
|
||||
) {
|
||||
if (!self::validAbsoluteDirectory($directory)) {
|
||||
throw new \InvalidArgumentException('Agent secret directory is invalid');
|
||||
}
|
||||
$this->fileReader = \Closure::fromCallable($fileReader ?? [self::class, 'readSecureFile']);
|
||||
}
|
||||
|
||||
/** @var \Closure(string):string|null */
|
||||
private \Closure $fileReader;
|
||||
|
||||
/**
|
||||
* Files use the following fixed names per Agent:
|
||||
*
|
||||
* <id>.hmac canonical standard-base64, 32 raw bytes
|
||||
* <id>.ca.pem panel trust anchor
|
||||
* <id>.crt panel client certificate
|
||||
* <id>.key panel client private key
|
||||
*
|
||||
* Returning paths instead of certificate contents keeps the TLS library's
|
||||
* normal certificate handling and lets CloudAgentClient re-check the
|
||||
* registered certificate fingerprint before every request.
|
||||
*
|
||||
* @return array{hmac_key:string,ca_file:string,cert_file:string,key_file:string}|null
|
||||
*/
|
||||
public function resolve(string $agentId): ?array
|
||||
{
|
||||
if (preg_match(self::AGENT_ID_PATTERN, $agentId) !== 1) {
|
||||
return null;
|
||||
}
|
||||
$base = rtrim($this->directory, '/') . '/' . $agentId;
|
||||
$hmac = $this->readHmac($base . '.hmac');
|
||||
if ($hmac === null) {
|
||||
return null;
|
||||
}
|
||||
$paths = [
|
||||
'ca_file' => $base . '.ca.pem',
|
||||
'cert_file' => $base . '.crt',
|
||||
'key_file' => $base . '.key',
|
||||
];
|
||||
foreach ($paths as $path) {
|
||||
if (($this->fileReader)($path) === null) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return ['hmac_key' => $hmac] + $paths;
|
||||
}
|
||||
|
||||
private function readHmac(string $path): ?string
|
||||
{
|
||||
$contents = ($this->fileReader)($path);
|
||||
if (!is_string($contents)) {
|
||||
return null;
|
||||
}
|
||||
// Permit exactly one conventional final LF/CRLF, but do not trim
|
||||
// arbitrary whitespace: accepting it would make the file protocol
|
||||
// ambiguous across PHP and Go.
|
||||
if (str_ends_with($contents, "\r\n")) {
|
||||
$contents = substr($contents, 0, -2);
|
||||
} elseif (str_ends_with($contents, "\n")) {
|
||||
$contents = substr($contents, 0, -1);
|
||||
}
|
||||
if ($contents === '' || preg_match('/^[A-Za-z0-9+\/=]+$/D', $contents) !== 1) {
|
||||
return null;
|
||||
}
|
||||
$decoded = base64_decode($contents, true);
|
||||
if (!is_string($decoded) || strlen($decoded) !== 32
|
||||
|| !hash_equals($contents, base64_encode($decoded))) {
|
||||
return null;
|
||||
}
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
private static function validAbsoluteDirectory(string $directory): bool
|
||||
{
|
||||
if ($directory === '' || $directory === '/' || $directory !== trim($directory)
|
||||
|| $directory[0] !== '/' || preg_match('/[\x00-\x1F\x7F]/', $directory) === 1
|
||||
|| str_contains($directory, '//')) {
|
||||
return false;
|
||||
}
|
||||
$parts = explode('/', trim($directory, '/'));
|
||||
foreach ($parts as $part) {
|
||||
if ($part === '' || $part === '.' || $part === '..'
|
||||
|| preg_match('/^[A-Za-z0-9_.:-]+$/D', $part) !== 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a secret file only when its leaf and every parent are real,
|
||||
* non-writable filesystem objects. The injected reader used by contract
|
||||
* tests is intentionally the sole bypass; production construction uses
|
||||
* this method by default.
|
||||
*/
|
||||
private static function readSecureFile(string $path): ?string
|
||||
{
|
||||
if ($path === '' || $path[0] !== '/' || preg_match('/[\x00-\x1F\x7F]/', $path) === 1) {
|
||||
return null;
|
||||
}
|
||||
// Reuse the transport resolver's ownership/symlink policy before
|
||||
// reading the HMAC, CA, certificate or private key. The bounded
|
||||
// size check below remains stricter for secret files.
|
||||
// HMAC material is a bearer signing secret just like the private key;
|
||||
// group/other-readable files are rejected even though CA/cert PEM
|
||||
// files may use the looser non-writable certificate mode.
|
||||
$privateKey = str_ends_with($path, '.key') || str_ends_with($path, '.hmac');
|
||||
if (!CloudAgentHostClientResolver::validateCredentialPath($path, $privateKey)) {
|
||||
return null;
|
||||
}
|
||||
$stat = @lstat($path);
|
||||
$maxBytes = str_ends_with($path, '.hmac')
|
||||
? self::MAX_KEY_FILE_BYTES : self::MAX_TLS_FILE_BYTES;
|
||||
if (!is_array($stat)
|
||||
|| (($stat['mode'] ?? 0) & 0170000) !== 0100000
|
||||
|| (($stat['mode'] ?? 0) & 0022) !== 0
|
||||
|| (int) ($stat['size'] ?? 0) < 1
|
||||
|| (int) ($stat['size'] ?? 0) > $maxBytes) {
|
||||
return null;
|
||||
}
|
||||
$directory = dirname($path);
|
||||
while ($directory !== '/') {
|
||||
$directoryStat = @lstat($directory);
|
||||
$mode = is_array($directoryStat) ? (int) ($directoryStat['mode'] ?? 0) : 0;
|
||||
if (!is_array($directoryStat)
|
||||
|| ($mode & 0170000) !== 0040000
|
||||
|| ($mode & 0022) !== 0) {
|
||||
return null;
|
||||
}
|
||||
$parent = dirname($directory);
|
||||
if ($parent === $directory) {
|
||||
return null;
|
||||
}
|
||||
$directory = $parent;
|
||||
}
|
||||
$value = @file_get_contents($path);
|
||||
return is_string($value) && strlen($value) <= $maxBytes
|
||||
? $value : null;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* Generate and validate identities for the greenfield Agent journal.
|
||||
*
|
||||
* The legacy panel jobs use a 32-character hexadecimal operation id. The Go
|
||||
* Agent protocol deliberately uses RFC 4122 UUIDs, so new callers must never
|
||||
* reuse a legacy id or silently pad it into a UUID-shaped value.
|
||||
*/
|
||||
final class CloudAgentOperationIdentity
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public static function uuid(): string
|
||||
{
|
||||
$bytes = random_bytes(16);
|
||||
// RFC 4122 version 4 / variant 1.
|
||||
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
|
||||
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
|
||||
$hex = bin2hex($bytes);
|
||||
return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-'
|
||||
. substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-'
|
||||
. substr($hex, 20, 12);
|
||||
}
|
||||
|
||||
public static function idempotencyKey(string $prefix = 'panel'): string
|
||||
{
|
||||
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/D', $prefix) !== 1) {
|
||||
throw new \InvalidArgumentException('Agent idempotency prefix is invalid');
|
||||
}
|
||||
return $prefix . '-' . bin2hex(random_bytes(16));
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a stable UUID for a caller-supplied idempotency key. This lets a
|
||||
* browser retry with the same key without inventing a second operation
|
||||
* identity; a changed payload is still rejected by the journal hash.
|
||||
*/
|
||||
public static function uuidForIdempotencyKey(string $key): string
|
||||
{
|
||||
self::validateIdempotencyKey($key);
|
||||
$bytes = hash('sha256', "virt-cloud-agent-operation\0" . $key, true);
|
||||
$bytes = substr($bytes, 0, 16);
|
||||
// UUID version 5 shape (the namespace is the panel's local contract,
|
||||
// not a security secret); uniqueness comes from the full key digest.
|
||||
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x50);
|
||||
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
|
||||
$hex = bin2hex($bytes);
|
||||
return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-'
|
||||
. substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-'
|
||||
. substr($hex, 20, 12);
|
||||
}
|
||||
|
||||
public static function validateUuid(mixed $value): string
|
||||
{
|
||||
if (!is_string($value)
|
||||
|| 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);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function validateIdempotencyKey(mixed $value): string
|
||||
{
|
||||
if (!is_string($value)
|
||||
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/D', $value) !== 1) {
|
||||
throw new CloudError('面板 Agent 幂等键无效', 422);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,385 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
|
||||
/**
|
||||
* Reconcile one uncertain Agent operation without replaying its mutation.
|
||||
*
|
||||
* The panel journal and the Agent journal are separate durable stores. A
|
||||
* lost response therefore cannot be resolved by submitting the original
|
||||
* request again: doing so could apply a lifecycle action twice. This service
|
||||
* claims the existing uncertain row, reads the Agent journal, and asks the
|
||||
* Agent's explicit read-back endpoint only when the first read is not already
|
||||
* terminal. A local row is finalized only after a complete, identity-checked
|
||||
* Agent envelope is received; reduced/error responses remain uncertain.
|
||||
*/
|
||||
final class CloudAgentOperationReconcileService
|
||||
{
|
||||
private const LEASE_SECONDS = 120;
|
||||
|
||||
/** @var \Closure():string */
|
||||
private \Closure $leaseOwnerFactory;
|
||||
|
||||
/**
|
||||
* @param callable|null $leaseOwnerFactory Returns a process-local lease
|
||||
* owner. It is never persisted or sent as an Agent 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 reconcile lease is outside the supported range');
|
||||
}
|
||||
$this->leaseOwnerFactory = \Closure::fromCallable(
|
||||
$leaseOwnerFactory ?? static fn (): string => 'php-agent-reconcile-' . bin2hex(random_bytes(8)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the production service from the fresh Agent registry and secret
|
||||
* directory. No legacy engine or SSH client is consulted.
|
||||
*/
|
||||
public static function fromConfig(
|
||||
?callable $leaseOwnerFactory = null,
|
||||
int $leaseSeconds = self::LEASE_SECONDS,
|
||||
): self {
|
||||
return new self(
|
||||
CloudAgentHostClientResolverFactory::fromConfig(),
|
||||
new CloudAgentOperationRepository(),
|
||||
$leaseOwnerFactory,
|
||||
$leaseSeconds,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile one tenant-visible domain power operation.
|
||||
*
|
||||
* Only `domain_power` is exposed by the current panel job DTO. Keeping
|
||||
* this allow-list explicit prevents an internal observation/plan UUID
|
||||
* from becoming a generic Agent proxy. Other operation kinds need their
|
||||
* own owner binding and presentation contract before being added here.
|
||||
*
|
||||
* @param array<string,mixed> $actor
|
||||
* @return array<string,mixed> fresh repository record
|
||||
*/
|
||||
public function reconcile(string $operationId, array $actor): array
|
||||
{
|
||||
$operationId = CloudAgentOperationIdentity::validateUuid($operationId);
|
||||
$record = $this->authorizedRecord($operationId, $actor);
|
||||
$status = (string) ($record['status'] ?? '');
|
||||
if (in_array($status, ['succeeded', 'failed'], true)) {
|
||||
return $record;
|
||||
}
|
||||
if ($status !== 'uncertain') {
|
||||
throw new CloudError('任务仍在处理中,请稍后再核对', 409);
|
||||
}
|
||||
if (($record['kind'] ?? null) !== 'domain_power') {
|
||||
throw new CloudError('该 Agent 操作暂不支持面板核对', 409);
|
||||
}
|
||||
|
||||
$agentId = is_string($record['agent_id'] ?? null) ? $record['agent_id'] : '';
|
||||
$hostId = self::positiveInt($record['host_id'] ?? null);
|
||||
if ($agentId === '' || $hostId < 1) {
|
||||
throw new CloudError('任务所属 Agent 身份已损坏', 503);
|
||||
}
|
||||
|
||||
// Resolve the current endpoint, then fence it to the immutable Agent
|
||||
// identity stored on the operation. A host re-enrollment must never
|
||||
// let an old operation be queried against a different Agent.
|
||||
// Reconciliation is read-only and must remain possible while the
|
||||
// Agent registry reports degraded. Mutating dispatches still use
|
||||
// resolve(), which only admits active registrations.
|
||||
$handle = $this->resolver->resolveReadOnly($hostId);
|
||||
if ($handle->hostId !== $hostId || !hash_equals($agentId, $handle->agentId)) {
|
||||
throw new CloudError('任务所属 Agent 身份已变化,请联系管理员核对', 409);
|
||||
}
|
||||
|
||||
$owner = ($this->leaseOwnerFactory)();
|
||||
if (!is_string($owner)
|
||||
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $owner) !== 1) {
|
||||
throw new CloudError('面板 Agent 核对租约身份无效', 503);
|
||||
}
|
||||
$claim = $this->claimReconcile($operationId, $owner);
|
||||
$record = $claim['record'] ?? $record;
|
||||
$claimToken = $claim['claim'] ?? null;
|
||||
if (!$claimToken instanceof CloudAgentOperationClaim) {
|
||||
throw new CloudError('面板 Agent 核对未能取得租约', 503);
|
||||
}
|
||||
|
||||
$getFailure = null;
|
||||
try {
|
||||
$first = null;
|
||||
try {
|
||||
$first = $handle->getOperation($operationId, $actor);
|
||||
} catch (CloudError $error) {
|
||||
$getFailure = $error;
|
||||
}
|
||||
|
||||
if (is_array($first)) {
|
||||
$envelope = $this->envelope($first, $record);
|
||||
if ($envelope !== null && self::terminal($envelope->status)) {
|
||||
return $this->finalizeEnvelope($claimToken, $envelope);
|
||||
}
|
||||
}
|
||||
|
||||
// The Agent endpoint is a typed read-back operation. It must not
|
||||
// call the original PowerDomain/lifecycle method again.
|
||||
$reconciled = null;
|
||||
try {
|
||||
$reconciled = $handle->reconcile($operationId, $actor);
|
||||
} catch (CloudError $error) {
|
||||
$getFailure = $error;
|
||||
}
|
||||
if (is_array($reconciled)) {
|
||||
$envelope = $this->envelope($reconciled, $record);
|
||||
if ($envelope !== null) {
|
||||
if (self::terminal($envelope->status)) {
|
||||
return $this->finalizeEnvelope($claimToken, $envelope);
|
||||
}
|
||||
return $this->retainUncertain(
|
||||
$claimToken,
|
||||
self::safeErrorCode($envelope->errorCode, 'agent_reconcile_incomplete'),
|
||||
self::boundary($envelope->commitBoundary),
|
||||
$envelope->result,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Non-2xx responses are intentionally reduced by CloudAgentClient
|
||||
// and cannot prove identity/terminal state. One final GET may
|
||||
// obtain the complete record after a successful Agent read-back;
|
||||
// otherwise the panel remains explicitly uncertain.
|
||||
if (is_array($reconciled) || $getFailure !== null) {
|
||||
try {
|
||||
$last = $handle->getOperation($operationId, $actor);
|
||||
$envelope = $this->envelope($last, $record);
|
||||
if ($envelope !== null && self::terminal($envelope->status)) {
|
||||
return $this->finalizeEnvelope($claimToken, $envelope);
|
||||
}
|
||||
} catch (CloudError $error) {
|
||||
$getFailure = $error;
|
||||
}
|
||||
}
|
||||
|
||||
$fallback = is_array($reconciled) && is_string($reconciled['error_code'] ?? null)
|
||||
? $reconciled['error_code'] : '';
|
||||
$fallback = self::safeErrorCode($fallback,
|
||||
$getFailure === null ? 'agent_reconcile_uncertain' : 'agent_reconcile_transport_uncertain');
|
||||
return $this->retainUncertain($claimToken, $fallback);
|
||||
} catch (CloudAgentOperationException $error) {
|
||||
// A lost local lease/CAS is not a host result. Do not overwrite a
|
||||
// newer claimant; surface the conflict for a later operation-ID
|
||||
// retry.
|
||||
// A malformed terminal envelope can fail repository validation
|
||||
// before its CAS write (for example a sensitive result field or
|
||||
// an unproven commit boundary). Release our reconcile lease by
|
||||
// retaining uncertain state, but never downgrade lease/storage
|
||||
// conflicts into a host result.
|
||||
if (in_array($error->errorCode, ['invalid_request', 'invalid_transition'], true)) {
|
||||
try {
|
||||
return $this->retainUncertain(
|
||||
$claimToken,
|
||||
'agent_reconcile_result_invalid',
|
||||
);
|
||||
} catch (CloudAgentOperationException) {
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
throw $error;
|
||||
} catch (CloudError $error) {
|
||||
// Malformed or mismatched Agent envelopes are never terminal
|
||||
// evidence. Keep the row uncertain and retain the safe error code.
|
||||
try {
|
||||
return $this->retainUncertain(
|
||||
$claimToken,
|
||||
$error->httpStatus === 502
|
||||
? 'agent_reconcile_response_invalid'
|
||||
: 'agent_reconcile_transport_uncertain',
|
||||
);
|
||||
} catch (CloudAgentOperationException) {
|
||||
throw $error;
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
try {
|
||||
return $this->retainUncertain($claimToken, 'agent_reconcile_response_invalid');
|
||||
} catch (CloudAgentOperationException) {
|
||||
throw new CloudError('Agent 核对结果无法保存,请稍后重试', 503);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{record:array<string,mixed>,claim:CloudAgentOperationClaim} */
|
||||
private function claimReconcile(string $operationId, string $owner): array
|
||||
{
|
||||
try {
|
||||
return $this->operations->claim(
|
||||
$operationId,
|
||||
$owner,
|
||||
$this->leaseSeconds,
|
||||
'reconcile',
|
||||
);
|
||||
} catch (CloudAgentOperationException $error) {
|
||||
// claim() fences an expired running worker to uncertain and throws
|
||||
// after committing that fence. Retry exactly once in reconcile
|
||||
// mode; never dispatch the original operation again.
|
||||
if ($error->errorCode !== 'uncertain') {
|
||||
throw $error;
|
||||
}
|
||||
return $this->operations->claim(
|
||||
$operationId,
|
||||
$owner,
|
||||
$this->leaseSeconds,
|
||||
'reconcile',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $record */
|
||||
private function envelope(array $response, array $record): ?CloudAgentOperationEnvelope
|
||||
{
|
||||
try {
|
||||
return CloudAgentOperationEnvelope::fromResponse(
|
||||
$response,
|
||||
(string) $record['operation_id'],
|
||||
(string) $record['idempotency_key'],
|
||||
(string) $record['request_hash'],
|
||||
(string) $record['kind'],
|
||||
(string) $record['target'],
|
||||
);
|
||||
} catch (CloudError) {
|
||||
// Reduced non-2xx envelopes and malformed identity are both
|
||||
// non-terminal. The caller will retain uncertain state.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function finalizeEnvelope(
|
||||
CloudAgentOperationClaim $claim,
|
||||
CloudAgentOperationEnvelope $envelope,
|
||||
): array {
|
||||
if ($envelope->status === 'succeeded') {
|
||||
return $this->operations->finalize(
|
||||
$claim,
|
||||
'succeeded',
|
||||
$envelope->result,
|
||||
'',
|
||||
self::boundary($envelope->commitBoundary),
|
||||
);
|
||||
}
|
||||
if ($envelope->status === 'failed') {
|
||||
return $this->operations->finalize(
|
||||
$claim,
|
||||
'failed',
|
||||
$envelope->result,
|
||||
self::safeErrorCode($envelope->errorCode, 'agent_reconcile_failed'),
|
||||
self::boundary($envelope->commitBoundary),
|
||||
);
|
||||
}
|
||||
return $this->retainUncertain(
|
||||
$claim,
|
||||
self::safeErrorCode($envelope->errorCode, 'agent_reconcile_incomplete'),
|
||||
self::boundary($envelope->commitBoundary),
|
||||
$envelope->result,
|
||||
);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed>|null $result */
|
||||
private function retainUncertain(
|
||||
CloudAgentOperationClaim $claim,
|
||||
string $errorCode,
|
||||
?string $boundary = null,
|
||||
?array $result = null,
|
||||
): array {
|
||||
return $this->operations->finalize(
|
||||
$claim,
|
||||
'uncertain',
|
||||
$result,
|
||||
self::safeErrorCode($errorCode, 'agent_reconcile_uncertain'),
|
||||
$boundary,
|
||||
);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $actor @return array<string,mixed> */
|
||||
private function authorizedRecord(string $operationId, array $actor): array
|
||||
{
|
||||
try {
|
||||
$record = $this->operations->get($operationId);
|
||||
} catch (CloudAgentOperationException $error) {
|
||||
if ($error->errorCode === 'not_found') {
|
||||
throw new CloudError('任务不存在', 404);
|
||||
}
|
||||
throw new CloudError('Agent 操作记录暂时不可用', 503);
|
||||
}
|
||||
$uuid = is_string($record['instance_uuid'] ?? null)
|
||||
? strtolower(trim($record['instance_uuid'])) : '';
|
||||
$hostId = self::positiveInt($record['host_id'] ?? null);
|
||||
$instanceId = self::positiveInt($record['instance_id'] ?? null);
|
||||
if ($hostId < 1 || $instanceId < 1
|
||||
|| preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $uuid) !== 1
|
||||
|| !is_string($record['agent_id'] ?? null) || trim($record['agent_id']) === '') {
|
||||
throw new CloudError('任务身份已损坏', 503);
|
||||
}
|
||||
try {
|
||||
// Query the numeric generation first, then compare UUID in PHP so
|
||||
// a case-insensitive database collation cannot bridge identities.
|
||||
$instance = CloudInstance::where('host_id', $hostId)
|
||||
->where('id', $instanceId)->first();
|
||||
} catch (\Throwable) {
|
||||
throw new CloudError('任务所属实例暂时不可用', 503);
|
||||
}
|
||||
$currentUuid = $instance === null
|
||||
? '' : strtolower(trim((string) ($instance->uuid ?? '')));
|
||||
if ($instance === null || $currentUuid === '' || !hash_equals($uuid, $currentUuid)
|
||||
|| (!(bool) ($actor['is_admin'] ?? false)
|
||||
&& (int) ($instance->user_id ?? 0) !== (int) ($actor['user_id'] ?? 0))) {
|
||||
throw new CloudError('任务不存在', 404);
|
||||
}
|
||||
$operationCreated = self::positiveInt($record['created_at'] ?? null);
|
||||
$instanceCreated = self::positiveInt($instance->created_at ?? null);
|
||||
if ($operationCreated > 0 && $instanceCreated > 0 && $operationCreated < $instanceCreated) {
|
||||
// A reused numeric id/UUID must not let an old uncertain row be
|
||||
// reconciled against a newly provisioned VM generation.
|
||||
throw new CloudError('任务实例代际已变化,请重新查询', 409);
|
||||
}
|
||||
if (($record['kind'] ?? null) === 'domain_power'
|
||||
&& !hash_equals($uuid, strtolower(trim((string) ($record['target'] ?? ''))))) {
|
||||
// The numeric instance lookup alone is not sufficient: a corrupt
|
||||
// or manually inserted operation target could otherwise ask the
|
||||
// Agent to read back another UUID under this owner's VM.
|
||||
throw new CloudError('任务实例目标已损坏', 503);
|
||||
}
|
||||
return $record;
|
||||
}
|
||||
|
||||
private static function terminal(string $status): bool
|
||||
{
|
||||
return in_array($status, ['succeeded', 'failed'], true);
|
||||
}
|
||||
|
||||
private static function boundary(?string $boundary): ?string
|
||||
{
|
||||
// A local uncertain row may already be fenced to unknown. Never ask
|
||||
// the repository to roll that evidence back to not_started.
|
||||
return $boundary === null || $boundary === 'not_started' ? null : $boundary;
|
||||
}
|
||||
|
||||
private static function safeErrorCode(string $value, string $fallback): string
|
||||
{
|
||||
return preg_match('/^[a-z][a-z0-9_.-]{0,63}$/D', $value) === 1
|
||||
? $value : $fallback;
|
||||
}
|
||||
|
||||
private static function positiveInt(mixed $value): int
|
||||
{
|
||||
if (is_int($value)) {
|
||||
return $value > 0 ? $value : 0;
|
||||
}
|
||||
return is_string($value) && preg_match('/^[1-9][0-9]*$/D', $value) === 1
|
||||
? (int) $value : 0;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
// Dependency-free source contract for the first mutating page cutover. The
|
||||
// full integration test belongs to the panel CI (PHP/Composer is not part of
|
||||
// this development shell); this guard ensures the action endpoint cannot
|
||||
// silently fall back to the legacy queue or transport.
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$value = file_get_contents($root . '/' . $path);
|
||||
if (!is_string($value)) {
|
||||
throw new RuntimeException('Missing Agent action cutover source: ' . $path);
|
||||
}
|
||||
return $value;
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$controller = $read('app/Controllers/CloudApiController.php');
|
||||
$service = $read('app/Services/Cloud/CloudAgentActionService.php');
|
||||
$identity = $read('app/Services/Cloud/CloudAgentOperationIdentity.php');
|
||||
$gateway = $read('app/Services/Cloud/CloudAgentVmGateway.php');
|
||||
$repository = $read('app/Services/Cloud/CloudAgentOperationRepository.php');
|
||||
$runtime = $read('public/cloud/runtime.js');
|
||||
|
||||
$actionOffset = strpos($controller, 'public function actions(');
|
||||
$actionBody = $actionOffset === false ? '' : substr($controller, $actionOffset);
|
||||
$actionEnd = $actionBody === '' ? false : strpos($actionBody, "\n public function reinstall(");
|
||||
if ($actionEnd !== false) {
|
||||
$actionBody = substr($actionBody, 0, $actionEnd);
|
||||
}
|
||||
$assert($actionOffset !== false
|
||||
&& $actionEnd !== false
|
||||
&& str_contains($actionBody, 'agentActionService()->dispatch')
|
||||
&& str_contains($actionBody, 'CloudAgentDispatchUncertain')
|
||||
&& str_contains($actionBody, "'/api/v1/jobs/'"),
|
||||
'Action endpoint is not wired to the Agent operation/status boundary.');
|
||||
foreach (['CloudJobService::enqueue', 'CloudEngineClient', 'ssh', 'SSH', 'shell_exec', 'curl_exec'] as $forbidden) {
|
||||
$assert(!str_contains($actionBody, $forbidden),
|
||||
'Action endpoint still contains a legacy transport/queue reference: ' . $forbidden);
|
||||
}
|
||||
$assert(str_contains($service, 'CloudAgentOperationIdentity::uuidForIdempotencyKey')
|
||||
&& str_contains($service, '重试必须同时提供 operation_id 和幂等键')
|
||||
&& !str_contains($service, 'idempotencyKeyForOperationId')
|
||||
&& str_contains($service, 'CloudAgentVmGateway')
|
||||
&& str_contains($service, "'action'")
|
||||
&& str_contains($service, "'instance_id' => (string)"),
|
||||
'Action service lost typed identity, gateway dispatch, or browser DTO projection.');
|
||||
$assert(str_contains($identity, 'random_bytes(16)')
|
||||
&& str_contains($identity, 'uuidForIdempotencyKey')
|
||||
&& str_contains($identity, 'validateIdempotencyKey')
|
||||
&& !str_contains($identity, 'idempotencyKeyForOperationId'),
|
||||
'Agent operation identity must use UUIDs and bounded idempotency keys without deriving a key from an opaque operation UUID.');
|
||||
$assert(str_contains($gateway, "'poweroff' => 'destroy'")
|
||||
&& str_contains($gateway, 'isReducedFailure')
|
||||
&& str_contains($gateway, 'isDefinitiveReducedRejection')
|
||||
&& str_contains($gateway, 'agent_operation_transport_uncertain'),
|
||||
'Gateway lost the panel-to-Agent power mapping or reduced-error handling.');
|
||||
$assert(str_contains($repository, 'lockInstanceState')
|
||||
&& str_contains($repository, "'instance_busy'")
|
||||
&& str_contains($repository, "whereIn('status', ['pending', 'running', 'uncertain'])")
|
||||
&& str_contains($repository, 'in_array($request[\'kind\'], self::MUTATING_KINDS, true)'),
|
||||
'Agent mutations lost the per-instance durable serialization gate.');
|
||||
$assert(str_contains($actionBody, 'bodyIdempotency !== $headerIdempotency')
|
||||
&& str_contains($actionBody, 'bodyOperationId !== $headerOperationId')
|
||||
&& str_contains($actionBody, '重试必须同时提供 operation_id 和幂等键')
|
||||
&& str_contains($actionBody, 'CloudAgentOperationException'),
|
||||
'Action endpoint must reject split identity headers and preserve deterministic repository errors.');
|
||||
$assert(str_contains($runtime, 'POWER_OPERATION_STORAGE_PREFIX')
|
||||
&& str_contains($runtime, 'powerOperationStorageKey(vmId, action, vmUuid = \'\')')
|
||||
&& str_contains($runtime, 'powerOperationMemory')
|
||||
&& str_contains($runtime, "body: { action, idempotency_key: idempotencyKey }")
|
||||
&& str_contains($runtime, "headers: { 'Idempotency-Key': idempotencyKey }")
|
||||
&& str_contains($runtime, 'allowUncertain: true')
|
||||
&& str_contains($runtime, 'reconcile: true')
|
||||
&& str_contains($runtime, '${path}/reconcile')
|
||||
&& str_contains($runtime, '结果待核对')
|
||||
&& str_contains($runtime, 'clearPowerOperationKey'),
|
||||
'Power UI must persist one bounded idempotency key and surface uncertain Agent results without retrying.');
|
||||
|
||||
fwrite(STDOUT, "Cloud Agent action cutover contract passed.\n");
|
||||
@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
// Dependency-free source/behavior contract for the host-local Agent key
|
||||
// resolver. It intentionally does not require PHP/Composer in the audit
|
||||
// environment.
|
||||
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentSecretResolver.php';
|
||||
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentFileSecretResolver.php';
|
||||
|
||||
use App\Services\Cloud\CloudAgentFileSecretResolver;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$rawKey = str_repeat('k', 32);
|
||||
$encodedKey = base64_encode($rawKey);
|
||||
$files = [
|
||||
'/run/virt-cloud/agents/agent-103.hmac' => $encodedKey . "\n",
|
||||
'/run/virt-cloud/agents/agent-103.ca.pem' => 'CA',
|
||||
'/run/virt-cloud/agents/agent-103.crt' => 'CERT',
|
||||
'/run/virt-cloud/agents/agent-103.key' => 'KEY',
|
||||
];
|
||||
$resolver = new CloudAgentFileSecretResolver(
|
||||
'/run/virt-cloud/agents',
|
||||
static fn (string $path): ?string => $files[$path] ?? null,
|
||||
);
|
||||
$material = $resolver->resolve('agent-103');
|
||||
$assert(is_array($material) && hash_equals($rawKey, $material['hmac_key'] ?? ''),
|
||||
'The resolver did not decode the canonical base64 key into raw bytes.');
|
||||
$assert(($material['cert_file'] ?? '') === '/run/virt-cloud/agents/agent-103.crt'
|
||||
&& ($material['key_file'] ?? '') === '/run/virt-cloud/agents/agent-103.key',
|
||||
'The resolver returned unexpected TLS paths.');
|
||||
|
||||
foreach (['agent/103', '../agent-103', ' agent-103', '', 'agent-103\n'] as $invalid) {
|
||||
$assert($resolver->resolve($invalid) === null,
|
||||
'Invalid Agent ID was accepted: ' . json_encode($invalid));
|
||||
}
|
||||
|
||||
$badFiles = $files;
|
||||
$badFiles['/run/virt-cloud/agents/agent-103.hmac'] = $encodedKey . " \n";
|
||||
$bad = new CloudAgentFileSecretResolver(
|
||||
'/run/virt-cloud/agents',
|
||||
static fn (string $path): ?string => $badFiles[$path] ?? null,
|
||||
);
|
||||
$assert($bad->resolve('agent-103') === null,
|
||||
'The resolver accepted ambiguous whitespace in the key file.');
|
||||
|
||||
$nonCanonical = $files;
|
||||
$nonCanonical['/run/virt-cloud/agents/agent-103.hmac'] = rtrim($encodedKey, '=') . "\n";
|
||||
$nonCanonicalResolver = new CloudAgentFileSecretResolver(
|
||||
'/run/virt-cloud/agents',
|
||||
static fn (string $path): ?string => $nonCanonical[$path] ?? null,
|
||||
);
|
||||
$assert($nonCanonicalResolver->resolve('agent-103') === null,
|
||||
'The resolver accepted non-canonical Base64 padding.');
|
||||
|
||||
foreach (['relative/agents', '/', '/run//virt-cloud/agents', '/run/../agents', '/run/virt cloud/agents'] as $directory) {
|
||||
try {
|
||||
new CloudAgentFileSecretResolver($directory);
|
||||
throw new RuntimeException('Unsafe secret directory was accepted: ' . $directory);
|
||||
} catch (InvalidArgumentException) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
$source = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentFileSecretResolver.php');
|
||||
$assert(is_string($source)
|
||||
&& str_contains($source, 'base64_decode')
|
||||
&& str_contains($source, 'lstat')
|
||||
&& str_contains($source, 'validAbsoluteDirectory')
|
||||
&& str_contains($source, 'hash_equals')
|
||||
&& str_contains($source, 'CloudAgentSecretResolver')
|
||||
&& !str_contains($source, 'CloudSecrets')
|
||||
&& !str_contains($source, 'CloudEngineClient')
|
||||
&& !str_contains($source, 'ssh'),
|
||||
'The file resolver crossed the legacy secret or SSH boundary.');
|
||||
|
||||
fwrite(STDOUT, "Cloud Agent file secret resolver contract passed.\n");
|
||||
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
// Source-level contract for the explicit Agent operation read-back endpoint.
|
||||
// The panel development shell may not have PHP/Composer, so the executable
|
||||
// integration test belongs in panel CI; these assertions still prevent a
|
||||
// future change from turning reconciliation into a mutation replay or an
|
||||
// unauthorised generic Agent proxy.
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$value = file_get_contents($root . '/' . $path);
|
||||
if (!is_string($value)) {
|
||||
throw new RuntimeException('Missing Agent reconcile contract source: ' . $path);
|
||||
}
|
||||
return $value;
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$service = $read('app/Services/Cloud/CloudAgentOperationReconcileService.php');
|
||||
$controller = $read('app/Controllers/CloudApiController.php');
|
||||
$handle = $read('app/Services/Cloud/CloudAgentHandle.php');
|
||||
$routes = $read('config/routes_cloud.php');
|
||||
$middleware = $read('app/Middleware/CloudApi.php');
|
||||
|
||||
foreach ([
|
||||
'CloudAgentOperationEnvelope::fromResponse',
|
||||
'getOperation(',
|
||||
'->reconcile(',
|
||||
"'reconcile'",
|
||||
'CloudAgentOperationRepository',
|
||||
'->finalize(',
|
||||
'agent_reconcile_result_invalid',
|
||||
'hash_equals',
|
||||
'resolveReadOnly',
|
||||
"->where('host_id'",
|
||||
"->where('id'",
|
||||
'instance_uuid',
|
||||
"record['target']",
|
||||
] as $required) {
|
||||
$assert(str_contains($service, $required),
|
||||
'Reconcile service is missing a required safety boundary: ' . $required);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'CloudEngineClient', 'CloudJobService', 'CloudWorkerService',
|
||||
'shell_exec', 'curl_exec', 'CloudAgentVmGateway', '->operation(',
|
||||
] as $forbidden) {
|
||||
$assert(!str_contains($service, $forbidden),
|
||||
'Reconcile service crossed a legacy or mutation boundary: ' . $forbidden);
|
||||
}
|
||||
|
||||
$uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
|
||||
$assert(str_contains($routes, "/jobs/{id:{$uuid}}/reconcile")
|
||||
&& str_contains($routes, 'CloudApiController:reconcileJob'),
|
||||
'The explicit UUID reconcile route is missing.');
|
||||
$assert(str_contains($middleware, '/api/v1/jobs/[0-9a-f]{8}-[0-9a-f]{4}')
|
||||
&& str_contains($middleware, '/reconcile$'),
|
||||
'The reconcile route is not classified as database-only by CloudApi middleware.');
|
||||
|
||||
$methodOffset = strpos($controller, 'public function reconcileJob(');
|
||||
$assert($methodOffset !== false, 'CloudApiController has no reconcileJob endpoint.');
|
||||
$method = substr($controller, $methodOffset);
|
||||
$assert(str_contains($method, 'CloudAgentOperationIdentity::validateUuid')
|
||||
&& str_contains($method, 'CloudAgentOperationReconcileService')
|
||||
&& str_contains($method, 'CloudAgentOperationStatusService::forActor')
|
||||
&& str_contains($method, "=== 'uncertain' ? 202 : 200"),
|
||||
'reconcileJob does not validate, authorize through the service, and project the safe status DTO.');
|
||||
$assert(str_contains($handle, 'public function reconcile(')
|
||||
&& str_contains($handle, 'typed read-back endpoint')
|
||||
&& !str_contains($handle, "if (\$this->readOnly) {\n throw new CloudError('降级宿主机 Agent 仅允许只读观察', 503);\n }\n return \$this->client->reconcile"),
|
||||
'A degraded read-only Agent handle must keep the non-replaying reconcile endpoint available.');
|
||||
|
||||
fwrite(STDOUT, "Cloud Agent operation reconcile contract passed.\n");
|
||||
@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
// Dependency-free contract for the administrator health cutover. The runtime
|
||||
// PHP test suite exercises the real registry, mTLS and database adapters; this
|
||||
// source guard runs in the lightweight audit shell where PHP/Composer may be
|
||||
// unavailable.
|
||||
$root = dirname(__DIR__);
|
||||
$runtime = file_get_contents($root . '/app/Services/Cloud/CloudRuntimeHealthService.php');
|
||||
$registry = file_get_contents($root . '/app/Services/Cloud/CloudAgentRegistryHealthService.php');
|
||||
$javascript = file_get_contents($root . '/public/cloud/admin-operations.js');
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$assert(is_string($runtime)
|
||||
&& str_contains($runtime, 'CloudAgentRegistryHealthService::fromConfig()')
|
||||
&& str_contains($runtime, "\$this->check('engine', 'Go Agent'")
|
||||
&& !str_contains($runtime, 'CloudEngineClient')
|
||||
&& !str_contains($runtime, 'shell_exec')
|
||||
&& !str_contains($runtime, 'ssh'),
|
||||
'Runtime health still depends on the legacy Engine/SSH transport.');
|
||||
$assert(is_string($registry)
|
||||
&& str_contains($registry, 'fromConfig()')
|
||||
&& str_contains($registry, 'client_certificate_fingerprint')
|
||||
&& str_contains($registry, '$fingerprint'),
|
||||
'Agent health registry lost fresh configuration or certificate pinning.');
|
||||
$assert(is_string($javascript)
|
||||
&& str_contains($javascript, 'Agent liveness')
|
||||
&& !str_contains($javascript, '引擎连通不代表'),
|
||||
'Administrator health UI still describes the retired Engine probe.');
|
||||
|
||||
fwrite(STDOUT, "Cloud Agent runtime health contract passed.\n");
|
||||
@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
// The list/detail page must not open the retired Python Engine merely to
|
||||
// decorate a VM row. Live=1 status polling has a separate typed Agent seam;
|
||||
// these two broad page paths are deliberately cache-first and get their
|
||||
// observations from CloudInstanceRuntimeSyncService.
|
||||
$source = file_get_contents(dirname(__DIR__) . '/app/Controllers/CloudApiController.php');
|
||||
if (!is_string($source)) {
|
||||
throw new RuntimeException('CloudApiController source is missing.');
|
||||
}
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$start = strpos($source, 'private function vmListContexts(');
|
||||
$end = strpos($source, ' public function vms(', $start === false ? 0 : $start);
|
||||
$list = ($start !== false && $end !== false) ? substr($source, $start, $end - $start) : '';
|
||||
$assert(str_contains($list, 'CloudInstanceRuntimeService::forInstances')
|
||||
&& str_contains($list, 'state_fresh')
|
||||
&& str_contains($list, 'host unavailable'),
|
||||
'VM list context no longer uses the bounded Go-Agent-fed runtime cache.');
|
||||
foreach (['CloudEngineClient', '->host(', 'vms/'] as $forbidden) {
|
||||
$assert(!str_contains($list, $forbidden),
|
||||
'VM list context still contains a legacy Engine read: ' . $forbidden);
|
||||
}
|
||||
|
||||
$start = strpos($source, 'private function vmData(');
|
||||
$end = strpos($source, ' public function vms(', $start === false ? 0 : $start);
|
||||
$detail = ($start !== false && $end !== false) ? substr($source, $start, $end - $start) : '';
|
||||
$assert(str_contains($detail, 'CloudInstanceRuntimeService::forInstances')
|
||||
&& str_contains($detail, 'state_fresh'),
|
||||
'VM detail does not use the runtime cache when no preloaded context exists.');
|
||||
foreach (['CloudEngineClient', '->host(', 'vms/'] as $forbidden) {
|
||||
$assert(!str_contains($detail, $forbidden),
|
||||
'VM detail still contains a legacy Engine read: ' . $forbidden);
|
||||
}
|
||||
|
||||
fwrite(STDOUT, "Cloud API VM cache cutover contract passed.\n");
|
||||
Loading…
Reference in New Issue