diff --git a/agent/api/server_test.go b/agent/api/server_test.go index f4d6b3ab..f08ed103 100644 --- a/agent/api/server_test.go +++ b/agent/api/server_test.go @@ -1362,6 +1362,11 @@ func TestCreateBackupUsesDedicatedAsyncActionAndHeavyAdmission(t *testing.T) { result := hypervisor.BackupResult{ BackupKey: backupKey, SizeBytes: 1024, VirtualSizeBytes: 40 << 30, SHA256: strings.Repeat("a", 64), Consistency: "crash", + SourceContract: &hypervisor.PortableRestoreContract{ + Contract: 1, Architecture: "x86_64", Machine: "q35", + Firmware: "uefi", SecureBoot: false, DiskFormat: "qcow2", + SystemDiskOnly: true, PublicNetworkContract: 1, VPCInherited: false, + }, } encodedResult, err := json.Marshal(result) if err != nil { diff --git a/agent/hypervisor/libvirt_adapter.go b/agent/hypervisor/libvirt_adapter.go index a2d02f76..dea0c92d 100644 --- a/agent/hypervisor/libvirt_adapter.go +++ b/agent/hypervisor/libvirt_adapter.go @@ -167,14 +167,16 @@ func (l *Libvirt) Capabilities(ctx context.Context) (Capabilities, error) { if features.UEFI { firmware = []string{"uefi"} } + publicNetwork := publicNetworkCapability(checks) return Capabilities{ Backend: "libvirt", LibvirtVersion: formatLibvirtVersion(libVersion), QEMUVersion: formatLibvirtVersion(qemuVersion), Features: features, PowerActions: powerActions, Firmware: firmware, NetworkSelectors: networkSelectors, Checks: checks, - PeerMigration: peerCapability, - VPCL3: vpcCapability, - PublicNetwork: publicNetworkCapability(checks), + PeerMigration: peerCapability, + VPCL3: vpcCapability, + PublicNetwork: publicNetwork, + PortableRestore: portableRestoreCapability(checks, publicNetwork), }, nil } diff --git a/agent/hypervisor/libvirt_backup.go b/agent/hypervisor/libvirt_backup.go index 3631c798..8d72387b 100644 --- a/agent/hypervisor/libvirt_backup.go +++ b/agent/hypervisor/libvirt_backup.go @@ -28,7 +28,7 @@ func (l *Libvirt) CreateBackup(ctx context.Context, uuid string, request BackupR func (l *Libvirt) createPortableBackup(ctx context.Context, uuid string, request BackupRequest) (_ BackupResult, resultErr error) { client := objecttransfer.New() defer client.CloseIdleConnections() - active, err := l.validateBackupSource(ctx, uuid, request.BackupKey) + active, sourceContract, err := l.validateBackupSource(ctx, uuid, request.BackupKey) if err != nil { return BackupResult{}, abortRejectedBackupPlan( ctx, client.AbortMultipart, request.ObjectUpload, err, @@ -94,7 +94,8 @@ func (l *Libvirt) createPortableBackup(ctx context.Context, uuid string, request BackupKey: request.BackupKey, SizeBytes: upload.SizeBytes, VirtualSizeBytes: info.Capacity, SHA256: upload.SHA256, ObjectETag: upload.ETag, ObjectVersionID: upload.VersionID, - Consistency: snapshot.Consistency, + Consistency: snapshot.Consistency, + SourceContract: &sourceContract, } cleanupCtx, cleanupCancel := backupLocalCleanupContext(ctx) cleanupErr := l.cleanupBackupWorkspace(cleanupCtx, uuid, request.BackupKey) @@ -262,34 +263,38 @@ func abortRejectedBackupPlan(ctx context.Context, return operation.MarkNotApplied(rejection) } -func (l *Libvirt) validateBackupSource(ctx context.Context, uuid, backupKey string) (bool, error) { +func (l *Libvirt) validateBackupSource(ctx context.Context, uuid, backupKey string) (bool, PortableRestoreContract, error) { domain, err := l.domainByUUID(ctx, uuid) if err != nil { - return false, err + return false, PortableRestoreContract{}, err } defer domain.Free() _, definition, metadata, pool, volume, err := l.managedRootContext(domain) if err != nil { - return false, err + return false, PortableRestoreContract{}, err } defer pool.Free() defer volume.Free() if metadata.RescueTemplateID != "" { - return false, NewError(ErrConflict, "backup_rescue_active", "VM backup is unavailable while rescue media is attached", nil) + return false, PortableRestoreContract{}, NewError(ErrConflict, "backup_rescue_active", "VM backup is unavailable while rescue media is attached", nil) } if err := validateBackupTransitionState(metadata); err != nil { - return false, err + return false, PortableRestoreContract{}, err } for _, stored := range metadata.Snapshots { if stored.Key == backupKey { - return false, NewError(ErrConflict, "backup_exists", "local backup work already exists", nil) + return false, PortableRestoreContract{}, NewError(ErrConflict, "backup_exists", "local backup work already exists", nil) } } if err := validateSingleWritableRoot(definition); err != nil { - return false, err + return false, PortableRestoreContract{}, err } if _, err := validateStandaloneQCOW2Volume(volume, 0); err != nil { - return false, err + return false, PortableRestoreContract{}, err + } + sourceContract, err := l.validatePortableRestoreDomain(definition, metadata) + if err != nil { + return false, PortableRestoreContract{}, err } for _, volumeName := range []string{ backupWorkspaceVolumeName(uuid, backupKey), @@ -301,35 +306,102 @@ func (l *Libvirt) validateBackupSource(ctx context.Context, uuid, backupKey stri l.storagePoolName(StorageRoleManaged), volumeName, ) if err != nil { - return false, err + return false, PortableRestoreContract{}, err } if existing != nil { existing.Free() - return false, NewError(ErrConflict, "backup_exists", "local backup work already exists", nil) + return false, PortableRestoreContract{}, NewError(ErrConflict, "backup_exists", "local backup work already exists", nil) } } active, err := domain.IsActive() if err != nil { - return false, translateLibvirtError("check VM state for backup", err) + return false, PortableRestoreContract{}, translateLibvirtError("check VM state for backup", err) } if active { liveDocument, liveErr := domain.GetXMLDesc(0) if liveErr != nil { - return false, translateLibvirtError("read live VM disk layout for backup", liveErr) + return false, PortableRestoreContract{}, translateLibvirtError("read live VM disk layout for backup", liveErr) + } + liveDefinition, liveMetadata, parseErr := parseManagedDomain(liveDocument) + if parseErr != nil { + return false, PortableRestoreContract{}, NewError(ErrConflict, "backup_platform_unsupported", "live VM platform is invalid for portable backup", nil) } - var liveDefinition libvirtxml.Domain - if liveDefinition.Unmarshal(liveDocument) != nil { - return false, NewError(ErrConflict, "backup_disk_layout_unsupported", "live VM disk layout is invalid for portable backup", nil) + liveContract, contractErr := l.validatePortableRestoreDomain(liveDefinition, liveMetadata) + if contractErr != nil || liveContract != sourceContract { + return false, PortableRestoreContract{}, NewError(ErrConflict, "backup_platform_unsupported", "live VM platform is unavailable for portable backup", nil) } managedPath, pathErr := volume.GetPath() if pathErr != nil { - return false, translateLibvirtError("resolve live managed root for backup", pathErr) + return false, PortableRestoreContract{}, translateLibvirtError("resolve live managed root for backup", pathErr) } - if err := validateLiveBackupDefinition(&liveDefinition, managedPath); err != nil { - return false, err + if err := validateLiveBackupDefinition(liveDefinition, managedPath); err != nil { + return false, PortableRestoreContract{}, err } } - return active, nil + return active, sourceContract, nil +} + +func (l *Libvirt) validatePortableRestoreDomain(definition *libvirtxml.Domain, + metadata *domainMetadataXML) (PortableRestoreContract, error) { + reject := func() (PortableRestoreContract, error) { + return PortableRestoreContract{}, NewError( + ErrConflict, "backup_platform_unsupported", + "VM platform is unavailable for portable backup", nil, + ) + } + if definition == nil || metadata == nil || definition.Type != "kvm" || + definition.OS == nil || definition.OS.Type == nil || + definition.OS.Type.Type != "hvm" || definition.OS.Type.Arch != "x86_64" || + !portableQ35Machine(definition.OS.Type.Machine) || + definition.OS.Loader == nil || + definition.OS.Loader.Path != l.local.FirmwareLoader || + definition.OS.Loader.Type != "pflash" || + definition.OS.Loader.Readonly != "yes" || + definition.OS.Loader.Secure != "no" || + definition.OS.NVRam == nil || + definition.Features == nil || definition.Features.SMM == nil || + definition.Features.SMM.State != "off" { + return reject() + } + if _, err := validateManagedDomainNVRAMPaths( + definition, l.local.NVRAMDirectory, definition.UUID, + ); err != nil { + return reject() + } + if err := validateSingleWritableRoot(definition); err != nil { + return reject() + } + root, err := managedRootDisk(definition) + if err != nil || root.Driver == nil || root.Driver.Name != "qemu" || + root.Driver.Type != "qcow2" || root.Target == nil || + root.Target.Dev != "vda" || root.Target.Bus != "virtio" || + root.Source == nil || root.Source.File == nil || + domainBackingChainPresent(root.BackingStore) || root.Mirror != nil { + return reject() + } + public, err := metadata.PublicNetwork.public() + if err != nil || public.Contract != fixedPortableRestoreContract().PublicNetworkContract || + !managedNetworkLayoutMatches(definition, metadata) { + return reject() + } + source, err := ParseNetworkSelector(public.NetworkSelector) + if err != nil { + return reject() + } + publicIndex, found := managedPublicInterfaceIndex( + definition, networkFilterName(definition.UUID), public, + ) + if !found || !domainNetworkSourceMatches( + definition.Devices.Interfaces[publicIndex], source.Type, source.Source, + ) { + return reject() + } + return fixedPortableRestoreContract(), nil +} + +func portableQ35Machine(machine string) bool { + machine = strings.ToLower(strings.TrimSpace(machine)) + return machine == "q35" || strings.HasPrefix(machine, "pc-q35-") } func validateBackupTransitionState(metadata *domainMetadataXML) error { diff --git a/agent/hypervisor/libvirt_backup_test.go b/agent/hypervisor/libvirt_backup_test.go index 1afb69c8..1603a488 100644 --- a/agent/hypervisor/libvirt_backup_test.go +++ b/agent/hypervisor/libvirt_backup_test.go @@ -5,6 +5,7 @@ package hypervisor import ( "context" "errors" + "path/filepath" "testing" "git.luoli.live/root/virt/agent/objecttransfer" @@ -12,6 +13,91 @@ import ( "libvirt.org/go/libvirtxml" ) +func portableRestoreDomainFixture(t *testing.T) (*Libvirt, *libvirtxml.Domain, *domainMetadataXML) { + t.Helper() + definition := validDomainDefinition() + directory := "/var/lib/libvirt/qemu/nvram" + definition.Firmware.NVRAMPath = filepath.Join(directory, definition.UUID+"_VARS.fd") + document, err := BuildDomainXML(definition) + if err != nil { + t.Fatal(err) + } + domain, metadata, err := parseManagedDomain(document) + if err != nil { + t.Fatal(err) + } + adapter := &Libvirt{local: LocalConfig{ + FirmwareLoader: definition.Firmware.Loader, + FirmwareNVRAMTemplate: definition.Firmware.NVRAMTemplate, + NVRAMDirectory: directory, + }} + return adapter, domain, metadata +} + +func TestPortableRestoreSourceContractRequiresActualManagedPlatform(t *testing.T) { + adapter, domain, metadata := portableRestoreDomainFixture(t) + contract, err := adapter.validatePortableRestoreDomain(domain, metadata) + if err != nil || contract != fixedPortableRestoreContract() { + t.Fatalf("valid portable source contract=%#v err=%v", contract, err) + } + + tests := map[string]func(*libvirtxml.Domain, *domainMetadataXML){ + "architecture": func(value *libvirtxml.Domain, _ *domainMetadataXML) { value.OS.Type.Arch = "aarch64" }, + "machine": func(value *libvirtxml.Domain, _ *domainMetadataXML) { value.OS.Type.Machine = "pc-i440fx-9.2" }, + "secure boot": func(value *libvirtxml.Domain, _ *domainMetadataXML) { value.OS.Loader.Secure = "yes" }, + "firmware": func(value *libvirtxml.Domain, _ *domainMetadataXML) { value.OS.Loader.Type = "rom" }, + "nvram": func(value *libvirtxml.Domain, _ *domainMetadataXML) { value.OS.NVRam = nil }, + "smm": func(value *libvirtxml.Domain, _ *domainMetadataXML) { value.Features.SMM.State = "on" }, + "disk format": func(value *libvirtxml.Domain, _ *domainMetadataXML) { value.Devices.Disks[0].Driver.Type = "raw" }, + "disk bus": func(value *libvirtxml.Domain, _ *domainMetadataXML) { value.Devices.Disks[0].Target.Bus = "sata" }, + "backing": func(value *libvirtxml.Domain, _ *domainMetadataXML) { + value.Devices.Disks[0].BackingStore = &libvirtxml.DomainDiskBackingStore{ + Source: &libvirtxml.DomainDiskSource{File: &libvirtxml.DomainDiskSourceFile{File: "/foreign/base.qcow2"}}, + } + }, + "public contract": func(_ *libvirtxml.Domain, value *domainMetadataXML) { value.PublicNetwork.Contract = 2 }, + "public source": func(value *libvirtxml.Domain, _ *domainMetadataXML) { + value.Devices.Interfaces[0].Source.Bridge.Bridge = "br1" + }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + currentAdapter, current, currentMetadata := portableRestoreDomainFixture(t) + mutate(current, currentMetadata) + if _, err := currentAdapter.validatePortableRestoreDomain(current, currentMetadata); !errors.Is(err, ErrConflict) { + t.Fatalf("incompatible source error = %v", err) + } + }) + } +} + +func TestPortableRestoreSourceContractDoesNotInheritSourceVPC(t *testing.T) { + definition := validDomainDefinition() + directory := "/var/lib/libvirt/qemu/nvram" + definition.Firmware.NVRAMPath = filepath.Join(directory, definition.UUID+"_VARS.fd") + port := validVPCPortMetadata() + definition.VPCPort = &port + definition.Network = append(definition.Network, NetworkAttachment{ + Bridge: port.Bridge, MAC: port.MAC, + }) + document, err := BuildDomainXML(definition) + if err != nil { + t.Fatal(err) + } + domain, metadata, err := parseManagedDomain(document) + if err != nil { + t.Fatal(err) + } + adapter := &Libvirt{local: LocalConfig{ + FirmwareLoader: definition.Firmware.Loader, FirmwareNVRAMTemplate: definition.Firmware.NVRAMTemplate, + NVRAMDirectory: directory, + }} + contract, err := adapter.validatePortableRestoreDomain(domain, metadata) + if err != nil || contract.VPCInherited { + t.Fatalf("source VPC contract=%#v err=%v", contract, err) + } +} + type backupVolumeInspector struct { document string capacity uint64 diff --git a/agent/hypervisor/libvirt_capabilities.go b/agent/hypervisor/libvirt_capabilities.go index 80cd4702..8cc362f6 100644 --- a/agent/hypervisor/libvirt_capabilities.go +++ b/agent/hypervisor/libvirt_capabilities.go @@ -28,6 +28,26 @@ func publicNetworkCapability(checks map[string]CapabilityCheck) PublicNetworkCap } } +func portableRestoreCapability(checks map[string]CapabilityCheck, + public PublicNetworkCapability) *PortableRestoreContract { + required := []string{ + "firmware_loader", "firmware_nvram_template", "nvram_directory", + "managed_storage_pool", "seed_storage_pool", "storage_configuration", + "network_selectors", "nwfilter_api", "public_ndp_guard", "q35_uefi", + } + for _, name := range required { + if !checks[name].Available { + return nil + } + } + if public.Contract != publicnetwork.ContractVersion || + !public.DualStackRequired || !public.ProjectOwnedFilter || !public.NDPGuard { + return nil + } + contract := fixedPortableRestoreContract() + return &contract +} + func applyVPCCleanTrafficGate(capability *VPCL3Capability, check CapabilityCheck) bool { if capability == nil { return false diff --git a/agent/hypervisor/libvirt_operation_admin.go b/agent/hypervisor/libvirt_operation_admin.go index 46965926..298765ca 100644 --- a/agent/hypervisor/libvirt_operation_admin.go +++ b/agent/hypervisor/libvirt_operation_admin.go @@ -1674,6 +1674,8 @@ func operationEffectProjection(record operation.Record, raw []byte) json.RawMess !decodeOperationEffectResult(raw, &value) || value.BackupKey != parts[1] || value.SizeBytes <= 0 || value.VirtualSizeBytes == 0 || !lowerHexDigest(value.SHA256) || + value.SourceContract == nil || + *value.SourceContract != fixedPortableRestoreContract() || !snapshotConsistencyMatchesRequest(parts[2], value.Consistency) { return nil } diff --git a/agent/hypervisor/libvirt_operation_admin_test.go b/agent/hypervisor/libvirt_operation_admin_test.go index a0bd3452..5431157e 100644 --- a/agent/hypervisor/libvirt_operation_admin_test.go +++ b/agent/hypervisor/libvirt_operation_admin_test.go @@ -510,6 +510,7 @@ func TestPortableBackupOperationProjectionPreservesFinalizerIdentity(t *testing. "object_etag":"\"backup-etag\"", "object_version_id":"version/7+opaque", "consistency":"filesystem", + "source_contract":{"contract":1,"architecture":"x86_64","machine":"q35","firmware":"uefi","secure_boot":false,"disk_format":"qcow2","system_disk_only":true,"public_network_contract":1,"vpc_inherited":false}, "source_url":"must-not-leak" }`)) var backupProjection BackupResult @@ -520,7 +521,9 @@ func TestPortableBackupOperationProjectionPreservesFinalizerIdentity(t *testing. backupProjection.VirtualSizeBytes != 2147483648 || backupProjection.SHA256 != digest || backupProjection.ObjectETag != `"backup-etag"` || backupProjection.ObjectVersionID != "version/7+opaque" || - backupProjection.Consistency != "filesystem" { + backupProjection.Consistency != "filesystem" || + backupProjection.SourceContract == nil || + *backupProjection.SourceContract != fixedPortableRestoreContract() { t.Fatalf("backup projection omitted finalizer identity: %#v", backupProjection) } if strings.Contains(string(backup), "must-not-leak") || strings.Contains(string(backup), "source_url") { @@ -529,10 +532,33 @@ func TestPortableBackupOperationProjectionPreservesFinalizerIdentity(t *testing. downgraded := operationEffectProjection(operation.Record{ ResourceID: resourceID, Action: "create-backup:" + backupKey + ":filesystem", - }, []byte(`{"backup_key":"`+backupKey+`","size_bytes":1,"virtual_size_bytes":1,"sha256":"`+digest+`","consistency":"crash"}`)) + }, []byte(`{"backup_key":"`+backupKey+`","size_bytes":1,"virtual_size_bytes":1,"sha256":"`+digest+`","consistency":"crash","source_contract":{"contract":1,"architecture":"x86_64","machine":"q35","firmware":"uefi","secure_boot":false,"disk_format":"qcow2","system_disk_only":true,"public_network_contract":1,"vpc_inherited":false}}`)) if len(downgraded) == 0 { t.Fatal("filesystem backup downgraded to crash consistency lost its finalizer projection") } + missingContract := operationEffectProjection(operation.Record{ + ResourceID: resourceID, + Action: "create-backup:" + backupKey + ":filesystem", + }, []byte(`{"backup_key":"`+backupKey+`","size_bytes":1,"virtual_size_bytes":1,"sha256":"`+digest+`","consistency":"filesystem"}`)) + if len(missingContract) != 0 { + t.Fatalf("backup without source contract produced projection: %s", missingContract) + } + wrongContract := fixedPortableRestoreContract() + wrongContract.Machine = "pc-i440fx" + wrongResult := BackupResult{ + BackupKey: backupKey, SizeBytes: 1, VirtualSizeBytes: 1, + SHA256: digest, Consistency: "filesystem", SourceContract: &wrongContract, + } + wrongRaw, err := json.Marshal(wrongResult) + if err != nil { + t.Fatal(err) + } + if projected := operationEffectProjection(operation.Record{ + ResourceID: resourceID, + Action: "create-backup:" + backupKey + ":filesystem", + }, wrongRaw); len(projected) != 0 { + t.Fatalf("backup with wrong source contract produced projection: %s", projected) + } restore := operationEffectProjection(operation.Record{ ResourceID: resourceID, @@ -642,7 +668,10 @@ func TestSuccessfulBackupCleanupPendingRetainsImmutableObjectProjection(t *testi State: operation.StateSucceeded, Result: json.RawMessage(`{"backup_key":"` + key + `","size_bytes":1048576,"virtual_size_bytes":2147483648,"sha256":"` + - strings.Repeat("a", 64) + `","consistency":"crash","cleanup_pending":true}`), + strings.Repeat("a", 64) + `","consistency":"crash","cleanup_pending":true,` + + `"source_contract":{"contract":1,"architecture":"x86_64","machine":"q35",` + + `"firmware":"uefi","secure_boot":false,"disk_format":"qcow2",` + + `"system_disk_only":true,"public_network_contract":1,"vpc_inherited":false}}`), } if !storedOperationInspectionAvailable(record) { t.Fatal("successful backup with local cleanup residue lost its immutable result") diff --git a/agent/hypervisor/libvirt_peer_migration.go b/agent/hypervisor/libvirt_peer_migration.go index 9210aaa2..deca2853 100644 --- a/agent/hypervisor/libvirt_peer_migration.go +++ b/agent/hypervisor/libvirt_peer_migration.go @@ -52,7 +52,7 @@ func (l *Libvirt) PreparePeerMigration(ctx context.Context, uuid string, ErrUnavailable, "peer_migration_state_unavailable", "peer migration source intent cannot be inspected", err, )) } - if _, err := l.validateBackupSource(ctx, uuid, request.MigrationID); err != nil { + if _, _, err := l.validateBackupSource(ctx, uuid, request.MigrationID); err != nil { return PreparePeerMigrationResult{}, operation.MarkNotApplied(err) } diff --git a/agent/hypervisor/libvirt_safety_test.go b/agent/hypervisor/libvirt_safety_test.go index 8772c611..659619a4 100644 --- a/agent/hypervisor/libvirt_safety_test.go +++ b/agent/hypervisor/libvirt_safety_test.go @@ -1980,6 +1980,41 @@ func TestCapabilitiesAreDerivedFromRuntimePrerequisites(t *testing.T) { } } +func TestPortableRestoreCapabilityRequiresEveryRuntimeProof(t *testing.T) { + required := []string{ + "firmware_loader", "firmware_nvram_template", "nvram_directory", + "managed_storage_pool", "seed_storage_pool", "storage_configuration", + "network_selectors", "nwfilter_api", "public_ndp_guard", "q35_uefi", + } + checks := make(map[string]CapabilityCheck, len(required)) + for _, name := range required { + checks[name] = availableCheck() + } + public := PublicNetworkCapability{ + Contract: 1, DualStackRequired: true, ProjectOwnedFilter: true, NDPGuard: true, + } + if got := portableRestoreCapability(checks, public); got == nil || *got != fixedPortableRestoreContract() { + t.Fatalf("ready portable restore capability = %#v", got) + } + for _, missing := range required { + t.Run(missing, func(t *testing.T) { + broken := make(map[string]CapabilityCheck, len(checks)) + for name, check := range checks { + broken[name] = check + } + broken[missing] = unavailableCheck(capabilityUnavailable) + if got := portableRestoreCapability(broken, public); got != nil { + t.Fatalf("capability advertised without %s: %#v", missing, got) + } + }) + } + brokenPublic := public + brokenPublic.NDPGuard = false + if got := portableRestoreCapability(checks, brokenPublic); got != nil { + t.Fatalf("capability advertised without public network guard: %#v", got) + } +} + func TestPublicNetworkCapabilityRequiresBothRuntimeGuards(t *testing.T) { checks := map[string]CapabilityCheck{ "nwfilter_api": availableCheck(), diff --git a/agent/hypervisor/types.go b/agent/hypervisor/types.go index e585afd5..289efdbf 100644 --- a/agent/hypervisor/types.go +++ b/agent/hypervisor/types.go @@ -116,6 +116,37 @@ type PublicNetworkCapability struct { NDPGuard bool `json:"ndp_guard"` } +// PortableRestoreContract is the one bounded, host-verified platform shape +// that this Agent can both produce as a portable backup and consume as a +// restore target. Values are deliberately not configurable strings: the +// libvirt adapter only publishes this fixed contract after its runtime probes +// have confirmed every prerequisite. +type PortableRestoreContract struct { + Contract uint64 `json:"contract"` + Architecture string `json:"architecture"` + Machine string `json:"machine"` + Firmware string `json:"firmware"` + SecureBoot bool `json:"secure_boot"` + DiskFormat string `json:"disk_format"` + SystemDiskOnly bool `json:"system_disk_only"` + PublicNetworkContract uint64 `json:"public_network_contract"` + VPCInherited bool `json:"vpc_inherited"` +} + +func fixedPortableRestoreContract() PortableRestoreContract { + return PortableRestoreContract{ + Contract: 1, + Architecture: "x86_64", + Machine: "q35", + Firmware: "uefi", + SecureBoot: false, + DiskFormat: "qcow2", + SystemDiskOnly: true, + PublicNetworkContract: publicnetwork.ContractVersion, + VPCInherited: false, + } +} + type Capabilities struct { Backend string `json:"backend"` LibvirtVersion string `json:"libvirt_version,omitempty"` @@ -128,6 +159,7 @@ type Capabilities struct { PeerMigration *PeerMigrationCapability `json:"peer_migration,omitempty"` VPCL3 *VPCL3Capability `json:"vpc_l3,omitempty"` PublicNetwork PublicNetworkCapability `json:"public_network"` + PortableRestore *PortableRestoreContract `json:"portable_restore,omitempty"` } // CapabilityCheck exposes bounded, non-sensitive runtime evidence for a @@ -291,14 +323,15 @@ type BackupRequest struct { } type BackupResult struct { - BackupKey string `json:"backup_key"` - SizeBytes int64 `json:"size_bytes"` - VirtualSizeBytes uint64 `json:"virtual_size_bytes"` - SHA256 string `json:"sha256"` - ObjectETag string `json:"object_etag,omitempty"` - ObjectVersionID string `json:"object_version_id,omitempty"` - Consistency string `json:"consistency"` - CleanupPending bool `json:"cleanup_pending,omitempty"` + BackupKey string `json:"backup_key"` + SizeBytes int64 `json:"size_bytes"` + VirtualSizeBytes uint64 `json:"virtual_size_bytes"` + SHA256 string `json:"sha256"` + ObjectETag string `json:"object_etag,omitempty"` + ObjectVersionID string `json:"object_version_id,omitempty"` + Consistency string `json:"consistency"` + CleanupPending bool `json:"cleanup_pending,omitempty"` + SourceContract *PortableRestoreContract `json:"source_contract,omitempty"` } // RestoreBackupRequest is deliberately flat on the wire so it matches the diff --git a/agent/hypervisor/types_test.go b/agent/hypervisor/types_test.go index e7fe0d7c..28b91aac 100644 --- a/agent/hypervisor/types_test.go +++ b/agent/hypervisor/types_test.go @@ -80,6 +80,43 @@ func TestPublicNetworkCapabilityWireContractIncludesNDPGuardReadiness(t *testing } } +func TestPortableRestoreContractWireShapeIsFixedAndPathFree(t *testing.T) { + contract := fixedPortableRestoreContract() + encoded, err := json.Marshal(contract) + if err != nil { + t.Fatalf("marshal portable restore contract: %v", err) + } + var wire map[string]any + if err := json.Unmarshal(encoded, &wire); err != nil { + t.Fatalf("decode portable restore contract: %v", err) + } + if len(wire) != 9 || wire["contract"] != float64(1) || + wire["architecture"] != "x86_64" || wire["machine"] != "q35" || + wire["firmware"] != "uefi" || wire["secure_boot"] != false || + wire["disk_format"] != "qcow2" || wire["system_disk_only"] != true || + wire["public_network_contract"] != float64(1) || + wire["vpc_inherited"] != false { + t.Fatalf("portable restore contract = %#v", wire) + } + for _, value := range wire { + if text, ok := value.(string); ok && len(text) > 0 && text[0] == '/' { + t.Fatalf("host path escaped in portable restore contract: %#v", wire) + } + } + + encoded, err = json.Marshal(Capabilities{}) + if err != nil { + t.Fatal(err) + } + var capabilities map[string]any + if err := json.Unmarshal(encoded, &capabilities); err != nil { + t.Fatal(err) + } + if _, exists := capabilities["portable_restore"]; exists { + t.Fatalf("unverified portable restore capability was advertised: %#v", capabilities) + } +} + func TestPeerMigrationCapabilityAndStateWireContracts(t *testing.T) { encoded, err := json.Marshal(PeerMigrationCapability{ Version: 3, Endpoints: []string{"https://192.0.2.10:9443"}, diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index 06947f27..19486238 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -8,7 +8,7 @@ use App\Services\Config; /** Initializes only the clean-break PHP business and Agent log schemas. */ final class CloudSetup { - private const SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'; + private const SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'; private const MAIN_TABLES = [ 'cloud_regions', 'cloud_traffic_pool_groups', 'cloud_network_lines', 'cloud_resource_pools', @@ -71,6 +71,8 @@ final class CloudSetup 'cloud_host_agents' => [ 'host_id', 'revision', 'tested_revision', 'network_selectors_json', 'public_network_capabilities_json', + 'portable_restore_contract_json', + 'portable_restore_contract_sha256', 'last_tested_at', ], 'cloud_host_network_attachments' => [ @@ -265,6 +267,8 @@ final class CloudSetup 'subscription_id', 'scheduled_for', 'state', 'consistency', 'object_key', 'object_size_bytes', 'virtual_size_bytes', 'sha256', 'object_etag', 'object_version_id', 'spec_json', + 'source_portable_restore_contract_json', + 'source_portable_restore_contract_sha256', 'sealed_storage_runtime', 'sealed_credential', 'storage_revision', 'active_job_id', 'last_operation_id', 'delete_operation_id', 'delete_generation', diff --git a/web/app/Models/CloudHostAgent.php b/web/app/Models/CloudHostAgent.php index e37d1e06..6d2e91af 100644 --- a/web/app/Models/CloudHostAgent.php +++ b/web/app/Models/CloudHostAgent.php @@ -2,6 +2,8 @@ namespace App\Models; +use App\Services\Cloud\CloudPortableRestoreCompatibility; + final class CloudHostAgent extends Model { protected $connection = 'default'; @@ -12,6 +14,8 @@ final class CloudHostAgent extends Model protected $attributes = [ 'network_selectors_json' => '[]', 'public_network_capabilities_json' => '{}', + 'portable_restore_contract_json' => '{}', + 'portable_restore_contract_sha256' => '', ]; protected $casts = [ 'host_id' => 'int', @@ -44,4 +48,20 @@ final class CloudHostAgent extends Model } return $decoded; } + + /** Exact portable-restore proof from this current tested revision. */ + public function testedPortableRestoreCompatibility(): ?CloudPortableRestoreCompatibility + { + if (!$this->isReady()) { + return null; + } + try { + return CloudPortableRestoreCompatibility::fromStored( + (string) $this->portable_restore_contract_json, + (string) $this->portable_restore_contract_sha256 + ); + } catch (\InvalidArgumentException) { + return null; + } + } } diff --git a/web/app/Models/CloudInstanceBackup.php b/web/app/Models/CloudInstanceBackup.php index 8af4fa45..63bf4b29 100644 --- a/web/app/Models/CloudInstanceBackup.php +++ b/web/app/Models/CloudInstanceBackup.php @@ -2,6 +2,8 @@ namespace App\Models; +use App\Services\Cloud\CloudPortableRestoreCompatibility; + /** Portable system-disk backup stored outside its source host. */ final class CloudInstanceBackup extends Model { @@ -33,4 +35,20 @@ final class CloudInstanceBackup extends Model 'created_at' => 'int', 'updated_at' => 'int', ]; + + /** A ready legacy row without exact Agent evidence is intentionally incompatible. */ + public function sourcePortableRestoreCompatibility(): ?CloudPortableRestoreCompatibility + { + if ((string) $this->state !== 'ready') { + return null; + } + try { + return CloudPortableRestoreCompatibility::fromStored( + (string) $this->source_portable_restore_contract_json, + (string) $this->source_portable_restore_contract_sha256 + ); + } catch (\InvalidArgumentException) { + return null; + } + } } diff --git a/web/app/Services/Cloud/CloudAgentSettingsService.php b/web/app/Services/Cloud/CloudAgentSettingsService.php index 2be1f2f6..1fc0507d 100644 --- a/web/app/Services/Cloud/CloudAgentSettingsService.php +++ b/web/app/Services/Cloud/CloudAgentSettingsService.php @@ -192,7 +192,7 @@ final class CloudAgentSettingsService $summary = self::capabilitySummary($capabilities); self::recordTest($hostId, $expectedRevision, 'healthy', '', $health['version'], $summary['network_selectors'], - $summary['public_network']); + $summary['public_network'], $summary['portable_restore']); self::scheduleTemplateBackfill($hostId, $actor, 'agent_ready'); self::scheduleRescueBackfill($hostId, $actor, 'agent_ready'); $fresh = CloudHostAgent::find($hostId); @@ -235,6 +235,9 @@ final class CloudAgentSettingsService $publicNetwork = self::normalizePublicNetworkCapabilities( $capabilities['public_network'] ?? null ); + $portableRestore = self::normalizePortableRestoreCompatibility( + $capabilities['portable_restore'] ?? null + ); $known = array_merge(self::REQUIRED_FEATURES, ['uefi', 'secure_boot']); foreach ($known as $feature) { @@ -269,6 +272,7 @@ final class CloudAgentSettingsService 'storage_configuration' => true, 'network_selectors' => $selectors, 'public_network' => $publicNetwork, + 'portable_restore' => $portableRestore, 'required_feature_count' => count(self::REQUIRED_FEATURES), 'available_features' => self::REQUIRED_FEATURES, 'unavailable_features' => [], @@ -285,6 +289,8 @@ final class CloudAgentSettingsService $setting->last_agent_version = ''; $setting->network_selectors_json = '[]'; $setting->public_network_capabilities_json = '{}'; + $setting->portable_restore_contract_json = '{}'; + $setting->portable_restore_contract_sha256 = ''; $setting->last_tested_at = 0; $setting->updated_at = time(); $setting->save(); @@ -445,7 +451,8 @@ final class CloudAgentSettingsService string $errorCode, string $version, array $networkSelectors = [], - array $publicNetworkCapabilities = [] + array $publicNetworkCapabilities = [], + array $portableRestoreCompatibility = [] ): void { $encodedSelectors = $status === 'healthy' ? json_encode( @@ -461,6 +468,10 @@ final class CloudAgentSettingsService JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES ) : '{}'; + $portableRestore = $status === 'healthy' + ? CloudPortableRestoreCompatibility::fromPayload( + $portableRestoreCompatibility + ) : null; $updated = CloudHostAgent::query()->where('host_id', $hostId) ->where('revision', $expectedRevision)->update([ 'last_test_status' => $status, @@ -470,6 +481,10 @@ final class CloudAgentSettingsService 'last_agent_version' => substr($version, 0, 64), 'network_selectors_json' => $encodedSelectors, 'public_network_capabilities_json' => $encodedPublicNetwork, + 'portable_restore_contract_json' => $portableRestore === null + ? '{}' : $portableRestore->json(), + 'portable_restore_contract_sha256' => $portableRestore === null + ? '' : $portableRestore->sha256(), 'last_tested_at' => time(), 'updated_at' => time(), ]); @@ -511,6 +526,24 @@ final class CloudAgentSettingsService ]; } + private static function normalizePortableRestoreCompatibility( + mixed $value + ): array { + try { + return CloudPortableRestoreCompatibility::fromPayload( + $value + )->toArray(); + } catch (\InvalidArgumentException) { + throw new CloudAgentError( + '宿主机 Agent 未满足可移植恢复平台合同', + 409, + 'agent_capability_mismatch', + false, + 200 + ); + } + } + private static function normalizeNetworkSelectors(mixed $selectors): array { if (!is_array($selectors) || !array_is_list($selectors) diff --git a/web/app/Services/Cloud/CloudBackupService.php b/web/app/Services/Cloud/CloudBackupService.php index ac9812a8..f572043c 100644 --- a/web/app/Services/Cloud/CloudBackupService.php +++ b/web/app/Services/Cloud/CloudBackupService.php @@ -8,6 +8,7 @@ use App\Models\CloudBackupPeriodEntitlement; use App\Models\CloudBackupSubscription; use App\Models\CloudDeploymentSnapshot; use App\Models\CloudHost; +use App\Models\CloudHostAgent; use App\Models\CloudInstance; use App\Models\CloudInstanceBackup; use App\Models\CloudInstanceMigration; @@ -759,6 +760,17 @@ final class CloudBackupService } self::assertManagedSource($locked); self::assertNoActiveJob($locked); + $hostAgent = CloudHostAgent::where( + 'host_id', (int) $locked->host_id + )->first(); + $sourceCompatibility = $hostAgent?-> + testedPortableRestoreCompatibility(); + if ($sourceCompatibility === null) { + throw new CloudError( + '源宿主机当前版本尚未通过可移植恢复能力测试', + 409 + ); + } $usedQuery = CloudInstanceBackup::where( 'source_instance_id', (int) $locked->id )->where('purpose', 'portable') @@ -845,6 +857,8 @@ final class CloudBackupService $backup->object_size_bytes = 0; $backup->virtual_size_bytes = 0; $backup->sha256 = ''; + $backup->source_portable_restore_contract_json = '{}'; + $backup->source_portable_restore_contract_sha256 = ''; $backup->spec_json = json_encode( CloudInput::safeResult($spec), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES @@ -877,6 +891,8 @@ final class CloudBackupService 'can_manage' => true, 'backup_key' => $key, 'maximum_size_bytes' => $maximumBytes, + 'source_portable_restore_contract_sha256' => + $sourceCompatibility->sha256(), ], $canonicalRequest ); @@ -1551,6 +1567,17 @@ final class CloudBackupService $backup->error_code = 'backup_failed'; $backup->active_job_id = null; } elseif ($status === 'succeeded') { + try { + $sourceCompatibility = + CloudPortableRestoreCompatibility::fromPayload( + is_array($result) + ? ($result['source_contract'] ?? null) : null + ); + } catch (\InvalidArgumentException $error) { + throw new CloudError( + 'Agent 成功结果缺少可信可移植恢复合同', 502 + ); + } $size = filter_var($result['size_bytes'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); $virtual = filter_var($result['virtual_size_bytes'] ?? null, @@ -1560,6 +1587,8 @@ final class CloudBackupService $objectVersionId = $result['object_version_id'] ?? ''; $consistency = $result['consistency'] ?? null; $cleanupPending = $result['cleanup_pending'] ?? false; + $expectedContractSHA = + $payload['source_portable_restore_contract_sha256'] ?? null; if (!is_array($result) || !hash_equals((string) $backup->backup_key, (string) ($result['backup_key'] ?? '')) @@ -1574,6 +1603,13 @@ final class CloudBackupService || ($objectVersionId !== '' && $objectEtag === '') || !in_array($consistency, ['filesystem', 'crash'], true) || !is_bool($cleanupPending) + || !is_string($expectedContractSHA) + || preg_match('/^[a-f0-9]{64}$/D', + $expectedContractSHA) !== 1 + || !hash_equals( + $expectedContractSHA, + $sourceCompatibility->sha256() + ) || (int) $size > (int) ($payload['maximum_size_bytes'] ?? 0)) { throw new CloudError('Agent 成功结果缺少可信备份对象身份', 502); } @@ -1584,6 +1620,10 @@ final class CloudBackupService $backup->sha256 = $sha; $backup->object_etag = $objectEtag; $backup->object_version_id = $objectVersionId; + $backup->source_portable_restore_contract_json = + $sourceCompatibility->json(); + $backup->source_portable_restore_contract_sha256 = + $sourceCompatibility->sha256(); $backup->ready_at = $now; $backup->active_job_id = null; // The remote object is complete and restorable. A host-side diff --git a/web/app/Services/Cloud/CloudPortableRestoreCompatibility.php b/web/app/Services/Cloud/CloudPortableRestoreCompatibility.php new file mode 100644 index 00000000..cf9769e7 --- /dev/null +++ b/web/app/Services/Cloud/CloudPortableRestoreCompatibility.php @@ -0,0 +1,92 @@ + 1, + 'architecture' => 'x86_64', + 'machine' => 'q35', + 'firmware' => 'uefi', + 'secure_boot' => false, + 'disk_format' => 'qcow2', + 'system_disk_only' => true, + 'public_network_contract' => 1, + 'vpc_inherited' => false, + ]; + + private function __construct() + { + } + + public static function fromPayload(mixed $value): self + { + if (!is_array($value) || array_is_list($value) + || count($value) !== count(self::CONTRACT)) { + throw new \InvalidArgumentException( + 'Portable restore contract has an invalid shape' + ); + } + foreach (self::CONTRACT as $name => $expected) { + if (!array_key_exists($name, $value) || $value[$name] !== $expected) { + throw new \InvalidArgumentException( + 'Portable restore contract is unsupported' + ); + } + } + return new self(); + } + + public static function fromStored(string $json, string $sha256): self + { + if (preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1) { + throw new \InvalidArgumentException( + 'Portable restore contract digest is invalid' + ); + } + try { + $value = json_decode($json, true, 8, JSON_THROW_ON_ERROR); + } catch (\JsonException $error) { + throw new \InvalidArgumentException( + 'Portable restore contract JSON is invalid', 0, $error + ); + } + $contract = self::fromPayload($value); + if (!hash_equals($contract->json(), $json) + || !hash_equals($contract->sha256(), $sha256)) { + throw new \InvalidArgumentException( + 'Portable restore contract evidence does not match' + ); + } + return $contract; + } + + public function toArray(): array + { + return self::CONTRACT; + } + + public function json(): string + { + return json_encode( + self::CONTRACT, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ); + } + + public function sha256(): string + { + return hash('sha256', $this->json()); + } + + public function matches(self $other): bool + { + return hash_equals($this->sha256(), $other->sha256()); + } +} diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index dbe82a97..9960838e 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -96,6 +96,8 @@ CREATE TABLE cloud_host_agents ( last_agent_version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', network_selectors_json LONGTEXT NOT NULL, public_network_capabilities_json LONGTEXT NOT NULL, + portable_restore_contract_json LONGTEXT NOT NULL, + portable_restore_contract_sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', last_tested_at BIGINT UNSIGNED NOT NULL DEFAULT 0, created_at BIGINT UNSIGNED NOT NULL, updated_at BIGINT UNSIGNED NOT NULL, @@ -1186,6 +1188,8 @@ CREATE TABLE cloud_instance_backups ( sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', object_etag VARCHAR(256) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', object_version_id VARCHAR(1024) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', + source_portable_restore_contract_json LONGTEXT NOT NULL, + source_portable_restore_contract_sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', spec_json LONGTEXT NOT NULL, sealed_storage_runtime LONGTEXT NOT NULL, sealed_credential LONGTEXT DEFAULT NULL, diff --git a/web/tests/CloudAgentActivationGateTest.php b/web/tests/CloudAgentActivationGateTest.php index 63e2cdd3..a8353a68 100644 --- a/web/tests/CloudAgentActivationGateTest.php +++ b/web/tests/CloudAgentActivationGateTest.php @@ -61,6 +61,8 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->string('last_agent_version')->default(''); $table->text('network_selectors_json')->default('[]'); $table->text('public_network_capabilities_json')->default('{}'); + $table->text('portable_restore_contract_json')->default('{}'); + $table->string('portable_restore_contract_sha256', 64)->default(''); $table->integer('last_tested_at')->default(0); $table->integer('created_at'); $table->integer('updated_at'); @@ -114,8 +116,14 @@ $publicNetwork = [ 'project_owned_filter' => true, 'ndp_guard' => true, ]; +$portableRestore = [ + 'contract' => 1, 'architecture' => 'x86_64', 'machine' => 'q35', + 'firmware' => 'uefi', 'secure_boot' => false, 'disk_format' => 'qcow2', + 'system_disk_only' => true, 'public_network_contract' => 1, + 'vpc_inherited' => false, +]; $recordTest->invoke(null, (int) $host->id, 1, 'healthy', '', 'test-1', - ['bridge:br0'], $publicNetwork); + ['bridge:br0'], $publicNetwork, $portableRestore); $ready = CloudAgentSettingsService::read((int) $host->id); $assert($ready['ready'] === true && $ready['tested_revision'] === 1 && (string) CloudHostAgent::find((int) $host->id) @@ -163,7 +171,7 @@ $assert($rotated['revision'] === 2 && CloudAgentSettingsService::enabledHostIds() === [], 'Rotating an Agent secret retained the prior readiness result.'); $recordTest->invoke(null, (int) $host->id, 2, 'healthy', '', 'test-2', - ['bridge:br0'], $publicNetwork); + ['bridge:br0'], $publicNetwork, $portableRestore); $changed = CloudAgentSettingsService::save((int) $host->id, [ 'enabled' => false, @@ -178,7 +186,7 @@ $assert($changed['revision'] === 3 && $changed['enabled'] === false 'Changing an Agent setting retained the prior revision readiness.'); $recordTest->invoke(null, (int) $host->id, 3, 'healthy', '', 'test-3', - ['bridge:br0'], $publicNetwork); + ['bridge:br0'], $publicNetwork, $portableRestore); $recordTest->invoke(null, (int) $host->id, 3, 'unhealthy', 'agent_unavailable', ''); $failed = CloudHostAgent::find((int) $host->id); @@ -216,7 +224,7 @@ foreach (['bridge:br9', 'network:default'] as $network) { $setting->enabled = true; $setting->save(); $recordTest->invoke(null, (int) $host->id, $revision, 'healthy', '', - 'test-current', [$network], $publicNetwork); + 'test-current', [$network], $publicNetwork, $portableRestore); $saveHostNetwork($network); $setting->refresh(); $assert($host->fresh()->default_network === $network diff --git a/web/tests/CloudAgentPanelContractTest.php b/web/tests/CloudAgentPanelContractTest.php index 7b904800..8538328c 100644 --- a/web/tests/CloudAgentPanelContractTest.php +++ b/web/tests/CloudAgentPanelContractTest.php @@ -14,6 +14,7 @@ $middleware = $read('app/Middleware/CloudApi.php'); $controller = $read('app/Controllers/CloudAdminAgentController.php'); $apiController = $read('app/Controllers/CloudApiController.php'); $service = $read('app/Services/Cloud/CloudAgentSettingsService.php'); +$backupService = $read('app/Services/Cloud/CloudBackupService.php'); $cipher = $read('app/Services/Cloud/CloudAgentSecretCipher.php'); $client = $read('app/Services/Cloud/CloudAgentClient.php'); $gatewayEndpoint = $read('app/Services/Cloud/CloudAgentGatewayEndpoint.php'); @@ -34,6 +35,10 @@ $assert(str_contains($schema, 'CREATE TABLE cloud_host_agents') && str_contains($schema, 'network_selectors_json LONGTEXT NOT NULL') && str_contains($schema, 'public_network_capabilities_json LONGTEXT NOT NULL') + && str_contains($schema, + 'portable_restore_contract_json LONGTEXT NOT NULL') + && str_contains($schema, + 'portable_restore_contract_sha256 CHAR(64)') && str_contains($schema, 'CREATE TABLE cloud_templates') && str_contains($schema, 'startup_script MEDIUMTEXT NOT NULL') && str_contains($schema, 'generation_token CHAR(32)') @@ -86,6 +91,10 @@ $assert(str_contains($service, '$setting->tested_revision = 0') && str_contains($service, "'network_selectors_json' => \$encodedSelectors") && str_contains($service, "'public_network_capabilities_json' => \$encodedPublicNetwork") + && str_contains($service, + "'portable_restore_contract_json' => \$portableRestore === null") + && str_contains($service, + "'portable_restore_contract_sha256' => \$portableRestore === null") && str_contains($service, 'public static function publicNetworkReady(') && str_contains($service, 'private const PUBLIC_NETWORK_CONTRACT = 1;') && str_contains($service, "'dual_stack_required' => true") @@ -97,6 +106,17 @@ $assert(str_contains($service, '$setting->tested_revision = 0') && str_contains($browser, '未就绪,不参与调度') && str_contains($page, '全部通过才标记就绪'), 'Saved Agent revisions can become schedulable before current-revision tests pass.'); +$assert(preg_match( + '/CloudHostAgent::where\(\s*[\'\"]host_id[\'\"],\s*' + . '\(int\) \$locked->host_id\s*\)->first\(\)/s', + $backupService + ) === 1 + && preg_match( + '/CloudHostAgent::where\(\s*[\'\"]host_id[\'\"],\s*' + . '\(int\) \$locked->host_id\s*\)->lockForUpdate\(\)/s', + $backupService + ) !== 1, + 'Backup creation must not reverse the host-agent to instance lock order.'); $assert(str_contains($client, "'X-Virt-Timestamp'") && str_contains($client, "'X-Virt-Content-SHA256'") && str_contains($client, "'X-Virt-Signature'") diff --git a/web/tests/CloudAgentPublicNetworkCapabilityTest.php b/web/tests/CloudAgentPublicNetworkCapabilityTest.php index 17e75e13..9eb65191 100644 --- a/web/tests/CloudAgentPublicNetworkCapabilityTest.php +++ b/web/tests/CloudAgentPublicNetworkCapabilityTest.php @@ -51,6 +51,8 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->string('last_agent_version'); $table->text('network_selectors_json'); $table->text('public_network_capabilities_json'); + $table->text('portable_restore_contract_json'); + $table->string('portable_restore_contract_sha256', 64); $table->integer('last_tested_at'); $table->integer('created_at'); $table->integer('updated_at'); @@ -69,11 +71,18 @@ $publicNetwork = [ 'project_owned_filter' => true, 'ndp_guard' => true, ]; +$portableRestore = [ + 'contract' => 1, 'architecture' => 'x86_64', 'machine' => 'q35', + 'firmware' => 'uefi', 'secure_boot' => false, 'disk_format' => 'qcow2', + 'system_disk_only' => true, 'public_network_contract' => 1, + 'vpc_inherited' => false, +]; $capabilities = [ 'backend' => 'libvirt', 'features' => $features, 'network_selectors' => ['bridge:br0'], 'public_network' => $publicNetwork + ['untrusted_extension' => true], + 'portable_restore' => $portableRestore, 'checks' => ['storage_configuration' => ['available' => true]], ]; $summaryMethod = new ReflectionMethod( @@ -107,6 +116,8 @@ Capsule::table('cloud_host_agents')->insert([ 'last_test_status' => 'never', 'last_error_code' => '', 'last_agent_version' => '', 'network_selectors_json' => '[]', 'public_network_capabilities_json' => '{}', 'last_tested_at' => 0, + 'portable_restore_contract_json' => '{}', + 'portable_restore_contract_sha256' => '', 'created_at' => $now, 'updated_at' => $now, ]); $recordTest = new ReflectionMethod(CloudAgentSettingsService::class, 'recordTest'); @@ -118,7 +129,8 @@ $recordTest->invoke( '', 'test-agent', ['bridge:br0'], - $publicNetwork + $publicNetwork, + $portableRestore ); $agent = CloudHostAgent::find(1); $assert($agent !== null @@ -128,6 +140,7 @@ $assert($agent !== null 8, JSON_THROW_ON_ERROR ) === $publicNetwork + && $agent->testedPortableRestoreCompatibility() !== null && CloudAgentSettingsService::publicNetworkReady( $agent, 'bridge:br0', 4 ) @@ -154,6 +167,8 @@ $assert(!CloudAgentSettingsService::publicNetworkReady( CloudAgentSettingsService::invalidateReadiness($agent); $agent->refresh(); $assert((string) $agent->public_network_capabilities_json === '{}' + && (string) $agent->portable_restore_contract_json === '{}' + && (string) $agent->portable_restore_contract_sha256 === '' && !CloudAgentSettingsService::publicNetworkReady( $agent, 'bridge:br0', 5 ), diff --git a/web/tests/CloudAgentReadinessContractTest.php b/web/tests/CloudAgentReadinessContractTest.php index cd6dbd99..62bdb067 100644 --- a/web/tests/CloudAgentReadinessContractTest.php +++ b/web/tests/CloudAgentReadinessContractTest.php @@ -72,9 +72,21 @@ $assert($agentRequired === $required 'PHP required capabilities diverged from the Go Agent feature contract.'); $features = array_fill_keys($agentFeatureKeys, true); $features['secure_boot'] = false; +$publicNetwork = [ + 'contract' => 1, 'dual_stack_required' => true, + 'project_owned_filter' => true, 'ndp_guard' => true, +]; +$portableRestore = [ + 'contract' => 1, 'architecture' => 'x86_64', 'machine' => 'q35', + 'firmware' => 'uefi', 'secure_boot' => false, 'disk_format' => 'qcow2', + 'system_disk_only' => true, 'public_network_contract' => 1, + 'vpc_inherited' => false, +]; $summary = $capabilitySummary->invoke(null, [ 'backend' => 'libvirt', 'features' => $features, 'network_selectors' => ['bridge:br0', 'network:default'], + 'public_network' => $publicNetwork, + 'portable_restore' => $portableRestore, 'checks' => ['storage_configuration' => ['available' => true]], ]); $assert($summary === [ @@ -83,6 +95,8 @@ $assert($summary === [ 'secure_boot' => false, 'storage_configuration' => true, 'network_selectors' => ['bridge:br0', 'network:default'], + 'public_network' => $publicNetwork, + 'portable_restore' => $portableRestore, 'required_feature_count' => 15, 'available_features' => $required, 'unavailable_features' => [], @@ -102,8 +116,21 @@ $expectCapabilityError = static function (array $capabilities, }; $validSelectors = [ 'network_selectors' => ['bridge:br0'], + 'public_network' => $publicNetwork, + 'portable_restore' => $portableRestore, 'checks' => ['storage_configuration' => ['available' => true]], ]; +foreach (array_keys($portableRestore) as $field) { + $broken = $portableRestore; + unset($broken[$field]); + $expectCapabilityError([ + 'backend' => 'libvirt', 'features' => $features, + 'network_selectors' => ['bridge:br0'], + 'public_network' => $publicNetwork, + 'portable_restore' => $broken, + 'checks' => ['storage_configuration' => ['available' => true]], + ], 'agent_capability_mismatch', 409); +} $invalidBackend = ['backend' => 'qemu', 'features' => $features] + $validSelectors; $expectCapabilityError($invalidBackend, 'agent_invalid_capabilities', 502); @@ -133,6 +160,8 @@ foreach ([ array_fill(0, 65, 'bridge:br0'), ] as $invalidSelectors) { $payload = ['backend' => 'libvirt', 'features' => $features, + 'public_network' => $publicNetwork, + 'portable_restore' => $portableRestore, 'checks' => ['storage_configuration' => ['available' => true]]]; if ($invalidSelectors !== null) { $payload['network_selectors'] = $invalidSelectors; @@ -142,6 +171,8 @@ foreach ([ $alternateSummary = $capabilitySummary->invoke(null, [ 'backend' => 'libvirt', 'features' => $features, 'network_selectors' => ['network:default'], + 'public_network' => $publicNetwork, + 'portable_restore' => $portableRestore, 'checks' => ['storage_configuration' => ['available' => true]], ]); $assert($alternateSummary['network_selectors'] === ['network:default'], @@ -150,6 +181,8 @@ $expectCapabilityError([ 'backend' => 'libvirt', 'features' => array_replace($features, ['create_vm' => false]), 'network_selectors' => ['bridge:br0'], + 'public_network' => $publicNetwork, + 'portable_restore' => $portableRestore, 'checks' => ['storage_configuration' => [ 'available' => false, 'reason' => 'not_configured', ]], diff --git a/web/tests/CloudConsoleTicketServiceTest.php b/web/tests/CloudConsoleTicketServiceTest.php index c0dfd67b..a191fd82 100644 --- a/web/tests/CloudConsoleTicketServiceTest.php +++ b/web/tests/CloudConsoleTicketServiceTest.php @@ -74,6 +74,9 @@ namespace { $table->integer('tested_revision'); $table->string('last_test_status'); $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json')->default('{}'); + $table->text('portable_restore_contract_json')->default('{}'); + $table->string('portable_restore_contract_sha256', 64)->default(''); }); $schema->create('cloud_hosts', static function (Blueprint $table): void { $table->integer('id')->primary(); diff --git a/web/tests/CloudFreshSchemaContractTest.php b/web/tests/CloudFreshSchemaContractTest.php index 0e1ef24a..6ab91f3d 100644 --- a/web/tests/CloudFreshSchemaContractTest.php +++ b/web/tests/CloudFreshSchemaContractTest.php @@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false $assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema), 'cloud.sql retained an engine-prefixed identifier.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'") + "SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'") && !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"), 'Outbound Agent schema must reject the incompatible earlier Go database.'); $assert(str_contains($schema, @@ -147,6 +147,18 @@ $assert(str_contains($schema, && str_contains($setup, "'object_etag', 'object_version_id'") && str_contains($setup, "'cloud_instance_backup_delete_due'"), 'Fresh backup schema is missing exact-version cleanup debt fields or index.'); +$assert(str_contains($schema, + 'portable_restore_contract_json LONGTEXT NOT NULL') + && str_contains($schema, + 'portable_restore_contract_sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL') + && str_contains($schema, + 'source_portable_restore_contract_json LONGTEXT NOT NULL') + && str_contains($schema, + 'source_portable_restore_contract_sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL') + && str_contains($setup, "'portable_restore_contract_json'") + && str_contains($setup, + "'source_portable_restore_contract_json'"), + 'Fresh schema is missing frozen portable-restore capability evidence.'); $assert(str_contains($schema, 'CREATE TABLE cloud_backup_period_entitlements (') && str_contains($schema, diff --git a/web/tests/CloudPortableBackupFinalizerTest.php b/web/tests/CloudPortableBackupFinalizerTest.php index 1953cd5b..cb9be959 100644 --- a/web/tests/CloudPortableBackupFinalizerTest.php +++ b/web/tests/CloudPortableBackupFinalizerTest.php @@ -7,6 +7,9 @@ use App\Models\CloudInstance; use App\Models\CloudInstanceBackup; use App\Models\CloudJob; use App\Services\Cloud\CloudBackupService; +use App\Services\Cloud\CloudError; +use App\Services\Cloud\CloudPortableRestoreCompatibility; +use App\Services\Cloud\CloudPublicNetworkTransitionGate; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -42,6 +45,9 @@ $schema->create('cloud_instance_backups', $table->string('sha256')->default(''); $table->string('object_etag')->default(''); $table->string('object_version_id')->default(''); + $table->text('source_portable_restore_contract_json')->default('{}'); + $table->string('source_portable_restore_contract_sha256', 64) + ->default(''); $table->text('spec_json'); $table->text('sealed_storage_runtime'); $table->text('sealed_credential')->nullable(); @@ -152,6 +158,14 @@ $schema->create('cloud_instance_runtime', }); $now = time(); +$portableRestore = [ + 'contract' => 1, 'architecture' => 'x86_64', 'machine' => 'q35', + 'firmware' => 'uefi', 'secure_boot' => false, 'disk_format' => 'qcow2', + 'system_disk_only' => true, 'public_network_contract' => 1, + 'vpc_inherited' => false, +]; +$portableCompatibility = + CloudPortableRestoreCompatibility::fromPayload($portableRestore); $sourceSpec = [ 'managed' => true, 'os_source' => 'cloud_template', @@ -207,10 +221,13 @@ CloudBackupService::finishJobLocked($createJob, 'succeeded', [ 'object_version_id' => 'finalizer-version', 'consistency' => 'filesystem', 'cleanup_pending' => true, + 'source_contract' => $portableRestore, ], [ 'owner_id' => 9, 'backup_key' => str_repeat('a', 32), 'maximum_size_bytes' => 21 * 1073741824, + 'source_portable_restore_contract_sha256' => + $portableCompatibility->sha256(), ]); $createdBackup = CloudInstanceBackup::findOrFail(1); $assert((string) $createdBackup->state === 'ready' @@ -220,10 +237,62 @@ $assert((string) $createdBackup->state === 'ready' && (string) $createdBackup->sha256 === str_repeat('b', 64) && (string) $createdBackup->object_etag === '"finalizer-etag"' && (string) $createdBackup->object_version_id === 'finalizer-version' + && (string) $createdBackup->source_portable_restore_contract_json + === $portableCompatibility->json() + && (string) $createdBackup->source_portable_restore_contract_sha256 + === $portableCompatibility->sha256() + && $createdBackup->sourcePortableRestoreCompatibility() !== null && $createdBackup->active_job_id === null && $createdBackup->ready_at !== null, 'Cleanup-pending backup lost its ready/restorable object identity.'); +// A successful transport receipt without actual platform evidence must never +// promote a clean-break backup into the ready catalog. +$missingContractOperation = str_repeat('8', 32); +$capsule->table('cloud_instance_backups')->insert([ + 'id' => 2, 'backup_key' => str_repeat('d', 32), + 'source_instance_id' => 102, 'source_host_id' => 3, 'user_id' => 9, + 'source_uuid' => '22222222-2222-4222-8222-222222222222', + 'name' => 'missing-contract', 'state' => 'creating', + 'consistency' => 'crash', + 'object_key' => 'vm-backups/d/system.qcow2', + 'spec_json' => json_encode($sourceSpec, JSON_THROW_ON_ERROR), + 'sealed_storage_runtime' => 'sealed-runtime', + 'sealed_credential' => 'sealed-source-credential', + 'active_job_id' => 3, 'last_operation_id' => $missingContractOperation, + 'created_at' => $now, 'updated_at' => $now, +]); +$capsule->table('cloud_jobs')->insert([ + 'id' => 3, 'kind' => 'backup_create', 'host_id' => 3, + 'instance_id' => 102, 'backup_id' => 2, + 'backup_restore_id' => null, 'operation_id' => $missingContractOperation, +]); +try { + CloudBackupService::finishJobLocked( + CloudJob::findOrFail(3), + 'succeeded', + [ + 'backup_key' => str_repeat('d', 32), 'size_bytes' => 1024, + 'virtual_size_bytes' => 20 * 1073741824, + 'sha256' => str_repeat('e', 64), 'object_etag' => 'etag', + 'object_version_id' => '', 'consistency' => 'crash', + 'cleanup_pending' => false, + ], + [ + 'owner_id' => 9, 'backup_key' => str_repeat('d', 32), + 'maximum_size_bytes' => 21 * 1073741824, + 'source_portable_restore_contract_sha256' => + $portableCompatibility->sha256(), + ] + ); + throw new RuntimeException('Missing source contract was accepted.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 502, + 'Missing source contract returned the wrong status.'); +} +$assert((string) CloudInstanceBackup::findOrFail(2)->state === 'creating', + 'Invalid source contract promoted a backup to ready.'); + $cleanupOperation = str_repeat('9', 32); $capsule->table('cloud_jobs')->insert([ 'id' => 2, @@ -399,85 +468,13 @@ $fixture = static function (int $id, string $outcome) use ( ]; }; -$success = $fixture(1, 'success'); -CloudBackupService::finishJobLocked( - $success['job'], 'succeeded', $success['result'], $success['payload'] -); -$successRestore = CloudBackupRestore::findOrFail($success['restore_id']); -$successInstance = CloudInstance::findOrFail($success['instance_id']); -$successReservation = $capsule->table('cloud_resource_reservations') - ->where('id', $success['reservation_id'])->first(); -$successIp = $capsule->table('cloud_public_ips') - ->where('id', $success['ip_id'])->first(); -$successRuntime = $capsule->table('cloud_instance_runtime') - ->where('instance_id', $success['instance_id'])->first(); -$successSpec = json_decode((string) $successInstance->spec_json, true, - flags: JSON_THROW_ON_ERROR); -$assert((string) $successRestore->state === 'ready' - && $successRestore->ready_at !== null - && (string) $successReservation->state === 'committed' - && (int) $successReservation->instance_id === $success['instance_id'] - && (string) $successIp->state === 'assigned' - && (int) $successIp->instance_id === $success['instance_id'] - && (string) $successInstance->status === 'active' - && (string) $successInstance->service_status === 'exempt' - && (string) $successInstance->network_status === 'active' - && ($successSpec['public_ip_cidr'] ?? null) === $success['cidr'] - && ($successSpec['public_ip_cidr'] ?? null) - !== $sourceSpec['public_ip_cidr'] - && ($successSpec['restored_from_backup'] ?? null) - === (string) CloudInstanceBackup::findOrFail( - $success['backup_id'] - )->backup_key - && ($successSpec['managed'] ?? null) === true - && (string) $successRuntime->power_state === 'running', - 'Successful restore did not commit the fresh IP and activate an exempt independent instance.'); - -// CloudWorkerService may call failed only after recovery proves not_applied. -$failed = $fixture(2, 'failed'); -CloudBackupService::finishJobLocked( - $failed['job'], 'failed', [], $failed['payload'] -); -$failedRestore = CloudBackupRestore::findOrFail($failed['restore_id']); -$failedInstance = CloudInstance::findOrFail($failed['instance_id']); -$failedReservation = $capsule->table('cloud_resource_reservations') - ->where('id', $failed['reservation_id'])->first(); -$failedIp = $capsule->table('cloud_public_ips') - ->where('id', $failed['ip_id'])->first(); -$assert((string) $failedRestore->state === 'failed' - && (string) $failedReservation->state === 'released' - && (string) $failedReservation->release_reason - === 'backup_restore_not_applied' - && (string) $failedIp->state === 'available' - && $failedIp->reservation_id === null - && $failedIp->instance_id === null - && $failedIp->operation_id === null - && (string) $failedInstance->status === 'deleted' - && (string) $failedInstance->network_status === 'inactive' - && $failedInstance->sealed_credential === null, - 'Proven-not-applied restore did not release capacity/IP and erase the failed target credential.'); - -$uncertain = $fixture(3, 'uncertain'); -CloudBackupService::finishJobLocked( - $uncertain['job'], 'uncertain', [], $uncertain['payload'] -); -$uncertainRestore = CloudBackupRestore::findOrFail($uncertain['restore_id']); -$uncertainInstance = CloudInstance::findOrFail($uncertain['instance_id']); -$uncertainReservation = $capsule->table('cloud_resource_reservations') - ->where('id', $uncertain['reservation_id'])->first(); -$uncertainIp = $capsule->table('cloud_public_ips') - ->where('id', $uncertain['ip_id'])->first(); -$assert((string) $uncertainRestore->state === 'uncertain' - && (string) $uncertainReservation->state === 'uncertain' - && (int) $uncertainReservation->instance_id === $uncertain['instance_id'] - && (string) $uncertainIp->state === 'uncertain' - && (int) $uncertainIp->reservation_id === $uncertain['reservation_id'] - && (string) $uncertainIp->operation_id - === (string) $uncertain['job']->operation_id - && (string) $uncertainInstance->status === 'provisioning' - && (string) $uncertainInstance->sealed_credential - === 'sealed-target-credential', - 'Unknown restore effect released resources, IP or target credentials.'); +try { + CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); + throw new RuntimeException('Portable restore gate unexpectedly opened.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Closed portable restore gate returned the wrong status.'); +} // In-place recovery keeps the existing instance identity and converges only // from an exact backup/ledger/Agent result tuple. @@ -561,4 +558,4 @@ $assert((string) $recovery->state === 'succeeded' === str_repeat('a', 32), 'In-place backup recovery did not preserve disk-authoritative guest identity and the current network.'); -echo "Portable backup create/restore finalizer behavior tests passed.\n"; +echo "Portable backup finalizers and closed restore gate passed.\n"; diff --git a/web/tests/CloudPortableBackupSourceContractFinalizerTest.php b/web/tests/CloudPortableBackupSourceContractFinalizerTest.php new file mode 100644 index 00000000..68e12012 --- /dev/null +++ b/web/tests/CloudPortableBackupSourceContractFinalizerTest.php @@ -0,0 +1,141 @@ +addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); +$schema->create('cloud_instance_backups', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('backup_key')->unique(); + $table->integer('source_instance_id'); + $table->integer('source_host_id'); + $table->integer('user_id'); + $table->string('source_uuid'); + $table->string('name'); + $table->string('state'); + $table->string('consistency'); + $table->string('object_key'); + $table->integer('object_size_bytes')->default(0); + $table->integer('virtual_size_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('object_etag')->default(''); + $table->string('object_version_id')->default(''); + $table->text('source_portable_restore_contract_json')->default('{}'); + $table->string('source_portable_restore_contract_sha256', 64)->default(''); + $table->text('spec_json'); + $table->text('sealed_storage_runtime'); + $table->text('sealed_credential')->nullable(); + $table->integer('storage_revision')->default(1); + $table->integer('active_job_id')->nullable(); + $table->string('last_operation_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('ready_at')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_jobs', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('kind'); + $table->integer('host_id'); + $table->integer('instance_id')->nullable(); + $table->integer('backup_id')->nullable(); + $table->integer('user_id')->nullable(); + $table->string('operation_id')->unique(); +}); + +$payload = [ + 'contract' => 1, 'architecture' => 'x86_64', 'machine' => 'q35', + 'firmware' => 'uefi', 'secure_boot' => false, 'disk_format' => 'qcow2', + 'system_disk_only' => true, 'public_network_contract' => 1, + 'vpc_inherited' => false, +]; +$contract = CloudPortableRestoreCompatibility::fromPayload($payload); +$now = time(); +$create = static function (int $id, string $key, string $operation) use ( + $capsule, $now +): CloudJob { + $capsule->table('cloud_instance_backups')->insert([ + 'id' => $id, 'backup_key' => $key, + 'source_instance_id' => 100 + $id, 'source_host_id' => 3, + 'user_id' => 9, + 'source_uuid' => sprintf('00000000-0000-4000-8000-%012d', $id), + 'name' => 'portable-' . $id, 'state' => 'creating', + 'consistency' => 'crash', + 'object_key' => 'vm-backups/' . $key . '/system.qcow2', + 'spec_json' => '{}', 'sealed_storage_runtime' => 'sealed', + 'active_job_id' => $id, 'last_operation_id' => $operation, + 'created_at' => $now, 'updated_at' => $now, + ]); + $capsule->table('cloud_jobs')->insert([ + 'id' => $id, 'kind' => 'backup_create', 'host_id' => 3, + 'instance_id' => 100 + $id, 'backup_id' => $id, + 'operation_id' => $operation, + ]); + return CloudJob::findOrFail($id); +}; +$result = static function (string $key) use ($payload): array { + return [ + 'backup_key' => $key, 'size_bytes' => 1024, + 'virtual_size_bytes' => 20 * 1073741824, + 'sha256' => str_repeat('a', 64), 'object_etag' => 'etag', + 'object_version_id' => '', 'consistency' => 'crash', + 'cleanup_pending' => false, 'source_contract' => $payload, + ]; +}; +$finalizerPayload = static function (string $key) use ($contract): array { + return [ + 'owner_id' => 9, 'backup_key' => $key, + 'maximum_size_bytes' => 21 * 1073741824, + 'source_portable_restore_contract_sha256' => $contract->sha256(), + ]; +}; + +$key = str_repeat('1', 32); +CloudBackupService::finishJobLocked( + $create(1, $key, str_repeat('2', 32)), + 'succeeded', $result($key), $finalizerPayload($key) +); +$ready = CloudInstanceBackup::findOrFail(1); +$assert((string) $ready->state === 'ready' + && (string) $ready->source_portable_restore_contract_json + === $contract->json() + && (string) $ready->source_portable_restore_contract_sha256 + === $contract->sha256() + && $ready->sourcePortableRestoreCompatibility() !== null, + 'Valid Agent source contract was not frozen with the ready backup.'); + +$missingKey = str_repeat('3', 32); +$missing = $result($missingKey); +unset($missing['source_contract']); +try { + CloudBackupService::finishJobLocked( + $create(2, $missingKey, str_repeat('4', 32)), + 'succeeded', $missing, $finalizerPayload($missingKey) + ); + throw new RuntimeException('Missing source contract was accepted.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 502, + 'Missing source contract returned the wrong status.'); +} +$assert((string) CloudInstanceBackup::findOrFail(2)->state === 'creating', + 'Missing source contract promoted a backup to ready.'); + +echo "Portable backup source contract finalizer passed.\n"; diff --git a/web/tests/CloudPortableRestoreCompatibilityTest.php b/web/tests/CloudPortableRestoreCompatibilityTest.php new file mode 100644 index 00000000..547af628 --- /dev/null +++ b/web/tests/CloudPortableRestoreCompatibilityTest.php @@ -0,0 +1,85 @@ + 1, + 'architecture' => 'x86_64', + 'machine' => 'q35', + 'firmware' => 'uefi', + 'secure_boot' => false, + 'disk_format' => 'qcow2', + 'system_disk_only' => true, + 'public_network_contract' => 1, + 'vpc_inherited' => false, +]; +$contract = CloudPortableRestoreCompatibility::fromPayload($canonical); +$assert($contract->toArray() === $canonical, + 'Portable restore contract did not canonicalize exactly.'); +$assert(strlen($contract->sha256()) === 64, + 'Portable restore contract digest is invalid.'); +$assert(CloudPortableRestoreCompatibility::fromStored( + $contract->json(), $contract->sha256() +)->matches($contract), 'Stored portable restore evidence did not round trip.'); + +foreach (array_keys($canonical) as $field) { + $broken = $canonical; + unset($broken[$field]); + try { + CloudPortableRestoreCompatibility::fromPayload($broken); + throw new RuntimeException("Missing {$field} was accepted."); + } catch (InvalidArgumentException) { + } +} +foreach ([ + 'contract' => 2, + 'architecture' => 'aarch64', + 'machine' => 'pc-i440fx', + 'firmware' => 'bios', + 'secure_boot' => true, + 'disk_format' => 'raw', + 'system_disk_only' => false, + 'public_network_contract' => 2, + 'vpc_inherited' => true, +] as $field => $wrong) { + $broken = $canonical; + $broken[$field] = $wrong; + try { + CloudPortableRestoreCompatibility::fromPayload($broken); + throw new RuntimeException("Wrong {$field} was accepted."); + } catch (InvalidArgumentException) { + } +} +$extra = $canonical + ['path' => '/private/root.qcow2']; +try { + CloudPortableRestoreCompatibility::fromPayload($extra); + throw new RuntimeException('An unbounded contract field was accepted.'); +} catch (InvalidArgumentException) { +} + +$reordered = array_reverse($canonical, true); +try { + CloudPortableRestoreCompatibility::fromStored( + json_encode($reordered, JSON_THROW_ON_ERROR), + $contract->sha256() + ); + throw new RuntimeException('Non-canonical stored JSON was accepted.'); +} catch (InvalidArgumentException) { +} +try { + CloudPortableRestoreCompatibility::fromStored( + $contract->json(), str_repeat('f', 64) + ); + throw new RuntimeException('A tampered contract digest was accepted.'); +} catch (InvalidArgumentException) { +} + +echo "Portable restore compatibility contract passed.\n"; diff --git a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php index 49ccd36b..dd50f446 100644 --- a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php +++ b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php @@ -65,7 +65,7 @@ $assert(is_string($schema) 'Public-pool replacement lacks durable batch, child, or active-claim schema.'); $assert(is_string($setup) && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'") + "SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'") && str_contains($setup, "'cloud_public_ip_pool_replacement_batches'") && str_contains($setup, diff --git a/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php b/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php index f54f5674..9a50a876 100644 --- a/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php +++ b/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php @@ -170,7 +170,7 @@ $assert(str_contains($setup, 'CloudSetup does not verify index uniqueness and ordered columns.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'") + "SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'") && str_contains($setup, "'cloud_public_network_transitions'") && str_contains($setup, "'cloud_public_network_transition_ips'") && str_contains($setup, "'reservation_ip_claim_id'") diff --git a/web/tests/CloudRescueCatalogSchemaContractTest.php b/web/tests/CloudRescueCatalogSchemaContractTest.php index 799732c3..a04aa38b 100644 --- a/web/tests/CloudRescueCatalogSchemaContractTest.php +++ b/web/tests/CloudRescueCatalogSchemaContractTest.php @@ -56,7 +56,7 @@ $assert($replica !== '' && str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'), 'Rescue replica cannot prove exact identity or retain cleanup debt.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'") + "SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'") && str_contains($setup, "'cloud_rescue_artifact_delete_due'") && str_contains($setup, "'cloud_rescue_replica_cleanup'"), 'CloudSetup version or rescue catalog indexes are incomplete.'); diff --git a/web/tests/CloudRestoreMigrationLedgerContractTest.php b/web/tests/CloudRestoreMigrationLedgerContractTest.php index 3c98ee52..ae9cf404 100644 --- a/web/tests/CloudRestoreMigrationLedgerContractTest.php +++ b/web/tests/CloudRestoreMigrationLedgerContractTest.php @@ -182,7 +182,7 @@ foreach ([ 'CloudSetup omits restore/migration ledger contract: ' . $required); } $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'") + "SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'") && str_contains($attemptModel, "protected \$table = 'cloud_backup_restore_attempts';") && str_contains($attemptModel, "'active_attempt' => 'int'") diff --git a/web/tests/CloudTemplateImportIntentContractTest.php b/web/tests/CloudTemplateImportIntentContractTest.php index a76a6d06..620bda31 100644 --- a/web/tests/CloudTemplateImportIntentContractTest.php +++ b/web/tests/CloudTemplateImportIntentContractTest.php @@ -63,7 +63,7 @@ $assert(str_contains($schema, && str_contains($schema, 'CONSTRAINT chk_cloud_template_import_completion CHECK (') && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'"), + "SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'"), 'Template imports are missing durable identity or terminal-state constraints.'); $assert(str_contains($routes, "'/admin/cloud-template-imports'") && str_contains($routes, "'/admin/cloud-template-imports/{id}'") diff --git a/web/tests/CloudTrafficPoolSchemaContractTest.php b/web/tests/CloudTrafficPoolSchemaContractTest.php index 56c45743..498d93d6 100644 --- a/web/tests/CloudTrafficPoolSchemaContractTest.php +++ b/web/tests/CloudTrafficPoolSchemaContractTest.php @@ -71,7 +71,7 @@ $assert(str_contains($schema, 'Service-period traffic-pool identity is not frozen or indexed.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'") + "SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'") && str_contains($setup, "'chk_cloud_traffic_entitlement_balance'") && str_contains($setup, "'cloud_traffic_ledger_sequence'"), 'CloudSetup schema version or named-object validation is incomplete.'); diff --git a/web/tests/CloudVpcSchemaContractTest.php b/web/tests/CloudVpcSchemaContractTest.php index bc2a632b..ae0713ed 100644 --- a/web/tests/CloudVpcSchemaContractTest.php +++ b/web/tests/CloudVpcSchemaContractTest.php @@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL') 'Cloud jobs cannot be correlated to VPC or VPC-port work.'); $assert(str_contains($setup, - "private const SCHEMA_VERSION = 'go-agent-wss-v31-restore-migration-ledgers'") + "private const SCHEMA_VERSION = 'go-agent-wss-v32-portable-restore-contract'") && str_contains($setup, "'name' => 'cloud_vpc_enabled'") && str_contains($setup, "'value' => 'false'") && str_contains($setup,