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.
1157 lines
45 KiB
PHP
1157 lines
45 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudInstance;
|
|
use App\Models\CloudInstanceFirewallVersion;
|
|
use App\Models\CloudInstanceSnapshot;
|
|
use App\Models\CloudHostStorageConfiguration;
|
|
use App\Models\CloudJob;
|
|
use App\Models\CloudRescueTemplateDeletion;
|
|
use App\Models\CloudRescueTemplateImport;
|
|
use App\Models\CloudTemplate;
|
|
use App\Models\CloudTemplateReplica;
|
|
use App\Models\CloudUserIso;
|
|
use App\Models\CloudUserIsoReplica;
|
|
|
|
/** Rebuilds the immutable Agent Journal identity from PHP-owned durable state. */
|
|
final class CloudOperationRecoveryIdentity
|
|
{
|
|
private const VERSION = 1;
|
|
private const KEY = '_operation_identity';
|
|
private const UUID_PATTERN =
|
|
'/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/D';
|
|
private const CATALOG_ID_PATTERN = '/^[a-f0-9]{32}$/D';
|
|
private const TEMPLATE_ID_PATTERN =
|
|
'/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D';
|
|
|
|
/**
|
|
* Every PHP job kind that crosses an Agent mutation endpoint must carry an
|
|
* immutable Journal identity. This is intentionally broader than
|
|
* CloudOperationRecoveryPolicy: create and host storage keep their existing
|
|
* financial/operator recovery rules, but their responses are no less
|
|
* security-sensitive than automatically recoverable VM/catalog jobs.
|
|
*/
|
|
public static function supports(string $kind): bool
|
|
{
|
|
return CloudOperationRecoveryPolicy::identityScope($kind) !== null;
|
|
}
|
|
|
|
/**
|
|
* @return array{action:string,resource_id:string,request_fingerprint:string}
|
|
*/
|
|
public static function expected(
|
|
CloudJob $job,
|
|
bool $forAppliedEffect = false
|
|
): array {
|
|
try {
|
|
$payload = CloudSecrets::decrypt(
|
|
(string) $job->sealed_payload,
|
|
'job-payload'
|
|
);
|
|
} catch (\Throwable $error) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务恢复请求无法解密',
|
|
409
|
|
);
|
|
}
|
|
if (!is_array($payload) || array_is_list($payload)) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务恢复请求结构无效',
|
|
409
|
|
);
|
|
}
|
|
|
|
$stored = self::stored($payload);
|
|
if ($stored !== null && self::isPreparedEscrow($job, $payload, $stored)) {
|
|
// prepareRecoveredEffect() may legitimately mutate or remove the
|
|
// catalog/instance row used for the original strict validation.
|
|
// Its encrypted prepare envelope therefore carries the immutable
|
|
// identity which was validated before that ledger mutation.
|
|
return $stored;
|
|
}
|
|
if ($stored !== null
|
|
&& (string) $job->phase === 'terminal'
|
|
&& in_array((string) $job->effect_resolution,
|
|
['applied', 'not_applied'], true)) {
|
|
// A resolved task intentionally keeps only this non-secret
|
|
// binding. Any surviving safeResult body is redacted audit data,
|
|
// not the original wire payload and must not be re-fingerprinted.
|
|
return $stored;
|
|
}
|
|
$hasRequest = is_string($payload['method'] ?? null)
|
|
&& is_string($payload['request_target'] ?? null)
|
|
&& is_array($payload['body'] ?? null);
|
|
if (!$hasRequest) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务缺少可重建的 Agent 请求',
|
|
409
|
|
);
|
|
}
|
|
|
|
$identity = self::expectedFromPayload(
|
|
$job,
|
|
$payload,
|
|
$forAppliedEffect
|
|
);
|
|
if ($stored !== null && !self::same($identity, $stored)) {
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'任务持久化操作身份与原请求不匹配',
|
|
409
|
|
);
|
|
}
|
|
return $identity;
|
|
}
|
|
|
|
/**
|
|
* @return array{action:string,resource_id:string,request_fingerprint:string}
|
|
*/
|
|
public static function expectedFromPayload(
|
|
CloudJob $job,
|
|
array $payload,
|
|
bool $forAppliedEffect = false
|
|
): array {
|
|
if (!self::supports((string) $job->kind)
|
|
|| (string) $job->execution_mode !== 'agent'
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
(string) $job->operation_id) !== 1
|
|
|| (int) $job->host_id < 1
|
|
|| array_is_list($payload)) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务不具备可恢复的 Agent 身份',
|
|
409
|
|
);
|
|
}
|
|
$method = strtoupper((string) ($payload['method'] ?? ''));
|
|
$target = $payload['request_target'] ?? null;
|
|
$body = $payload['body'] ?? null;
|
|
if (!in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)
|
|
|| !is_string($target) || !str_starts_with($target, '/v1/')
|
|
|| !is_array($body)
|
|
|| ($body !== [] && array_is_list($body))) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务中的 Agent 线上请求无效',
|
|
409
|
|
);
|
|
}
|
|
self::assertBodyOperation($job, $body);
|
|
|
|
$kind = (string) $job->kind;
|
|
$scope = CloudOperationRecoveryPolicy::identityScope($kind);
|
|
if ($scope === 'create') {
|
|
[$action, $resourceId] = self::createIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body,
|
|
$forAppliedEffect
|
|
);
|
|
} elseif ($scope === 'storage') {
|
|
[$action, $resourceId] = self::storageIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body
|
|
);
|
|
} elseif ($scope === 'instance') {
|
|
[$action, $resourceId] = self::instanceIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body,
|
|
$forAppliedEffect
|
|
);
|
|
} else {
|
|
[$action, $resourceId] = self::catalogIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body
|
|
);
|
|
}
|
|
if (!CloudOperationRecoveryPolicy::allowsAction($kind, $action)) {
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'任务种类与 Agent 操作契约不匹配',
|
|
409
|
|
);
|
|
}
|
|
$wire = self::wireBody($kind, $body);
|
|
$encoded = json_encode(
|
|
$wire === [] ? (object) [] : $wire,
|
|
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE
|
|
);
|
|
return [
|
|
'action' => $action,
|
|
'resource_id' => $resourceId,
|
|
'request_fingerprint' => hash(
|
|
'sha256',
|
|
$method . "\n" . $target . "\n" . $encoded
|
|
),
|
|
];
|
|
}
|
|
|
|
/** Exact body translation used by both dispatch and identity recovery. */
|
|
public static function wireBody(string $kind, array $body): array
|
|
{
|
|
if ($kind === 'action' && ($body['action'] ?? null) === 'poweroff') {
|
|
$body['action'] = 'destroy';
|
|
}
|
|
return $body;
|
|
}
|
|
|
|
/** @param array{action:string,resource_id:string,request_fingerprint:string} $identity */
|
|
public static function persisted(array $identity): array
|
|
{
|
|
self::assertIdentityShape($identity);
|
|
return [
|
|
'version' => self::VERSION,
|
|
'action' => $identity['action'],
|
|
'resource_id' => $identity['resource_id'],
|
|
'request_fingerprint' => $identity['request_fingerprint'],
|
|
];
|
|
}
|
|
|
|
public static function payloadKey(): string
|
|
{
|
|
return self::KEY;
|
|
}
|
|
|
|
public static function same(array $expected, array $actual): bool
|
|
{
|
|
foreach (['action', 'resource_id', 'request_fingerprint'] as $key) {
|
|
if (!is_string($expected[$key] ?? null)
|
|
|| !is_string($actual[$key] ?? null)
|
|
|| !hash_equals($expected[$key], $actual[$key])) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public static function assertMatches(array $expected, array $actual): void
|
|
{
|
|
if (!self::same($expected, $actual)) {
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'Agent 操作身份与当前任务不匹配',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
|
|
private static function instanceIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body,
|
|
bool $forAppliedEffect
|
|
): array {
|
|
$instanceId = filter_var($job->instance_id, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]);
|
|
$instance = $instanceId === false ? null
|
|
: CloudInstance::find((int) $instanceId);
|
|
if ($instance === null
|
|
|| (int) $instance->host_id !== (int) $job->host_id
|
|
|| preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $instance->uuid)) !== 1
|
|
|| (int) ($payload['owner_id'] ?? 0)
|
|
!== (int) $instance->user_id
|
|
|| ((int) $job->user_id !== (int) $instance->user_id
|
|
&& ($payload['can_manage'] ?? false) !== true)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'任务与实例所属人、宿主机或 UUID 账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
$kind = (string) $job->kind;
|
|
if ((string) $instance->status === 'deleted'
|
|
&& !in_array($kind,
|
|
['delete', 'delete_force', 'expiry_delete'], true)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'实例状态与原操作请求矛盾',
|
|
409
|
|
);
|
|
}
|
|
$uuid = strtolower((string) $instance->uuid);
|
|
$base = '/v1/vms/' . rawurlencode($uuid);
|
|
$action = match ($kind) {
|
|
'action' => self::powerAction($method, $target, $base, $body),
|
|
'reinstall' => self::reinstallAction(
|
|
$job, $payload, $method, $target, $base, $body,
|
|
$forAppliedEffect
|
|
),
|
|
'rescue' => self::rescueAction($method, $target, $base, $body),
|
|
'delete', 'expiry_delete' => self::deleteAction(
|
|
$method, $target, $base, $body
|
|
),
|
|
'delete_force' => self::forceDeleteAction(
|
|
$job, $payload, $method, $target, $base, $body
|
|
),
|
|
'network_change' => self::networkChangeAction(
|
|
$method, $target, $base, $body
|
|
),
|
|
'instance_settings' => self::settingsAction(
|
|
$method, $target, $base, $body
|
|
),
|
|
'snapshot_create', 'snapshot_restore', 'snapshot_delete' =>
|
|
self::snapshotAction(
|
|
$job, $payload, $instance, $method, $target, $base, $body
|
|
),
|
|
'firewall_apply' => self::firewallAction(
|
|
$job, $payload, $instance, $method, $target, $base, $body
|
|
),
|
|
'service_suspend' => self::policyAction(
|
|
$method, $target, $base . '/service/suspend', $body,
|
|
['operation_id', 'reason'],
|
|
($body['reason'] ?? null) === 'purge',
|
|
'service-suspend'
|
|
),
|
|
'network_suspend' => self::policyAction(
|
|
$method, $target, $base . '/network/suspend', $body,
|
|
['operation_id', 'reason'],
|
|
is_string($body['reason'] ?? null)
|
|
&& in_array($body['reason'], ['traffic', 'expired'], true),
|
|
'network-suspend'
|
|
),
|
|
'network_resume' => self::policyAction(
|
|
$method, $target, $base . '/network/resume', $body,
|
|
['operation_id'],
|
|
true,
|
|
'network-resume'
|
|
),
|
|
default => throw new CloudRecoveryPayloadUnavailable(
|
|
'实例任务类型没有恢复身份映射', 409
|
|
),
|
|
};
|
|
return [$action, $uuid];
|
|
}
|
|
|
|
private static function createIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body,
|
|
bool $forAppliedEffect
|
|
): array {
|
|
self::expectRequest($method, $target, 'POST', '/v1/vms');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu',
|
|
'memory_mib', 'disk_gib', 'bandwidth_mbps', 'network',
|
|
'template_id', 'template_revision', 'template_generation_token',
|
|
'startup_script', 'hostname', 'guest_ssh_public_key',
|
|
'root_password', 'public_pool_key', 'public_pool_cidr',
|
|
'public_ip_cidr', 'gateway', 'dns_servers',
|
|
'platform_network_policy_snapshot',
|
|
]);
|
|
$resourceId = self::operationUuid((string) $job->operation_id);
|
|
$requestedUuid = $body['uuid'] ?? null;
|
|
$integers = ['vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps',
|
|
'template_revision'];
|
|
$validIntegers = true;
|
|
foreach ($integers as $field) {
|
|
if (filter_var(
|
|
$body[$field] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
) === false) {
|
|
$validIntegers = false;
|
|
break;
|
|
}
|
|
}
|
|
if (($body['source'] ?? null) !== 'cloud'
|
|
|| !is_string($body['name'] ?? null)
|
|
|| preg_match('/^[A-Za-z0-9_.-]{1,80}$/D', $body['name']) !== 1
|
|
|| !$validIntegers
|
|
|| !is_string($body['template_id'] ?? null)
|
|
|| preg_match(self::TEMPLATE_ID_PATTERN,
|
|
$body['template_id']) !== 1
|
|
|| !is_string($body['template_generation_token'] ?? null)
|
|
|| preg_match(self::CATALOG_ID_PATTERN,
|
|
$body['template_generation_token']) !== 1
|
|
|| !is_string($body['network'] ?? null)
|
|
|| trim($body['network']) === ''
|
|
|| !is_string($body['public_pool_key'] ?? null)
|
|
|| preg_match(self::CATALOG_ID_PATTERN,
|
|
$body['public_pool_key']) !== 1
|
|
|| !is_string($body['public_pool_cidr'] ?? null)
|
|
|| !is_string($body['public_ip_cidr'] ?? null)
|
|
|| !is_string($body['gateway'] ?? null)
|
|
|| !is_array($body['dns_servers'] ?? null)
|
|
|| !array_is_list($body['dns_servers'])
|
|
|| $body['dns_servers'] === []
|
|
|| !is_array($body['platform_network_policy_snapshot'] ?? null)
|
|
|| array_is_list($body['platform_network_policy_snapshot'])
|
|
|| ($requestedUuid !== null
|
|
&& (!is_string($requestedUuid)
|
|
|| !hash_equals($resourceId,
|
|
strtolower($requestedUuid))))
|
|
|| (int) $job->user_id < 1
|
|
|| $job->order_id === null
|
|
|| (int) $job->order_id < 1
|
|
|| array_key_exists('owner_id', $payload)) {
|
|
self::invalidPayload('创建实例请求与任务账本不匹配');
|
|
}
|
|
$metadata = $payload['template_metadata'] ?? null;
|
|
if (!is_array($metadata) || array_is_list($metadata)
|
|
|| ($metadata['template_id'] ?? null)
|
|
!== $body['template_id']
|
|
|| ($metadata['os_source'] ?? null) !== 'cloud_template'
|
|
|| !is_string($metadata['os_name'] ?? null)
|
|
|| trim($metadata['os_name']) === ''
|
|
|| ($metadata['login_name'] ?? null) !== 'root') {
|
|
self::invalidPayload('创建实例任务缺少可信模板快照');
|
|
}
|
|
if ($forAppliedEffect) {
|
|
self::assertCreateAppliedEscrow($payload, $body);
|
|
}
|
|
return ['create-vm', $resourceId];
|
|
}
|
|
|
|
private static function assertCreateAppliedEscrow(
|
|
array $payload,
|
|
array $body
|
|
): void {
|
|
$credential = $payload['credential'] ?? null;
|
|
$publicKey = $body['guest_ssh_public_key'] ?? null;
|
|
$hasKey = is_string($publicKey) && $publicKey !== '';
|
|
if (!is_array($credential) || array_is_list($credential)
|
|
|| array_diff(array_keys($credential), [
|
|
'password', 'login_name', 'auth_mode',
|
|
]) !== []
|
|
|| ($credential['login_name'] ?? null) !== 'root'
|
|
|| !is_string($credential['password'] ?? null)
|
|
|| !is_string($body['root_password'] ?? null)
|
|
|| !hash_equals(
|
|
(string) $body['root_password'],
|
|
(string) $credential['password']
|
|
)
|
|
|| ($credential['auth_mode'] ?? null)
|
|
!== ($hasKey ? 'password_and_key' : 'password')) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'创建成功恢复缺少完整且匹配的实例凭据',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
|
|
private static function storageIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'POST',
|
|
'/v1/storage/configuration'
|
|
);
|
|
$fields = [
|
|
'managed_directory', 'template_directory', 'seed_directory',
|
|
'user_iso_directory', 'rescue_directory',
|
|
];
|
|
self::assertAllowedBody($body, array_merge(
|
|
['operation_id'],
|
|
$fields
|
|
));
|
|
$revision = filter_var(
|
|
$payload['storage_revision'] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
$row = CloudHostStorageConfiguration::find((int) $job->host_id);
|
|
if (($payload['can_manage'] ?? null) !== true
|
|
|| $revision === false
|
|
|| $row === null
|
|
|| (int) $row->revision !== (int) $revision
|
|
|| (int) ($row->job_id ?? 0) !== (int) $job->id
|
|
|| !hash_equals((string) $job->operation_id,
|
|
(string) ($row->operation_id ?? ''))) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'宿主机存储任务与配置账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
$paths = [];
|
|
foreach ($fields as $field) {
|
|
$value = $body[$field] ?? null;
|
|
if (!is_string($value)
|
|
|| preg_match(
|
|
'#^/(?:[A-Za-z0-9._-]+)(?:/[A-Za-z0-9._-]+)*$#D',
|
|
$value
|
|
) !== 1
|
|
|| !hash_equals((string) $row->{$field}, $value)) {
|
|
self::invalidPayload(
|
|
'宿主机存储请求与配置账本不匹配'
|
|
);
|
|
}
|
|
$paths[] = $value;
|
|
}
|
|
foreach ($paths as $leftIndex => $left) {
|
|
foreach (array_slice($paths, $leftIndex + 1) as $right) {
|
|
if ($left === $right
|
|
|| str_starts_with($left, $right . '/')
|
|
|| str_starts_with($right, $left . '/')) {
|
|
self::invalidPayload('宿主机存储目录存在重叠');
|
|
}
|
|
}
|
|
}
|
|
return ['configure-storage', 'host-storage'];
|
|
}
|
|
|
|
/** Exact Go agent/api.operationUUID derivation for body-omitted UUIDs. */
|
|
private static function operationUuid(string $operationId): string
|
|
{
|
|
$digest = hash(
|
|
'sha256',
|
|
'virt-cloud-operation:' . $operationId,
|
|
true
|
|
);
|
|
$digest[6] = chr((ord($digest[6]) & 0x0f) | 0x50);
|
|
$digest[8] = chr((ord($digest[8]) & 0x3f) | 0x80);
|
|
$hex = bin2hex(substr($digest, 0, 16));
|
|
return substr($hex, 0, 8) . '-'
|
|
. substr($hex, 8, 4) . '-'
|
|
. substr($hex, 12, 4) . '-'
|
|
. substr($hex, 16, 4) . '-'
|
|
. substr($hex, 20, 12);
|
|
}
|
|
|
|
private static function powerAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/actions');
|
|
self::assertAllowedBody($body, ['operation_id', 'action']);
|
|
$action = $body['action'] ?? null;
|
|
if (!is_string($action)
|
|
|| !in_array($action,
|
|
['start', 'shutdown', 'reboot', 'reset', 'poweroff'], true)) {
|
|
self::invalidPayload('电源操作请求无效');
|
|
}
|
|
return 'power-' . ($action === 'poweroff' ? 'destroy' : $action);
|
|
}
|
|
|
|
private static function reinstallAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body,
|
|
bool $forAppliedEffect
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/reinstall');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'template_id', 'template_revision',
|
|
'template_generation_token', 'preserve_data', 'root_password',
|
|
'ssh_public_key',
|
|
]);
|
|
$templateId = $body['template_id'] ?? null;
|
|
if (!is_string($templateId)
|
|
|| preg_match(self::TEMPLATE_ID_PATTERN, $templateId) !== 1
|
|
|| filter_var($body['template_revision'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false
|
|
|| !is_string($body['template_generation_token'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
$body['template_generation_token']) !== 1) {
|
|
self::invalidPayload('重装请求中的模板快照无效');
|
|
}
|
|
if ($forAppliedEffect) {
|
|
self::assertReinstallAppliedEscrow($job, $payload, $body);
|
|
}
|
|
return 'reinstall-vm';
|
|
}
|
|
|
|
private static function assertReinstallAppliedEscrow(
|
|
CloudJob $job,
|
|
array $payload,
|
|
array $body
|
|
): void {
|
|
$credential = $payload['credential'] ?? null;
|
|
$metadata = $payload['template_metadata'] ?? null;
|
|
$hasKey = is_string($body['ssh_public_key'] ?? null)
|
|
&& $body['ssh_public_key'] !== '';
|
|
if (!is_array($credential) || array_is_list($credential)
|
|
|| array_diff(array_keys($credential), [
|
|
'password', 'login_name', 'auth_mode',
|
|
]) !== []
|
|
|| ($credential['login_name'] ?? null) !== 'root'
|
|
|| !is_string($credential['password'] ?? null)
|
|
|| ($credential['password'] ?? null)
|
|
!== ($body['root_password'] ?? null)
|
|
|| ($credential['auth_mode'] ?? null)
|
|
!== ($hasKey ? 'password_and_key' : 'password')
|
|
|| !is_array($metadata) || array_is_list($metadata)
|
|
|| array_diff(array_keys($metadata), [
|
|
'template_id', 'os_source', 'os_name', 'login_name',
|
|
]) !== []
|
|
|| ($metadata['template_id'] ?? null)
|
|
!== ($body['template_id'] ?? null)
|
|
|| ($metadata['os_source'] ?? null) !== 'cloud_template'
|
|
|| !is_string($metadata['os_name'] ?? null)
|
|
|| trim($metadata['os_name']) === ''
|
|
|| ($metadata['login_name'] ?? null) !== 'root') {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'重装成功恢复缺少完整凭据或可信模板快照',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
|
|
private static function rescueAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
if ($method !== 'POST') {
|
|
self::invalidPayload('救援操作请求方法无效');
|
|
}
|
|
if ($target === $base . '/rescue/enter') {
|
|
self::assertAllowedBody($body, ['operation_id', 'template_id']);
|
|
if (!is_string($body['template_id'] ?? null)
|
|
|| preg_match(self::TEMPLATE_ID_PATTERN,
|
|
$body['template_id']) !== 1) {
|
|
self::invalidPayload('救援镜像标识无效');
|
|
}
|
|
return 'enter-rescue';
|
|
}
|
|
if ($target === $base . '/rescue/force-start') {
|
|
self::assertAllowedBody($body, ['operation_id', 'ack_data_loss']);
|
|
if (($body['ack_data_loss'] ?? null) !== true) {
|
|
self::invalidPayload('救援强制启动确认无效');
|
|
}
|
|
return 'force-start-rescue';
|
|
}
|
|
if ($target === $base . '/rescue/exit') {
|
|
self::assertAllowedBody($body,
|
|
['operation_id', 'network_suspended']);
|
|
if (!is_bool($body['network_suspended'] ?? null)) {
|
|
self::invalidPayload('救援退出网络状态无效');
|
|
}
|
|
return 'exit-rescue:'
|
|
. ($body['network_suspended'] ? 'suspended' : 'connected');
|
|
}
|
|
self::invalidPayload('救援操作路径无效');
|
|
}
|
|
|
|
private static function deleteAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'DELETE', $base);
|
|
self::assertAllowedBody($body,
|
|
['operation_id', 'remove_managed_disks']);
|
|
if (($body['remove_managed_disks'] ?? null) !== true) {
|
|
self::invalidPayload('删除请求缺少托管磁盘清理确认');
|
|
}
|
|
return 'delete-vm';
|
|
}
|
|
|
|
private static function forceDeleteAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/force-delete');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'prior_operation_id', 'ack_data_loss',
|
|
'remove_managed_disks',
|
|
]);
|
|
if (($body['operation_id'] ?? null) !== (string) $job->operation_id
|
|
|| !is_string($body['prior_operation_id'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
$body['prior_operation_id']) !== 1
|
|
|| ($payload['prior_operation_id'] ?? null)
|
|
!== $body['prior_operation_id']
|
|
|| ($body['ack_data_loss'] ?? null) !== true
|
|
|| ($body['remove_managed_disks'] ?? null) !== true) {
|
|
self::invalidPayload('强制删除请求关联无效');
|
|
}
|
|
return 'force-delete-vm';
|
|
}
|
|
|
|
private static function networkChangeAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/network');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'network', 'public_pool_key', 'public_pool_cidr',
|
|
'public_ip_cidr', 'gateway', 'dns_servers', 'confirm_restart',
|
|
]);
|
|
if (($body['confirm_restart'] ?? null) !== true
|
|
|| !is_string($body['network'] ?? null)
|
|
|| !is_string($body['public_pool_key'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
$body['public_pool_key']) !== 1
|
|
|| !is_string($body['public_pool_cidr'] ?? null)
|
|
|| !is_string($body['public_ip_cidr'] ?? null)
|
|
|| !is_string($body['gateway'] ?? null)
|
|
|| !is_array($body['dns_servers'] ?? null)
|
|
|| !array_is_list($body['dns_servers'])) {
|
|
self::invalidPayload('公网 IP 变更请求无效');
|
|
}
|
|
return 'change-network';
|
|
}
|
|
|
|
private static function settingsAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
if (!in_array($method, ['POST', 'PATCH'], true)
|
|
|| $target !== $base . '/settings') {
|
|
self::invalidPayload('实例设置请求路径无效');
|
|
}
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'hostname', 'root_password', 'ssh_public_key',
|
|
'confirm_restart',
|
|
]);
|
|
$changed = array_intersect(
|
|
array_keys($body),
|
|
['hostname', 'root_password', 'ssh_public_key']
|
|
);
|
|
if (($body['confirm_restart'] ?? null) !== true || $changed === []) {
|
|
self::invalidPayload('实例设置恢复字段无效');
|
|
}
|
|
return 'update-settings';
|
|
}
|
|
|
|
private static function snapshotAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
CloudInstance $instance,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
$snapshotId = filter_var($job->snapshot_id, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]);
|
|
$snapshot = $snapshotId === false ? null
|
|
: CloudInstanceSnapshot::find((int) $snapshotId);
|
|
$key = $payload['snapshot_key'] ?? null;
|
|
if ($snapshot === null
|
|
|| (int) $snapshot->instance_id !== (int) $instance->id
|
|
|| (int) $snapshot->host_id !== (int) $job->host_id
|
|
|| (int) $snapshot->user_id !== (int) $instance->user_id
|
|
|| !is_string($key)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $key) !== 1
|
|
|| !hash_equals((string) $snapshot->snapshot_key, $key)
|
|
|| !hash_equals((string) $snapshot->last_operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'快照任务与实例目录账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
if ((string) $job->kind === 'snapshot_create') {
|
|
self::expectRequest($method, $target, 'POST', $base . '/snapshots');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'snapshot_id', 'snapshot_key', 'name',
|
|
'description', 'quiesce', 'consistency_mode',
|
|
]);
|
|
$consistency = $body['consistency_mode'] ?? null;
|
|
if (($body['snapshot_key'] ?? null) !== $key
|
|
|| !in_array($consistency, ['filesystem', 'crash'], true)) {
|
|
self::invalidPayload('创建快照请求无效');
|
|
}
|
|
return 'create-snapshot:' . $key . ':' . $consistency;
|
|
}
|
|
self::assertAllowedBody($body, ['operation_id']);
|
|
if ((string) $job->kind === 'snapshot_restore') {
|
|
self::expectRequest($method, $target, 'POST',
|
|
$base . '/snapshots/' . rawurlencode($key) . '/restore');
|
|
return 'restore-snapshot:' . $key;
|
|
}
|
|
self::expectRequest($method, $target, 'DELETE',
|
|
$base . '/snapshots/' . rawurlencode($key));
|
|
return 'delete-snapshot:' . $key;
|
|
}
|
|
|
|
private static function firewallAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
CloudInstance $instance,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'PUT', $base . '/firewall');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'revision', 'default_in', 'default_out',
|
|
'policy_digest', 'rules',
|
|
]);
|
|
$versionId = filter_var($payload['firewall_version_id'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$version = $versionId === false ? null
|
|
: CloudInstanceFirewallVersion::find((int) $versionId);
|
|
if ($version === null
|
|
|| (int) $version->instance_id !== (int) $instance->id
|
|
|| (int) $version->job_id !== (int) $job->id
|
|
|| !hash_equals((string) $version->operation_id,
|
|
(string) $job->operation_id)
|
|
|| (int) $version->revision !== (int) ($body['revision'] ?? 0)
|
|
|| (int) ($payload['firewall_revision'] ?? 0)
|
|
!== (int) $version->revision
|
|
|| !is_string($body['policy_digest'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
$body['policy_digest']) !== 1
|
|
|| ($payload['agent_firewall_policy_digest'] ?? null)
|
|
!== $body['policy_digest']
|
|
|| !is_array($body['rules'] ?? null)
|
|
|| !array_is_list($body['rules'])) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'防火墙任务与版本账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
return 'apply-firewall';
|
|
}
|
|
|
|
private static function policyAction(
|
|
string $method,
|
|
string $target,
|
|
string $expectedTarget,
|
|
array $body,
|
|
array $allowed,
|
|
bool $valid,
|
|
string $action
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $expectedTarget);
|
|
self::assertAllowedBody($body, $allowed);
|
|
if (!$valid) {
|
|
self::invalidPayload('系统策略请求无效');
|
|
}
|
|
return $action;
|
|
}
|
|
|
|
private static function catalogIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
return match ((string) $job->kind) {
|
|
'template_import_replica', 'template_metadata_replica',
|
|
'template_delete_replica' => self::templateIdentity(
|
|
$job, $payload, $method, $target, $body
|
|
),
|
|
'rescue_template_import', 'rescue_template_delete' =>
|
|
self::rescueTemplateIdentity(
|
|
$job, $payload, $method, $target, $body
|
|
),
|
|
'user_iso_import_replica', 'user_iso_delete_replica' =>
|
|
self::userIsoIdentity(
|
|
$job, $payload, $method, $target, $body
|
|
),
|
|
default => throw new CloudRecoveryPayloadUnavailable(
|
|
'目录任务类型没有恢复身份映射', 409
|
|
),
|
|
};
|
|
}
|
|
|
|
private static function templateIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
$id = $payload['template_id'] ?? null;
|
|
$template = is_string($id) ? CloudTemplate::find($id) : null;
|
|
$replica = is_string($id) ? CloudTemplateReplica::where(
|
|
'host_id', (int) $job->host_id
|
|
)->where('template_id', $id)->first() : null;
|
|
$parent = $job->parent_job_id === null ? null
|
|
: CloudJob::find((int) $job->parent_job_id);
|
|
$expectedParent = [
|
|
'template_import_replica' => 'template_import',
|
|
'template_metadata_replica' => 'template_metadata_sync',
|
|
'template_delete_replica' => 'template_delete',
|
|
][(string) $job->kind];
|
|
if (!is_string($id)
|
|
|| preg_match(self::TEMPLATE_ID_PATTERN, $id) !== 1
|
|
|| $template === null || $replica === null || $parent === null
|
|
|| (string) $parent->kind !== $expectedParent
|
|
|| (int) $template->active_job_id !== (int) $parent->id
|
|
|| (int) $replica->job_id !== (int) $job->id
|
|
|| !hash_equals((string) $replica->operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'云镜像子任务与副本账本不匹配', 409
|
|
);
|
|
}
|
|
$resource = 'template:' . $id;
|
|
if ((string) $job->kind === 'template_import_replica') {
|
|
self::expectRequest($method, $target, 'POST', '/v1/templates');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'id', 'name', 'source_url', 'source_token',
|
|
'os_family', 'version', 'architecture', 'sha256', 'revision',
|
|
'generation_token',
|
|
]);
|
|
if (($body['id'] ?? null) !== $id
|
|
|| (int) ($body['revision'] ?? 0) !== (int) $replica->revision
|
|
|| ($body['generation_token'] ?? null)
|
|
!== (string) $replica->generation_token) {
|
|
self::invalidPayload('云镜像导入请求与副本不匹配');
|
|
}
|
|
return ['import-template', $resource];
|
|
}
|
|
if ((string) $job->kind === 'template_metadata_replica') {
|
|
self::expectRequest($method, $target, 'PATCH',
|
|
'/v1/templates/' . rawurlencode($id));
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'name', 'revision', 'generation_token',
|
|
]);
|
|
if ((int) ($body['revision'] ?? 0) !== (int) $template->revision
|
|
|| ($body['generation_token'] ?? null)
|
|
!== (string) $template->generation_token) {
|
|
self::invalidPayload('云镜像元数据请求与目录不匹配');
|
|
}
|
|
return ['update-template', $resource];
|
|
}
|
|
self::expectRequest($method, $target, 'DELETE',
|
|
'/v1/templates/' . rawurlencode($id));
|
|
self::assertAllowedBody($body, ['operation_id']);
|
|
return ['delete-template', $resource];
|
|
}
|
|
|
|
private static function rescueTemplateIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
$id = $payload['rescue_template_id'] ?? null;
|
|
if (!is_string($id)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $id) !== 1) {
|
|
self::invalidPayload('救援镜像任务标识无效');
|
|
}
|
|
if ((string) $job->kind === 'rescue_template_import') {
|
|
$row = CloudRescueTemplateImport::where(
|
|
'operation_id', (string) $job->operation_id
|
|
)->where('host_id', (int) $job->host_id)->first();
|
|
self::expectRequest($method, $target, 'POST',
|
|
'/v1/rescue-templates');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'id', 'name', 'source_url', 'source_token',
|
|
'sha256',
|
|
]);
|
|
if ($row === null || (int) $row->job_id !== (int) $job->id
|
|
|| ($body['id'] ?? null) !== $id
|
|
|| (string) $row->template_id !== $id
|
|
|| ($body['name'] ?? null) !== (string) $row->name) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'救援镜像导入任务与目录账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
return ['import-rescue-template', 'rescue-template:' . $id];
|
|
}
|
|
$row = CloudRescueTemplateDeletion::where(
|
|
'host_id', (int) $job->host_id
|
|
)->where('operation_id', (string) $job->operation_id)->first();
|
|
self::expectRequest($method, $target, 'DELETE',
|
|
'/v1/rescue-templates/' . rawurlencode($id));
|
|
self::assertAllowedBody($body, ['operation_id']);
|
|
if ($row === null || (int) $row->job_id !== (int) $job->id
|
|
|| (string) $row->template_id !== $id) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'救援镜像删除任务与目录账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
return ['delete-rescue-template', 'rescue-template:' . $id];
|
|
}
|
|
|
|
private static function userIsoIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
$id = $payload['user_iso_id'] ?? null;
|
|
$owner = filter_var($payload['owner_id'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$iso = is_string($id) ? CloudUserIso::find($id) : null;
|
|
$replica = is_string($id) ? CloudUserIsoReplica::where(
|
|
'host_id', (int) $job->host_id
|
|
)->where('user_iso_id', $id)->first() : null;
|
|
$parent = $job->parent_job_id === null ? null
|
|
: CloudJob::find((int) $job->parent_job_id);
|
|
$expectedParent = [
|
|
'user_iso_import_replica' => 'user_iso_import',
|
|
'user_iso_delete_replica' => 'user_iso_delete',
|
|
][(string) $job->kind];
|
|
if (!is_string($id)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $id) !== 1
|
|
|| $owner === false || $iso === null || $replica === null
|
|
|| $parent === null
|
|
|| $parent->parent_job_id !== null
|
|
|| (string) $parent->execution_mode !== 'aggregate'
|
|
|| (string) $parent->kind !== $expectedParent
|
|
|| (int) $parent->user_id !== (int) $owner
|
|
|| (int) $job->user_id !== (int) $owner
|
|
|| (int) $iso->active_job_id !== (int) $parent->id
|
|
|| (int) $iso->user_id !== (int) $owner
|
|
|| (int) $replica->user_id !== (int) $owner
|
|
|| (int) $replica->job_id !== (int) $job->id
|
|
|| !hash_equals((string) $replica->operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'ISO 子任务与所属人或副本账本不匹配', 409
|
|
);
|
|
}
|
|
$resource = 'user-iso:' . (int) $owner . ':' . $id;
|
|
if ((string) $job->kind === 'user_iso_import_replica') {
|
|
self::expectRequest($method, $target, 'POST', '/v1/user-isos');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'id', 'owner_id', 'name', 'source_url',
|
|
'source_token', 'sha256',
|
|
]);
|
|
if (($body['id'] ?? null) !== $id
|
|
|| (int) ($body['owner_id'] ?? 0) !== (int) $owner
|
|
|| ($body['name'] ?? null) !== (string) $iso->name) {
|
|
self::invalidPayload('ISO 导入请求与目录不匹配');
|
|
}
|
|
return ['import-user-iso', $resource];
|
|
}
|
|
self::expectRequest($method, $target, 'DELETE',
|
|
'/v1/user-isos/' . rawurlencode($id)
|
|
. '?owner_id=' . (int) $owner);
|
|
self::assertAllowedBody($body, ['operation_id']);
|
|
return ['delete-user-iso', $resource];
|
|
}
|
|
|
|
private static function assertBodyOperation(CloudJob $job, array $body): void
|
|
{
|
|
if (array_key_exists('operation_id', $body)
|
|
&& (!is_string($body['operation_id'])
|
|
|| !hash_equals((string) $job->operation_id,
|
|
$body['operation_id']))) {
|
|
self::invalidPayload('Agent 请求中的操作标识不匹配');
|
|
}
|
|
}
|
|
|
|
private static function expectRequest(
|
|
string $method,
|
|
string $target,
|
|
string $expectedMethod,
|
|
string $expectedTarget
|
|
): void {
|
|
if ($method !== $expectedMethod || $target !== $expectedTarget) {
|
|
self::invalidPayload('Agent 请求方法或路径与任务不匹配');
|
|
}
|
|
}
|
|
|
|
private static function assertAllowedBody(array $body, array $allowed): void
|
|
{
|
|
if (($body !== [] && array_is_list($body))
|
|
|| array_diff(array_keys($body), $allowed) !== []) {
|
|
self::invalidPayload('Agent 请求字段超出固定协议');
|
|
}
|
|
}
|
|
|
|
private static function invalidPayload(string $message): never
|
|
{
|
|
throw new CloudRecoveryPayloadUnavailable($message, 409);
|
|
}
|
|
|
|
private static function stored(array $payload): ?array
|
|
{
|
|
if (!array_key_exists(self::KEY, $payload)) {
|
|
return null;
|
|
}
|
|
$stored = $payload[self::KEY];
|
|
if (!is_array($stored) || array_is_list($stored)
|
|
|| array_diff(array_keys($stored), [
|
|
'version', 'action', 'resource_id', 'request_fingerprint',
|
|
]) !== []
|
|
|| ($stored['version'] ?? null) !== self::VERSION) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务持久化操作身份无效', 409
|
|
);
|
|
}
|
|
$identity = [
|
|
'action' => $stored['action'] ?? null,
|
|
'resource_id' => $stored['resource_id'] ?? null,
|
|
'request_fingerprint' => $stored['request_fingerprint'] ?? null,
|
|
];
|
|
self::assertIdentityShape($identity);
|
|
return $identity;
|
|
}
|
|
|
|
private static function isPreparedEscrow(
|
|
CloudJob $job,
|
|
array $payload,
|
|
array $identity
|
|
): bool {
|
|
$recovery = $payload['_operation_recovery'] ?? null;
|
|
$operation = is_array($recovery)
|
|
? ($recovery['operation'] ?? null) : null;
|
|
$operationIdentity = is_array($operation) ? [
|
|
'action' => $operation['action'] ?? null,
|
|
'resource_id' => $operation['resource_id'] ?? null,
|
|
'request_fingerprint' => $operation['request_fingerprint']
|
|
?? $operation['fingerprint'] ?? null,
|
|
] : [];
|
|
return is_array($recovery) && !array_is_list($recovery)
|
|
&& ($recovery['version'] ?? null) === 1
|
|
&& ($recovery['kind'] ?? null) === (string) $job->kind
|
|
&& is_string($recovery['prepared_marker'] ?? null)
|
|
&& str_starts_with(
|
|
$recovery['prepared_marker'],
|
|
'prepared:'
|
|
)
|
|
&& is_array($operation) && !array_is_list($operation)
|
|
&& ($operation['operation_id'] ?? null)
|
|
=== (string) $job->operation_id
|
|
&& self::same($identity, $operationIdentity);
|
|
}
|
|
|
|
private static function assertIdentityShape(array $identity): void
|
|
{
|
|
if (!is_string($identity['action'] ?? null)
|
|
|| strlen($identity['action']) > 128
|
|
|| preg_match(
|
|
'/^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$/D',
|
|
$identity['action']
|
|
) !== 1
|
|
|| !is_string($identity['resource_id'] ?? null)
|
|
|| strlen($identity['resource_id']) > 255
|
|
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/D',
|
|
$identity['resource_id']) !== 1
|
|
|| !is_string($identity['request_fingerprint'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
$identity['request_fingerprint']) !== 1) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务操作身份结构无效', 409
|
|
);
|
|
}
|
|
}
|
|
}
|