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.
virt/web/app/Services/Cloud/CloudPortableRestoreJobEnve...

640 lines
26 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudBackupRestore;
use App\Models\CloudBackupRestoreAttempt;
use App\Models\CloudInstanceBackup;
use App\Models\CloudJob;
use App\Models\CloudResourceReservation;
/**
* Secret-free, immutable Agent request intent for one portable-restore
* attempt. The object download capability is deliberately absent: the worker
* adds a short-lived URL only at the final wire boundary.
*/
final class CloudPortableRestoreJobEnvelope
{
private function __construct(
private readonly array $payload,
private readonly string $fingerprint,
private readonly CloudInstanceBackup $backup,
private readonly CloudBackupRestore $restore,
private readonly CloudBackupRestoreAttempt $attempt,
private readonly CloudResourceReservation $reservation
) {
}
public static function fromLedger(CloudInstanceBackup $backup,
CloudBackupRestore $restore, CloudBackupRestoreAttempt $attempt,
CloudResourceReservation $reservation,
CloudPortableRestoreTargetPlan $plan,
CloudPortableRestoreBackupEvidence $evidence,
CloudFrozenPublicNetworkIdentity $network
): self {
return self::fromLedgerState(
$backup,
$restore,
$attempt,
$reservation,
$plan,
$evidence,
$network,
true
);
}
private static function fromLedgerState(CloudInstanceBackup $backup,
CloudBackupRestore $restore, CloudBackupRestoreAttempt $attempt,
CloudResourceReservation $reservation,
CloudPortableRestoreTargetPlan $plan,
CloudPortableRestoreBackupEvidence $evidence,
CloudFrozenPublicNetworkIdentity $network,
bool $requireUnmaterialized
): self {
$planValue = $plan->toArray();
$backupEvidence = $evidence->backup();
$resources = $evidence->resources();
$input = $evidence->requestInput()->toArray();
$ownerId = (int) $backup->user_id;
if ((int) $backup->id < 1 || $ownerId < 1
|| (int) $restore->backup_id !== (int) $backup->id
|| (int) $attempt->backup_restore_id !== (int) $restore->id
|| (int) $attempt->reservation_id !== (int) $reservation->id
|| !$attempt->matchesReservation($reservation)
|| ($requireUnmaterialized
&& ($restore->target_instance_id !== null
|| $reservation->instance_id !== null))
|| $reservation->order_id !== null
|| $reservation->backup_restore_id !== null
|| (int) $reservation->user_id !== $ownerId
|| (int) $reservation->host_id !== (int) $attempt->target_host_id
|| (int) $restore->target_host_id
!== (int) $attempt->target_host_id
|| (int) $planValue['target']['host_id']
!== (int) $attempt->target_host_id
|| !hash_equals(
(string) $attempt->operation_id,
(string) $reservation->operation_id
)
|| !hash_equals(
(string) $attempt->target_plan_sha256,
$plan->sha256()
)
|| !hash_equals(
(string) $restore->selected_plan_sha256,
$plan->sha256()
)
|| !hash_equals(
(string) $attempt->target_claim_set_sha256,
$network->claimSetSha256()
)
|| !hash_equals(
(string) $attempt->target_public_network_sha256,
$network->publicNetworkSha256()
)
|| !hash_equals(
strtolower((string) $attempt->target_uuid),
strtolower((string) $restore->new_uuid)
)
|| !hash_equals(
(string) $attempt->target_name,
(string) $restore->new_name
)
|| CloudCanonicalJson::normalize($planValue['backup'])
!== CloudCanonicalJson::normalize($backupEvidence)
|| CloudCanonicalJson::normalize($planValue['resources'])
!== CloudCanonicalJson::normalize($resources)) {
throw new CloudError('恢复任务冻结身份与资源账本不一致', 409);
}
foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $field) {
if ((int) $reservation->{$field} !== (int) $resources[$field]) {
throw new CloudError('恢复任务冻结规格与资源预留不一致', 409);
}
}
$payload = [
'method' => 'POST',
'request_target' => '/v1/vms/' . rawurlencode(
strtolower((string) $attempt->target_uuid)
) . '/restore-backup',
'body' => [
'operation_id' => (string) $attempt->operation_id,
'uuid' => strtolower((string) $attempt->target_uuid),
'source' => '',
'name' => (string) $attempt->target_name,
'description' => '',
'vcpu' => (int) $resources['cpu_cores'],
'memory_mib' => (int) $resources['memory_mib'],
'disk_gib' => (int) $resources['disk_gib'],
'bandwidth_mbps' => (int) $resources['bandwidth_mbps'],
'public_network' => $network->publicNetwork()->toArray(),
'template_id' => '',
'template_revision' => 0,
'template_generation_token' => '',
'startup_script' => '',
'hostname' => '',
'guest_ssh_public_key' => '',
'root_password' => '',
'platform_network_policy_snapshot' =>
$input['platform_network_policy_snapshot'],
'debian_12_network_fix' =>
$input['debian_12_network_fix'],
'backup_key' => (string) $backup->backup_key,
'source_size_bytes' => (int) $backup->object_size_bytes,
'source_sha256' => (string) $backup->sha256,
],
'owner_id' => $ownerId,
'backup_key' => (string) $backup->backup_key,
'restore_key' => (string) $restore->restore_key,
'attempt_key' => (string) $attempt->attempt_key,
'generation' => (int) $attempt->generation,
'reservation_id' => (int) $reservation->id,
'target_plan_sha256' => (string) $attempt->target_plan_sha256,
'target_identity_sha256' =>
(string) $attempt->target_identity_sha256,
'target_claim_set_sha256' =>
(string) $attempt->target_claim_set_sha256,
'target_public_network_sha256' =>
(string) $attempt->target_public_network_sha256,
];
self::assertSecretFree($payload);
$canonical = CloudCanonicalJson::normalize($payload);
$encoded = json_encode(
$canonical,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS
);
return new self(
$payload,
hash('sha256', $encoded),
$backup,
$restore,
$attempt,
$reservation
);
}
/**
* Rebuild the queued attempt authority without taking locks. The caller
* may use this projection only for dispatch/recovery validation; every
* state mutation still belongs to its transaction coordinator.
*/
public static function fromJob(CloudJob $job, array $payload): self
{
return self::fromJobForDispatch($job, $payload);
}
/** Rebuild the strict pre-dispatch authority for a queued attempt. */
public static function fromJobForDispatch(
CloudJob $job,
array $payload
): self {
return self::fromJobState($job, $payload, true);
}
/**
* Rebuild recovery authority from stable ledgers only. This path never
* recreates the one-time object URL or its wire fingerprint.
*/
public static function fromJobForRecovery(
CloudJob $job,
array $payload
): self {
return self::fromJobState($job, $payload, false);
}
private static function fromJobState(
CloudJob $job,
array $payload,
bool $forDispatch
): self
{
if (array_is_list($payload)) {
throw new CloudError('恢复任务冻结信封结构无效', 409);
}
$stablePayload = self::withoutPersistedIdentity($payload);
if (!$forDispatch) {
unset($stablePayload['_operation_recovery']);
}
$attemptKey = $stablePayload['attempt_key'] ?? null;
if (!is_string($attemptKey)
|| preg_match('/^[a-f0-9]{32}$/D', $attemptKey) !== 1) {
throw new CloudError('恢复任务缺少尝试身份', 409);
}
$attempts = CloudBackupRestoreAttempt::where(
'attempt_key',
$attemptKey
)->limit(2)->get();
$attempt = $attempts->count() === 1 ? $attempts->first() : null;
$restore = $attempt instanceof CloudBackupRestoreAttempt
? CloudBackupRestore::find((int) $attempt->backup_restore_id)
: null;
$backup = $restore instanceof CloudBackupRestore
? CloudInstanceBackup::find((int) $restore->backup_id)
: null;
$reservation = $attempt instanceof CloudBackupRestoreAttempt
? CloudResourceReservation::find((int) $attempt->reservation_id)
: null;
if (!$attempt instanceof CloudBackupRestoreAttempt
|| !$restore instanceof CloudBackupRestore
|| !$backup instanceof CloudInstanceBackup
|| !$reservation instanceof CloudResourceReservation
|| (int) $attempt->job_id !== (int) $job->id
|| (int) $job->backup_restore_id !== (int) $restore->id
|| (int) $job->backup_id !== (int) $backup->id
|| (int) $job->user_id !== (int) $backup->user_id
|| (int) $job->host_id !== (int) $attempt->target_host_id
|| (string) $job->kind !== 'backup_restore'
|| (string) $job->execution_mode !== 'agent'
|| !hash_equals(
(string) $job->operation_id,
(string) $attempt->operation_id
)
|| !hash_equals(
(string) $job->request_idempotency_key,
(string) $attempt->attempt_key
)
|| (int) $reservation->user_id !== (int) $backup->user_id
|| (int) $reservation->host_id !== (int) $attempt->target_host_id
|| !hash_equals(
(string) $reservation->operation_id,
(string) $attempt->operation_id
)) {
throw new CloudError('恢复任务与尝试账本不一致', 409);
}
self::assertLifecycle(
$job,
$restore,
$attempt,
$reservation,
$forDispatch
);
try {
$plan = CloudPortableRestoreTargetPlan::fromStored(
(string) $attempt->target_plan_json,
(string) $attempt->target_plan_sha256
);
} catch (\InvalidArgumentException) {
throw new CloudError('恢复任务保存的目标计划损坏', 409);
}
if (!hash_equals(
(string) $restore->selected_plan_sha256,
$plan->sha256()
)
|| !hash_equals(
(string) $restore->selected_plan_json,
$plan->json()
)
|| (int) $plan->toArray()['target']['host_id']
!== (int) $attempt->target_host_id
|| (int) ($stablePayload['generation'] ?? 0)
!== (int) $attempt->generation
|| !hash_equals(
(string) ($stablePayload['target_plan_sha256'] ?? ''),
(string) $attempt->target_plan_sha256
)
|| !hash_equals(
(string) ($stablePayload['target_identity_sha256'] ?? ''),
(string) $attempt->target_identity_sha256
)
|| !hash_equals(
(string) ($stablePayload['target_claim_set_sha256'] ?? ''),
(string) $attempt->target_claim_set_sha256
)
|| !hash_equals(
(string) ($stablePayload[
'target_public_network_sha256'
] ?? ''),
(string) $attempt->target_public_network_sha256
)) {
throw new CloudError('恢复任务冻结摘要与尝试账本不一致', 409);
}
$evidence = CloudPortableRestoreBackupEvidence::fromBackup($backup);
$reservationState = (string) $reservation->state;
$claimSet = CloudPublicNetworkAllocationService::currentClaimSet(
(int) $reservation->id,
$reservationState,
$reservationState === 'committed'
? (int) $reservation->instance_id : null
);
try {
$network = CloudFrozenPublicNetworkIdentity::fromStored(
(int) $reservation->id,
(int) $attempt->target_host_id,
(string) $attempt->target_uuid,
(int) $attempt->target_network_attachment_id,
(string) $attempt->target_identity_json,
(string) $attempt->target_identity_sha256,
(string) $attempt->target_public_network_json,
(string) $attempt->target_public_network_sha256,
(string) $attempt->target_claim_set_sha256,
$claimSet
);
} catch (\InvalidArgumentException) {
throw new CloudError('恢复任务冻结公网身份损坏', 409);
}
$envelope = self::fromLedgerState(
$backup,
$restore,
$attempt,
$reservation,
$plan,
$evidence,
$network,
$forDispatch
);
$fullEnvelope = CloudCanonicalJson::normalize($envelope->payload());
$compactEnvelope = CloudCanonicalJson::normalize(
self::compactRecoveryPayload($envelope->payload())
);
if (CloudCanonicalJson::normalize($stablePayload) !== $fullEnvelope
&& ($forDispatch
|| CloudCanonicalJson::normalize($stablePayload)
!== $compactEnvelope)) {
throw new CloudError('恢复任务冻结信封已经变化', 409);
}
if ($forDispatch) {
$envelope->assertStoredJob($job);
} elseif (!hash_equals(
$envelope->fingerprint(),
(string) $job->request_fingerprint
)) {
throw new CloudError('恢复任务请求指纹与冻结信封不一致', 409);
}
self::assertSecretFree($payload);
return $envelope;
}
private static function assertLifecycle(CloudJob $job,
CloudBackupRestore $restore, CloudBackupRestoreAttempt $attempt,
CloudResourceReservation $reservation, bool $forDispatch): void
{
$state = (string) $attempt->state;
$resolution = (string) $attempt->effect_resolution;
$reservationState = (string) $reservation->state;
$allowedReservations = match ($state) {
'queued', 'awaiting_receipt' =>
$resolution === 'not_applicable' ? ['held'] : [],
'effect_unknown' =>
$resolution === 'unknown' ? ['uncertain'] : [],
'finalization_pending' => match ($resolution) {
'applied' => ['held', 'uncertain'],
'not_applied' => ['held', 'uncertain'],
default => [],
},
default => [],
};
$instanceMaterialized = $reservationState === 'committed';
$restoreInstanceId = $restore->target_instance_id === null
? null : (int) $restore->target_instance_id;
$reservationInstanceId = $reservation->instance_id === null
? null : (int) $reservation->instance_id;
$jobInstanceId = $job->instance_id === null
? null : (int) $job->instance_id;
$resolutionRecorded = $state === 'finalization_pending';
$expectedEvidence = match ($state) {
'queued', 'awaiting_receipt' => 'not_applicable',
'effect_unknown' => 'unknown',
'finalization_pending' => $resolution,
default => '',
};
$evidenceResolution = (string) $attempt->evidence_resolution;
$hasEvidence = is_string($attempt->evidence_json)
&& strlen((string) $attempt->evidence_json) > 1
&& is_string($attempt->evidence_sha256)
&& preg_match('/^[a-f0-9]{64}$/D',
(string) $attempt->evidence_sha256) === 1
&& $attempt->evidence_recorded_at !== null
&& hash_equals(
hash('sha256', (string) $attempt->evidence_json),
(string) $attempt->evidence_sha256
);
$evidenceShapeValid = $expectedEvidence === 'not_applicable'
? ($evidenceResolution === 'not_applicable'
&& $attempt->evidence_json === null
&& $attempt->evidence_sha256 === null
&& $attempt->evidence_recorded_at === null)
: ($expectedEvidence !== ''
&& $evidenceResolution === $expectedEvidence
&& $hasEvidence);
if (($forDispatch && $state !== 'queued')
|| ($forDispatch && $resolution !== 'not_applicable')
|| $allowedReservations === []
|| !$evidenceShapeValid
|| !in_array($reservationState, $allowedReservations, true)
|| (int) ($attempt->active_attempt ?? 0) !== 1
|| ($resolutionRecorded
? $attempt->effect_resolved_at === null
: $attempt->effect_resolved_at !== null)
|| $attempt->terminal_at !== null
|| ($instanceMaterialized
&& ($restoreInstanceId === null
|| $reservationInstanceId === null
|| $jobInstanceId === null
|| $restoreInstanceId !== $reservationInstanceId
|| $restoreInstanceId !== $jobInstanceId))
|| (!$instanceMaterialized
&& ($restoreInstanceId !== null
|| $reservationInstanceId !== null
|| $jobInstanceId !== null))) {
throw new CloudError('恢复任务尝试生命周期不一致', 409);
}
}
public function payload(): array
{
return $this->payload;
}
/**
* Remove only dispatch-time padding while retaining every stable ledger
* binding needed by late receipts and two-phase recovery.
*/
public static function compactRecoveryPayload(array $payload): array
{
$body = is_array($payload['body'] ?? null)
? $payload['body'] : [];
$compact = [
'method' => $payload['method'] ?? null,
'request_target' => $payload['request_target'] ?? null,
'owner_id' => $payload['owner_id'] ?? null,
'backup_key' => $payload['backup_key'] ?? null,
'restore_key' => $payload['restore_key'] ?? null,
'reservation_id' => $payload['reservation_id'] ?? null,
'attempt_key' => $payload['attempt_key'] ?? null,
'generation' => $payload['generation'] ?? null,
'target_plan_sha256' =>
$payload['target_plan_sha256'] ?? null,
'target_identity_sha256' =>
$payload['target_identity_sha256'] ?? null,
'target_claim_set_sha256' =>
$payload['target_claim_set_sha256'] ?? null,
'target_public_network_sha256' =>
$payload['target_public_network_sha256'] ?? null,
'body' => [
'operation_id' => $body['operation_id'] ?? null,
'uuid' => $body['uuid'] ?? null,
'name' => $body['name'] ?? null,
'vcpu' => $body['vcpu'] ?? null,
'memory_mib' => $body['memory_mib'] ?? null,
'disk_gib' => $body['disk_gib'] ?? null,
'bandwidth_mbps' => $body['bandwidth_mbps'] ?? null,
'public_network' => $body['public_network'] ?? null,
'backup_key' => $body['backup_key'] ?? null,
'source_size_bytes' => $body['source_size_bytes'] ?? null,
'source_sha256' => $body['source_sha256'] ?? null,
'debian_12_network_fix' =>
$body['debian_12_network_fix'] ?? null,
'platform_network_policy_snapshot' =>
$body['platform_network_policy_snapshot'] ?? null,
],
];
if (array_key_exists('_operation_identity', $payload)) {
$compact['_operation_identity'] =
$payload['_operation_identity'];
}
return $compact;
}
public function fingerprint(): string
{
return $this->fingerprint;
}
public function backup(): CloudInstanceBackup
{
return $this->backup;
}
public function restore(): CloudBackupRestore
{
return $this->restore;
}
public function attempt(): CloudBackupRestoreAttempt
{
return $this->attempt;
}
public function reservation(): CloudResourceReservation
{
return $this->reservation;
}
public function action(): string
{
return 'restore-backup:' . (string) $this->backup->backup_key;
}
public function resourceId(): string
{
return strtolower((string) $this->attempt->target_uuid);
}
/** Return the one transient Agent wire payload without mutating state. */
public function wirePayload(string $sourceUrl): array
{
$parts = parse_url($sourceUrl);
if ($sourceUrl === '' || strlen($sourceUrl) > 16384
|| !is_array($parts)
|| strtolower((string) ($parts['scheme'] ?? '')) !== 'https'
|| trim((string) ($parts['host'] ?? '')) === ''
|| isset($parts['user']) || isset($parts['pass'])) {
throw new CloudError('恢复任务临时下载能力无效', 409);
}
$wire = $this->payload;
$wire['body']['source_url'] = $sourceUrl;
return $wire;
}
public function assertStoredJob(CloudJob $job): void
{
if (!hash_equals(
$this->fingerprint,
(string) $job->request_fingerprint
)) {
throw new CloudError('恢复任务请求指纹与冻结信封不一致', 409);
}
try {
$stored = CloudSecrets::decrypt(
(string) $job->sealed_payload,
'job-payload'
);
} catch (\Throwable) {
throw new CloudError('恢复任务冻结信封无法读取', 409);
}
if (!is_array($stored) || array_is_list($stored)
|| CloudCanonicalJson::normalize(
self::withoutPersistedIdentity($stored)
) !== CloudCanonicalJson::normalize($this->payload)) {
throw new CloudError('恢复任务冻结信封已经变化', 409);
}
self::assertSecretFree($stored);
}
private static function withoutPersistedIdentity(array $payload): array
{
if (!array_key_exists('_operation_identity', $payload)) {
return $payload;
}
$identity = $payload['_operation_identity'];
$expectedAction = is_array($payload['body'] ?? null)
? 'restore-backup:'
. (string) ($payload['body']['backup_key'] ?? '')
: '';
$expectedResource = is_array($payload['body'] ?? null)
? strtolower((string) ($payload['body']['uuid'] ?? ''))
: '';
if (!is_array($identity) || array_is_list($identity)
|| array_keys($identity) !== [
'version', 'action', 'resource_id', 'request_fingerprint',
]
|| ($identity['version'] ?? null) !== 1
|| !is_string($identity['action'] ?? null)
|| !hash_equals($expectedAction, $identity['action'])
|| !is_string($identity['resource_id'] ?? null)
|| !hash_equals($expectedResource, $identity['resource_id'])
|| !is_string($identity['request_fingerprint'] ?? null)
|| preg_match('/^[a-f0-9]{64}$/D',
$identity['request_fingerprint']) !== 1) {
throw new CloudError('恢复任务持久化操作身份无效', 409);
}
unset($payload['_operation_identity']);
return $payload;
}
private static function assertSecretFree(array $payload): void
{
$body = $payload['body'] ?? null;
if (!is_array($body) || array_is_list($body)
|| array_key_exists('source_url', $body)
|| array_key_exists('object_key', $body)
|| self::containsForbiddenKey($payload)) {
throw new CloudError('恢复任务冻结信封包含临时下载能力', 409);
}
}
private static function containsForbiddenKey(array $value): bool
{
$forbidden = [
'source_url' => true,
'object_key' => true,
'sealed_storage_runtime' => true,
'access_key_id' => true,
'secret_access_key' => true,
'credentials' => true,
];
foreach ($value as $key => $item) {
if (is_string($key) && isset($forbidden[$key])) {
return true;
}
if (is_array($item) && self::containsForbiddenKey($item)) {
return true;
}
}
return false;
}
}