refactor(cloud): unify recovery commits and operation contracts
Share applied/not_applied preparation and atomic publication while preserving direction-specific evidence checks. Define recovery capabilities once, embed them in the Agent, and generate the PHP inventory with drift and full-kind behavior contracts. Permit only bounded public template generation IDs in inspection projections.go
parent
813f9f58a6
commit
371110d9fc
@ -0,0 +1,288 @@
|
||||
package operation
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const recoveryContractSchemaVersion = 1
|
||||
|
||||
var recoveryKindPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
|
||||
|
||||
//go:embed recovery_contract.json
|
||||
var embeddedRecoveryContractJSON []byte
|
||||
|
||||
var embeddedRecoveryContract = mustParseRecoveryContract(embeddedRecoveryContractJSON)
|
||||
|
||||
type recoveryContractDocument struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Operations []recoveryContractOperation `json:"operations"`
|
||||
}
|
||||
|
||||
type recoveryContractOperation struct {
|
||||
Kind string `json:"kind"`
|
||||
RecoveryMode string `json:"recovery_mode"`
|
||||
IdentityScope string `json:"identity_scope"`
|
||||
Actions []string `json:"actions"`
|
||||
ActionPatterns []string `json:"action_patterns"`
|
||||
SystemResolutions []string `json:"system_resolutions"`
|
||||
}
|
||||
|
||||
type recoveryResolutionSet map[string]struct{}
|
||||
|
||||
type recoveryActionPattern struct {
|
||||
source string
|
||||
pattern *regexp.Regexp
|
||||
resolutions recoveryResolutionSet
|
||||
}
|
||||
|
||||
type recoveryContract struct {
|
||||
actions map[string]recoveryResolutionSet
|
||||
patterns []recoveryActionPattern
|
||||
}
|
||||
|
||||
// SystemRecoveryActionAllowed is the deny-by-default capability boundary for
|
||||
// the panel's read-only inspector. A manifest entry without a permitted system
|
||||
// resolution (for example host storage coordination) does not grant access.
|
||||
func SystemRecoveryActionAllowed(action string) bool {
|
||||
return embeddedRecoveryContract.actionAllowed(action)
|
||||
}
|
||||
|
||||
// SystemRecoveryResolutionAllowed binds an automatic fence decision to the
|
||||
// exact immutable Agent action. This prevents a manifest entry that only
|
||||
// permits not_applied from inheriting the generic applied capability.
|
||||
func SystemRecoveryResolutionAllowed(action, resolution string) bool {
|
||||
return embeddedRecoveryContract.resolutionAllowed(action, resolution)
|
||||
}
|
||||
|
||||
func (contract recoveryContract) actionAllowed(action string) bool {
|
||||
if len(action) > 128 || !operationActionPattern.MatchString(action) {
|
||||
return false
|
||||
}
|
||||
if resolutions, ok := contract.actions[action]; ok && len(resolutions) > 0 {
|
||||
return true
|
||||
}
|
||||
for _, candidate := range contract.patterns {
|
||||
if len(candidate.resolutions) > 0 && candidate.pattern.MatchString(action) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (contract recoveryContract) resolutionAllowed(action, resolution string) bool {
|
||||
if len(action) > 128 || !operationActionPattern.MatchString(action) {
|
||||
return false
|
||||
}
|
||||
if resolutions, ok := contract.actions[action]; ok {
|
||||
_, allowed := resolutions[resolution]
|
||||
return allowed
|
||||
}
|
||||
for _, candidate := range contract.patterns {
|
||||
if candidate.pattern.MatchString(action) {
|
||||
_, allowed := candidate.resolutions[resolution]
|
||||
return allowed
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func mustParseRecoveryContract(document []byte) recoveryContract {
|
||||
contract, err := parseRecoveryContract(document)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("invalid embedded recovery contract: %v", err))
|
||||
}
|
||||
return contract
|
||||
}
|
||||
|
||||
func parseRecoveryContract(document []byte) (recoveryContract, error) {
|
||||
decoder := json.NewDecoder(bytes.NewReader(document))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
var decoded recoveryContractDocument
|
||||
if err := decoder.Decode(&decoded); err != nil {
|
||||
return recoveryContract{}, fmt.Errorf("decode recovery contract: %w", err)
|
||||
}
|
||||
var trailing json.RawMessage
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
if err == nil {
|
||||
return recoveryContract{}, errors.New("recovery contract contains a trailing JSON value")
|
||||
}
|
||||
return recoveryContract{}, fmt.Errorf("decode recovery contract trailer: %w", err)
|
||||
}
|
||||
if decoded.SchemaVersion != recoveryContractSchemaVersion {
|
||||
return recoveryContract{}, fmt.Errorf("unsupported recovery contract schema version %d", decoded.SchemaVersion)
|
||||
}
|
||||
if len(decoded.Operations) == 0 {
|
||||
return recoveryContract{}, errors.New("recovery contract operations must not be empty")
|
||||
}
|
||||
|
||||
contract := recoveryContract{actions: make(map[string]recoveryResolutionSet)}
|
||||
seenKinds := make(map[string]struct{}, len(decoded.Operations))
|
||||
seenPatterns := make(map[string]recoveryResolutionSet)
|
||||
var patternedResolutions recoveryResolutionSet
|
||||
for index, operation := range decoded.Operations {
|
||||
if err := validateRecoveryContractOperation(operation); err != nil {
|
||||
return recoveryContract{}, fmt.Errorf("recovery contract operation %d: %w", index, err)
|
||||
}
|
||||
if _, exists := seenKinds[operation.Kind]; exists {
|
||||
return recoveryContract{}, fmt.Errorf("recovery contract kind %q is duplicated", operation.Kind)
|
||||
}
|
||||
seenKinds[operation.Kind] = struct{}{}
|
||||
|
||||
resolutions := recoveryResolutionSetFrom(operation.SystemResolutions)
|
||||
for _, action := range operation.Actions {
|
||||
if existing, exists := contract.actions[action]; exists {
|
||||
if !sameRecoveryResolutionSet(existing, resolutions) {
|
||||
return recoveryContract{}, fmt.Errorf("action %q has conflicting system resolutions", action)
|
||||
}
|
||||
continue
|
||||
}
|
||||
contract.actions[action] = resolutions
|
||||
}
|
||||
for _, source := range operation.ActionPatterns {
|
||||
if existing, exists := seenPatterns[source]; exists {
|
||||
if !sameRecoveryResolutionSet(existing, resolutions) {
|
||||
return recoveryContract{}, fmt.Errorf("action pattern %q has conflicting system resolutions", source)
|
||||
}
|
||||
continue
|
||||
}
|
||||
// This loader intentionally does not analyze regex intersections.
|
||||
// Requiring every pattern to carry one identical grant prevents
|
||||
// overlaps from unioning different system-recovery capabilities.
|
||||
if patternedResolutions != nil && !sameRecoveryResolutionSet(patternedResolutions, resolutions) {
|
||||
return recoveryContract{}, errors.New("action patterns have conflicting system resolutions")
|
||||
}
|
||||
compiled, err := regexp.Compile(source)
|
||||
if err != nil {
|
||||
return recoveryContract{}, fmt.Errorf("compile action pattern %q: %w", source, err)
|
||||
}
|
||||
patternedResolutions = resolutions
|
||||
seenPatterns[source] = resolutions
|
||||
contract.patterns = append(contract.patterns, recoveryActionPattern{
|
||||
source: source, pattern: compiled, resolutions: resolutions,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// No exact action may silently acquire a second, different capability from
|
||||
// a pattern. The reviewed patterns are currently disjoint, but this check
|
||||
// keeps the invariant explicit if the manifest grammar is extended later.
|
||||
for action, exactResolutions := range contract.actions {
|
||||
for _, candidate := range contract.patterns {
|
||||
if candidate.pattern.MatchString(action) &&
|
||||
!sameRecoveryResolutionSet(exactResolutions, candidate.resolutions) {
|
||||
return recoveryContract{}, fmt.Errorf("action %q matches pattern %q with conflicting system resolutions", action, candidate.source)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return contract, nil
|
||||
}
|
||||
|
||||
func validateRecoveryContractOperation(operation recoveryContractOperation) error {
|
||||
if !recoveryKindPattern.MatchString(operation.Kind) {
|
||||
return fmt.Errorf("invalid kind %q", operation.Kind)
|
||||
}
|
||||
if operation.Actions == nil || operation.ActionPatterns == nil || operation.SystemResolutions == nil {
|
||||
return errors.New("actions, action_patterns, and system_resolutions must all be present")
|
||||
}
|
||||
|
||||
allowedScopes := map[string]bool{}
|
||||
expectedResolutions := []string(nil)
|
||||
requiresActions := false
|
||||
switch operation.RecoveryMode {
|
||||
case "generic":
|
||||
allowedScopes["instance"] = true
|
||||
allowedScopes["catalog"] = true
|
||||
expectedResolutions = []string{FenceResolutionApplied, FenceResolutionNotApplied}
|
||||
requiresActions = true
|
||||
case "create":
|
||||
allowedScopes["create"] = true
|
||||
expectedResolutions = []string{FenceResolutionNotApplied}
|
||||
requiresActions = true
|
||||
case "storage":
|
||||
allowedScopes["storage"] = true
|
||||
expectedResolutions = []string{}
|
||||
requiresActions = true
|
||||
case "aggregate", "payment":
|
||||
allowedScopes["none"] = true
|
||||
expectedResolutions = []string{}
|
||||
default:
|
||||
return fmt.Errorf("unsupported recovery_mode %q", operation.RecoveryMode)
|
||||
}
|
||||
if !allowedScopes[operation.IdentityScope] {
|
||||
return fmt.Errorf("identity_scope %q is invalid for recovery_mode %q", operation.IdentityScope, operation.RecoveryMode)
|
||||
}
|
||||
if requiresActions == (len(operation.Actions)+len(operation.ActionPatterns) == 0) {
|
||||
if requiresActions {
|
||||
return fmt.Errorf("recovery_mode %q requires an action or action pattern", operation.RecoveryMode)
|
||||
}
|
||||
return fmt.Errorf("recovery_mode %q must not define actions or action patterns", operation.RecoveryMode)
|
||||
}
|
||||
if !sameStringSlice(operation.SystemResolutions, expectedResolutions) {
|
||||
return fmt.Errorf("system_resolutions do not match recovery_mode %q", operation.RecoveryMode)
|
||||
}
|
||||
|
||||
seenActions := make(map[string]struct{}, len(operation.Actions))
|
||||
for _, action := range operation.Actions {
|
||||
if len(action) > 128 || !operationActionPattern.MatchString(action) {
|
||||
return fmt.Errorf("invalid action %q", action)
|
||||
}
|
||||
if _, exists := seenActions[action]; exists {
|
||||
return fmt.Errorf("action %q is duplicated", action)
|
||||
}
|
||||
seenActions[action] = struct{}{}
|
||||
}
|
||||
seenPatterns := make(map[string]struct{}, len(operation.ActionPatterns))
|
||||
for _, source := range operation.ActionPatterns {
|
||||
if len(source) < 2 || source[0] != '^' || source[len(source)-1] != '$' {
|
||||
return fmt.Errorf("action pattern %q must be anchored", source)
|
||||
}
|
||||
if _, err := regexp.Compile(source); err != nil {
|
||||
return fmt.Errorf("invalid action pattern %q: %w", source, err)
|
||||
}
|
||||
if _, exists := seenPatterns[source]; exists {
|
||||
return fmt.Errorf("action pattern %q is duplicated", source)
|
||||
}
|
||||
seenPatterns[source] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func recoveryResolutionSetFrom(resolutions []string) recoveryResolutionSet {
|
||||
result := make(recoveryResolutionSet, len(resolutions))
|
||||
for _, resolution := range resolutions {
|
||||
result[resolution] = struct{}{}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func sameRecoveryResolutionSet(left, right recoveryResolutionSet) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
for resolution := range left {
|
||||
if _, exists := right[resolution]; !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sameStringSlice(left, right []string) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
for index := range left {
|
||||
if left[index] != right[index] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -0,0 +1,368 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"operations": [
|
||||
{
|
||||
"kind": "action",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"power-start",
|
||||
"power-shutdown",
|
||||
"power-reboot",
|
||||
"power-reset",
|
||||
"power-destroy"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "reinstall",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"reinstall-vm"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "rescue",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"enter-rescue",
|
||||
"force-start-rescue",
|
||||
"exit-rescue:connected",
|
||||
"exit-rescue:suspended"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "delete",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"delete-vm"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "delete_force",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"force-delete-vm"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "expiry_delete",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"delete-vm"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "network_change",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"change-network"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "instance_settings",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"update-settings"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "snapshot_create",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [],
|
||||
"action_patterns": [
|
||||
"^create-snapshot:[a-f0-9]{32}:(?:filesystem|crash)$"
|
||||
],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "snapshot_restore",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [],
|
||||
"action_patterns": [
|
||||
"^restore-snapshot:[a-f0-9]{32}$"
|
||||
],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "snapshot_delete",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [],
|
||||
"action_patterns": [
|
||||
"^delete-snapshot:[a-f0-9]{32}$"
|
||||
],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "firewall_apply",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"apply-firewall"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "service_suspend",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"service-suspend"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "network_suspend",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"network-suspend"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "network_resume",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "instance",
|
||||
"actions": [
|
||||
"network-resume"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "template_import_replica",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "catalog",
|
||||
"actions": [
|
||||
"import-template"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "template_metadata_replica",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "catalog",
|
||||
"actions": [
|
||||
"update-template"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "template_delete_replica",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "catalog",
|
||||
"actions": [
|
||||
"delete-template"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "rescue_template_import",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "catalog",
|
||||
"actions": [
|
||||
"import-rescue-template"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "rescue_template_delete",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "catalog",
|
||||
"actions": [
|
||||
"delete-rescue-template"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "user_iso_import_replica",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "catalog",
|
||||
"actions": [
|
||||
"import-user-iso"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "user_iso_delete_replica",
|
||||
"recovery_mode": "generic",
|
||||
"identity_scope": "catalog",
|
||||
"actions": [
|
||||
"delete-user-iso"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"applied",
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "create",
|
||||
"recovery_mode": "create",
|
||||
"identity_scope": "create",
|
||||
"actions": [
|
||||
"create-vm"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": [
|
||||
"not_applied"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "host_storage_configure",
|
||||
"recovery_mode": "storage",
|
||||
"identity_scope": "storage",
|
||||
"actions": [
|
||||
"configure-storage"
|
||||
],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": []
|
||||
},
|
||||
{
|
||||
"kind": "payment_create",
|
||||
"recovery_mode": "payment",
|
||||
"identity_scope": "none",
|
||||
"actions": [],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": []
|
||||
},
|
||||
{
|
||||
"kind": "template_import",
|
||||
"recovery_mode": "aggregate",
|
||||
"identity_scope": "none",
|
||||
"actions": [],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": []
|
||||
},
|
||||
{
|
||||
"kind": "template_metadata_sync",
|
||||
"recovery_mode": "aggregate",
|
||||
"identity_scope": "none",
|
||||
"actions": [],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": []
|
||||
},
|
||||
{
|
||||
"kind": "template_delete",
|
||||
"recovery_mode": "aggregate",
|
||||
"identity_scope": "none",
|
||||
"actions": [],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": []
|
||||
},
|
||||
{
|
||||
"kind": "user_iso_import",
|
||||
"recovery_mode": "aggregate",
|
||||
"identity_scope": "none",
|
||||
"actions": [],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": []
|
||||
},
|
||||
{
|
||||
"kind": "user_iso_delete",
|
||||
"recovery_mode": "aggregate",
|
||||
"identity_scope": "none",
|
||||
"actions": [],
|
||||
"action_patterns": [],
|
||||
"system_resolutions": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,179 @@
|
||||
package operation
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEmbeddedRecoveryContractControlsSystemResolutions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
action string
|
||||
resolution string
|
||||
want bool
|
||||
}{
|
||||
{name: "generic applied", action: "power-start", resolution: FenceResolutionApplied, want: true},
|
||||
{name: "generic not applied", action: "power-start", resolution: FenceResolutionNotApplied, want: true},
|
||||
{name: "parameterized snapshot", action: "create-snapshot:0123456789abcdef0123456789abcdef:filesystem", resolution: FenceResolutionApplied, want: true},
|
||||
{name: "create not applied", action: "create-vm", resolution: FenceResolutionNotApplied, want: true},
|
||||
{name: "create applied", action: "create-vm", resolution: FenceResolutionApplied, want: false},
|
||||
{name: "storage excluded", action: "configure-storage", resolution: FenceResolutionNotApplied, want: false},
|
||||
{name: "unknown action", action: "future-operation", resolution: FenceResolutionApplied, want: false},
|
||||
{name: "unknown resolution", action: "power-start", resolution: "partial", want: false},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := SystemRecoveryResolutionAllowed(test.action, test.resolution); got != test.want {
|
||||
t.Fatalf("SystemRecoveryResolutionAllowed(%q, %q) = %v, want %v", test.action, test.resolution, got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRecoveryContractRejectsMalformedSchemas(t *testing.T) {
|
||||
validOperation := `{
|
||||
"kind":"action",
|
||||
"recovery_mode":"generic",
|
||||
"identity_scope":"instance",
|
||||
"actions":["power-start"],
|
||||
"action_patterns":[],
|
||||
"system_resolutions":["applied","not_applied"]
|
||||
}`
|
||||
valid := `{"schema_version":1,"operations":[` + validOperation + `]}`
|
||||
if _, err := parseRecoveryContract([]byte(valid)); err != nil {
|
||||
t.Fatalf("valid recovery contract rejected: %v", err)
|
||||
}
|
||||
|
||||
tests := map[string]string{
|
||||
"unknown envelope field": `{"schema_version":1,"operations":[` + validOperation + `],"future":true}`,
|
||||
"unknown operation field": strings.Replace(valid, `"system_resolutions":["applied","not_applied"]`, `"system_resolutions":["applied","not_applied"],"future":true`, 1),
|
||||
"unsupported schema": strings.Replace(valid, `"schema_version":1`, `"schema_version":2`, 1),
|
||||
"duplicate kind": `{"schema_version":1,"operations":[` + validOperation + `,` + validOperation + `]}`,
|
||||
"missing actions": strings.Replace(valid, `"actions":["power-start"],`, ``, 1),
|
||||
"mode resolution mismatch": strings.Replace(valid, `"system_resolutions":["applied","not_applied"]`, `"system_resolutions":["not_applied"]`, 1),
|
||||
"scope mode mismatch": strings.Replace(valid, `"identity_scope":"instance"`, `"identity_scope":"none"`, 1),
|
||||
"unanchored pattern": strings.Replace(valid,
|
||||
`"actions":["power-start"],
|
||||
"action_patterns":[]`,
|
||||
`"actions":[],
|
||||
"action_patterns":["power-.*"]`, 1),
|
||||
"invalid pattern": strings.Replace(valid,
|
||||
`"actions":["power-start"],
|
||||
"action_patterns":[]`,
|
||||
`"actions":[],
|
||||
"action_patterns":["^power-($"]`, 1),
|
||||
"trailing document": valid + `{}`,
|
||||
}
|
||||
for name, document := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := parseRecoveryContract([]byte(document)); err == nil {
|
||||
t.Fatal("malformed recovery contract was accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRecoveryContractAcceptsAnchoredManifestPattern(t *testing.T) {
|
||||
document := `{
|
||||
"schema_version":1,
|
||||
"operations":[{
|
||||
"kind":"custom_action",
|
||||
"recovery_mode":"generic",
|
||||
"identity_scope":"instance",
|
||||
"actions":[],
|
||||
"action_patterns":["^custom-action:[a-f0-9]{8}$"],
|
||||
"system_resolutions":["applied","not_applied"]
|
||||
}]
|
||||
}`
|
||||
contract, err := parseRecoveryContract([]byte(document))
|
||||
if err != nil {
|
||||
t.Fatalf("valid manifest pattern rejected: %v", err)
|
||||
}
|
||||
if !contract.resolutionAllowed("custom-action:0123abcd", FenceResolutionApplied) {
|
||||
t.Fatal("manifest pattern did not grant its declared resolution")
|
||||
}
|
||||
if contract.resolutionAllowed("custom-action:0123abcg", FenceResolutionApplied) {
|
||||
t.Fatal("manifest pattern matched an invalid action")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRecoveryContractRejectsCrossModeActionGrant(t *testing.T) {
|
||||
document := `{
|
||||
"schema_version":1,
|
||||
"operations":[
|
||||
{
|
||||
"kind":"action",
|
||||
"recovery_mode":"generic",
|
||||
"identity_scope":"instance",
|
||||
"actions":["power-start"],
|
||||
"action_patterns":[],
|
||||
"system_resolutions":["applied","not_applied"]
|
||||
},
|
||||
{
|
||||
"kind":"host_storage_configure",
|
||||
"recovery_mode":"storage",
|
||||
"identity_scope":"storage",
|
||||
"actions":["power-start"],
|
||||
"action_patterns":[],
|
||||
"system_resolutions":[]
|
||||
}
|
||||
]
|
||||
}`
|
||||
if _, err := parseRecoveryContract([]byte(document)); err == nil {
|
||||
t.Fatal("one Agent action acquired conflicting system-recovery grants")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRecoveryContractRejectsConflictingPatternGrants(t *testing.T) {
|
||||
document := `{
|
||||
"schema_version":1,
|
||||
"operations":[
|
||||
{
|
||||
"kind":"generic_pattern",
|
||||
"recovery_mode":"generic",
|
||||
"identity_scope":"instance",
|
||||
"actions":[],
|
||||
"action_patterns":["^generic-[a-z]+$"],
|
||||
"system_resolutions":["applied","not_applied"]
|
||||
},
|
||||
{
|
||||
"kind":"storage_pattern",
|
||||
"recovery_mode":"storage",
|
||||
"identity_scope":"storage",
|
||||
"actions":[],
|
||||
"action_patterns":["^storage-[a-z]+$"],
|
||||
"system_resolutions":[]
|
||||
}
|
||||
]
|
||||
}`
|
||||
if _, err := parseRecoveryContract([]byte(document)); err == nil {
|
||||
t.Fatal("patterns with conflicting system-recovery grants were accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRecoveryContractRejectsPatternOverrideOfExactAction(t *testing.T) {
|
||||
document := `{
|
||||
"schema_version":1,
|
||||
"operations":[
|
||||
{
|
||||
"kind":"generic_pattern",
|
||||
"recovery_mode":"generic",
|
||||
"identity_scope":"instance",
|
||||
"actions":[],
|
||||
"action_patterns":["^create-vm$"],
|
||||
"system_resolutions":["applied","not_applied"]
|
||||
},
|
||||
{
|
||||
"kind":"create",
|
||||
"recovery_mode":"create",
|
||||
"identity_scope":"create",
|
||||
"actions":["create-vm"],
|
||||
"action_patterns":[],
|
||||
"system_resolutions":["not_applied"]
|
||||
}
|
||||
]
|
||||
}`
|
||||
if _, err := parseRecoveryContract([]byte(document)); err == nil {
|
||||
t.Fatal("pattern overrode an exact action's narrower system-recovery grant")
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Development-only generator. Production PHP uses the generated constant and
|
||||
// never needs the Agent source tree, JSON parsing, or a writable deployment.
|
||||
$root = dirname(__DIR__);
|
||||
$source = $root . '/agent/operation/recovery_contract.json';
|
||||
$target = $root . '/web/app/Services/Cloud/CloudOperationRecoveryContract.php';
|
||||
$check = ($argv[1] ?? '') === '--check';
|
||||
if (count($argv) > 2 || (isset($argv[1]) && !$check)) {
|
||||
fwrite(STDERR, "Usage: php tools/generate-recovery-contract.php [--check]\n");
|
||||
exit(2);
|
||||
}
|
||||
$contract = json_decode(file_get_contents($source), true, 512,
|
||||
JSON_THROW_ON_ERROR);
|
||||
$hasKeys = static function (array $value, array $keys): bool {
|
||||
$actual = array_keys($value);
|
||||
sort($actual);
|
||||
sort($keys);
|
||||
return $actual === $keys;
|
||||
};
|
||||
if (!$hasKeys($contract, ['schema_version', 'operations'])
|
||||
|| ($contract['schema_version'] ?? null) !== 1
|
||||
|| !is_array($contract['operations'] ?? null)
|
||||
|| !array_is_list($contract['operations'])
|
||||
|| $contract['operations'] === []) {
|
||||
throw new RuntimeException('Invalid recovery contract envelope.');
|
||||
}
|
||||
$operations = [];
|
||||
foreach ($contract['operations'] as $entry) {
|
||||
if (!is_array($entry) || !$hasKeys($entry, [
|
||||
'kind', 'recovery_mode', 'identity_scope', 'actions',
|
||||
'action_patterns', 'system_resolutions',
|
||||
])) {
|
||||
throw new RuntimeException('Invalid recovery operation fields.');
|
||||
}
|
||||
$kind = $entry['kind'] ?? null;
|
||||
$mode = $entry['recovery_mode'] ?? null;
|
||||
$scope = $entry['identity_scope'] ?? null;
|
||||
if (!is_string($kind) || preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $kind) !== 1
|
||||
|| isset($operations[$kind])
|
||||
|| !in_array($mode, ['generic', 'create', 'storage', 'aggregate', 'payment'], true)
|
||||
|| !in_array($scope, ['instance', 'catalog', 'create', 'storage', 'none'], true)) {
|
||||
throw new RuntimeException('Invalid or duplicate recovery operation.');
|
||||
}
|
||||
foreach (['actions', 'action_patterns', 'system_resolutions'] as $field) {
|
||||
if (!is_array($entry[$field] ?? null) || !array_is_list($entry[$field])
|
||||
|| count(array_unique($entry[$field])) !== count($entry[$field])) {
|
||||
throw new RuntimeException('Invalid recovery list: ' . $kind . '.' . $field);
|
||||
}
|
||||
foreach ($entry[$field] as $value) {
|
||||
if (!is_string($value) || $value === '') {
|
||||
throw new RuntimeException('Invalid recovery entry: ' . $kind . '.' . $field);
|
||||
}
|
||||
}
|
||||
}
|
||||
$resolutions = match ($mode) {
|
||||
'generic' => ['applied', 'not_applied'],
|
||||
'create' => ['not_applied'],
|
||||
default => [],
|
||||
};
|
||||
$validScope = match ($mode) {
|
||||
'generic' => in_array($scope, ['instance', 'catalog'], true),
|
||||
'create', 'storage' => $scope === $mode,
|
||||
default => $scope === 'none',
|
||||
};
|
||||
if (!$validScope || $entry['system_resolutions'] !== $resolutions
|
||||
|| (($scope === 'none') !== ($entry['actions'] === [] && $entry['action_patterns'] === []))) {
|
||||
throw new RuntimeException('Unsafe recovery mode boundary: ' . $kind);
|
||||
}
|
||||
foreach ($entry['actions'] as $action) {
|
||||
if (strlen($action) > 128
|
||||
|| preg_match('/^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$/D', $action) !== 1) {
|
||||
throw new RuntimeException('Invalid recovery action: ' . $kind);
|
||||
}
|
||||
}
|
||||
foreach ($entry['action_patterns'] as $pattern) {
|
||||
if (!str_starts_with($pattern, '^') || !str_ends_with($pattern, '$')
|
||||
|| str_contains($pattern, '~') || @preg_match('~' . $pattern . '~D', '') === false) {
|
||||
throw new RuntimeException('Invalid anchored recovery pattern: ' . $kind);
|
||||
}
|
||||
}
|
||||
unset($entry['kind']);
|
||||
$operations[$kind] = $entry;
|
||||
}
|
||||
// The Agent authorizes by action, not PHP kind. Aliases such as delete and
|
||||
// expiry_delete are legal only when they grant the same resolution capability.
|
||||
$actionPermissions = [];
|
||||
$patterns = [];
|
||||
foreach ($operations as $entry) {
|
||||
foreach ($entry['actions'] as $action) {
|
||||
if (isset($actionPermissions[$action])
|
||||
&& $actionPermissions[$action] !== $entry['system_resolutions']) {
|
||||
throw new RuntimeException('Conflicting recovery permissions: ' . $action);
|
||||
}
|
||||
$actionPermissions[$action] = $entry['system_resolutions'];
|
||||
}
|
||||
foreach ($entry['action_patterns'] as $pattern) {
|
||||
// This generator deliberately does not analyze regex intersections.
|
||||
// Keep patterned capabilities uniform instead of unioning permissions.
|
||||
foreach ($patterns as $permissions) {
|
||||
if ($permissions !== $entry['system_resolutions']) {
|
||||
throw new RuntimeException('Conflicting patterned recovery permissions.');
|
||||
}
|
||||
}
|
||||
$patterns[$pattern] = $entry['system_resolutions'];
|
||||
}
|
||||
}
|
||||
foreach ($actionPermissions as $action => $permissions) {
|
||||
foreach ($patterns as $pattern => $patternPermissions) {
|
||||
if (preg_match('~' . $pattern . '~D', $action) === 1
|
||||
&& $permissions !== $patternPermissions) {
|
||||
throw new RuntimeException('Recovery pattern overrides permissions: ' . $action);
|
||||
}
|
||||
}
|
||||
}
|
||||
$lines = [];
|
||||
foreach ($operations as $kind => $entry) {
|
||||
$lines[] = " '$kind' => [";
|
||||
foreach ($entry as $key => $value) {
|
||||
$encoded = is_array($value)
|
||||
? '[' . implode(', ', array_map(static fn (string $item): string => var_export($item, true), $value)) . ']'
|
||||
: var_export($value, true);
|
||||
$lines[] = " '$key' => $encoded,";
|
||||
}
|
||||
$lines[] = ' ],';
|
||||
}
|
||||
$output = "<?php\n\nnamespace App\\Services\\Cloud;\n\n"
|
||||
. "// Generated from agent/operation/recovery_contract.json. Do not edit.\n"
|
||||
. "// Regenerate: php tools/generate-recovery-contract.php\n"
|
||||
. "final class CloudOperationRecoveryContract\n{\n"
|
||||
. " public const OPERATIONS = [\n" . implode("\n", $lines)
|
||||
. "\n ];\n}\n";
|
||||
if ($check) {
|
||||
if (!is_file($target) || file_get_contents($target) !== $output) {
|
||||
fwrite(STDERR, "Recovery contract is stale; run php tools/generate-recovery-contract.php\n");
|
||||
exit(1);
|
||||
}
|
||||
echo "Generated recovery contract is current.\n";
|
||||
exit(0);
|
||||
}
|
||||
if (file_put_contents($target, $output) !== strlen($output)) {
|
||||
throw new RuntimeException('Could not write PHP recovery contract.');
|
||||
}
|
||||
echo "Generated PHP recovery contract.\n";
|
||||
@ -0,0 +1,221 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
// Generated from agent/operation/recovery_contract.json. Do not edit.
|
||||
// Regenerate: php tools/generate-recovery-contract.php
|
||||
final class CloudOperationRecoveryContract
|
||||
{
|
||||
public const OPERATIONS = [
|
||||
'action' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['power-start', 'power-shutdown', 'power-reboot', 'power-reset', 'power-destroy'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'reinstall' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['reinstall-vm'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'rescue' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['enter-rescue', 'force-start-rescue', 'exit-rescue:connected', 'exit-rescue:suspended'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'delete' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['delete-vm'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'delete_force' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['force-delete-vm'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'expiry_delete' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['delete-vm'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'network_change' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['change-network'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'instance_settings' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['update-settings'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'snapshot_create' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => [],
|
||||
'action_patterns' => ['^create-snapshot:[a-f0-9]{32}:(?:filesystem|crash)$'],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'snapshot_restore' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => [],
|
||||
'action_patterns' => ['^restore-snapshot:[a-f0-9]{32}$'],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'snapshot_delete' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => [],
|
||||
'action_patterns' => ['^delete-snapshot:[a-f0-9]{32}$'],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'firewall_apply' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['apply-firewall'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'service_suspend' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['service-suspend'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'network_suspend' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['network-suspend'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'network_resume' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'instance',
|
||||
'actions' => ['network-resume'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'template_import_replica' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'catalog',
|
||||
'actions' => ['import-template'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'template_metadata_replica' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'catalog',
|
||||
'actions' => ['update-template'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'template_delete_replica' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'catalog',
|
||||
'actions' => ['delete-template'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'rescue_template_import' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'catalog',
|
||||
'actions' => ['import-rescue-template'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'rescue_template_delete' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'catalog',
|
||||
'actions' => ['delete-rescue-template'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'user_iso_import_replica' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'catalog',
|
||||
'actions' => ['import-user-iso'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'user_iso_delete_replica' => [
|
||||
'recovery_mode' => 'generic',
|
||||
'identity_scope' => 'catalog',
|
||||
'actions' => ['delete-user-iso'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['applied', 'not_applied'],
|
||||
],
|
||||
'create' => [
|
||||
'recovery_mode' => 'create',
|
||||
'identity_scope' => 'create',
|
||||
'actions' => ['create-vm'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => ['not_applied'],
|
||||
],
|
||||
'host_storage_configure' => [
|
||||
'recovery_mode' => 'storage',
|
||||
'identity_scope' => 'storage',
|
||||
'actions' => ['configure-storage'],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => [],
|
||||
],
|
||||
'payment_create' => [
|
||||
'recovery_mode' => 'payment',
|
||||
'identity_scope' => 'none',
|
||||
'actions' => [],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => [],
|
||||
],
|
||||
'template_import' => [
|
||||
'recovery_mode' => 'aggregate',
|
||||
'identity_scope' => 'none',
|
||||
'actions' => [],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => [],
|
||||
],
|
||||
'template_metadata_sync' => [
|
||||
'recovery_mode' => 'aggregate',
|
||||
'identity_scope' => 'none',
|
||||
'actions' => [],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => [],
|
||||
],
|
||||
'template_delete' => [
|
||||
'recovery_mode' => 'aggregate',
|
||||
'identity_scope' => 'none',
|
||||
'actions' => [],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => [],
|
||||
],
|
||||
'user_iso_import' => [
|
||||
'recovery_mode' => 'aggregate',
|
||||
'identity_scope' => 'none',
|
||||
'actions' => [],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => [],
|
||||
],
|
||||
'user_iso_delete' => [
|
||||
'recovery_mode' => 'aggregate',
|
||||
'identity_scope' => 'none',
|
||||
'actions' => [],
|
||||
'action_patterns' => [],
|
||||
'system_resolutions' => [],
|
||||
],
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudOperationRecoveryContract;
|
||||
use App\Services\Cloud\CloudOperationRecoveryIdentity;
|
||||
use App\Services\Cloud\CloudOperationRecoveryPolicy;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$contract = json_decode(file_get_contents(
|
||||
dirname(__DIR__, 2) . '/agent/operation/recovery_contract.json'
|
||||
), true, 512, JSON_THROW_ON_ERROR);
|
||||
$assert($contract['schema_version'] === 1, 'Unsupported recovery contract version.');
|
||||
$expected = [];
|
||||
foreach ($contract['operations'] as $entry) {
|
||||
$kind = $entry['kind'];
|
||||
$assert(!isset($expected[$kind]), 'Duplicate recovery kind: ' . $kind);
|
||||
unset($entry['kind']);
|
||||
$expected[$kind] = $entry;
|
||||
}
|
||||
$assert(CloudOperationRecoveryContract::OPERATIONS === $expected,
|
||||
'PHP/Agent recovery inventory drift: run php tools/generate-recovery-contract.php');
|
||||
|
||||
$generic = [];
|
||||
$automatic = [];
|
||||
foreach ($expected as $kind => $entry) {
|
||||
$mode = $entry['recovery_mode'];
|
||||
if ($mode === 'generic') {
|
||||
$generic[] = $kind;
|
||||
$assert($entry['system_resolutions'] === ['applied', 'not_applied'],
|
||||
'A generic leaf lost a recovery direction: ' . $kind);
|
||||
}
|
||||
if (in_array($mode, ['generic', 'create'], true)) {
|
||||
$automatic[] = $kind;
|
||||
}
|
||||
$assert(CloudOperationRecoveryPolicy::supports($kind) === ($mode === 'generic'),
|
||||
'Generic policy mode differs from inventory: ' . $kind);
|
||||
$assert(CloudOperationRecoveryIdentity::supports($kind)
|
||||
=== ($entry['identity_scope'] !== 'none'),
|
||||
'Identity support differs from inventory: ' . $kind);
|
||||
foreach (['applied', 'not_applied', 'unknown', ''] as $resolution) {
|
||||
$assert(CloudOperationRecoveryPolicy::allowsSystemResolution($kind, $resolution)
|
||||
=== in_array($resolution, $entry['system_resolutions'], true),
|
||||
'System resolution differs from inventory: ' . $kind);
|
||||
}
|
||||
foreach ($entry['actions'] as $action) {
|
||||
$assert(CloudOperationRecoveryPolicy::allowsAction($kind, $action),
|
||||
'Declared wire action is not recognized: ' . $kind . '/' . $action);
|
||||
$assert(!CloudOperationRecoveryPolicy::allowsAction($kind, $action . ':future')
|
||||
&& !CloudOperationRecoveryPolicy::allowsAction($kind, $action . "\n"),
|
||||
'Action matching is not exact: ' . $kind);
|
||||
}
|
||||
}
|
||||
$assert(CloudOperationRecoveryPolicy::kinds() === $generic,
|
||||
'Generic selector does not follow the inventory.');
|
||||
$assert(CloudOperationRecoveryPolicy::automaticKinds() === $automatic,
|
||||
'Automatic selector does not follow the inventory.');
|
||||
$assert($expected['create']['recovery_mode'] === 'create'
|
||||
&& $expected['create']['system_resolutions'] === ['not_applied']
|
||||
&& !CloudOperationRecoveryPolicy::supports('create'),
|
||||
'Create must retain dedicated finance recovery and one-way fence resolution.');
|
||||
foreach (['host_storage_configure', 'payment_create', 'template_import',
|
||||
'template_metadata_sync', 'template_delete', 'user_iso_import', 'user_iso_delete'] as $kind) {
|
||||
$assert($expected[$kind]['system_resolutions'] === []
|
||||
&& !in_array($kind, $automatic, true),
|
||||
'A separately finalized operation gained system recovery: ' . $kind);
|
||||
}
|
||||
foreach (['', 'future_kind'] as $kind) {
|
||||
$assert(!CloudOperationRecoveryPolicy::supports($kind)
|
||||
&& !CloudOperationRecoveryIdentity::supports($kind)
|
||||
&& !CloudOperationRecoveryPolicy::allowsAction($kind, 'create-vm'),
|
||||
'Unknown kinds must be denied.');
|
||||
}
|
||||
$key = str_repeat('ab', 16);
|
||||
foreach ([
|
||||
['snapshot_create', 'create-snapshot:' . $key . ':filesystem'],
|
||||
['snapshot_create', 'create-snapshot:' . $key . ':crash'],
|
||||
['snapshot_restore', 'restore-snapshot:' . $key],
|
||||
['snapshot_delete', 'delete-snapshot:' . $key],
|
||||
] as [$kind, $action]) {
|
||||
$assert(CloudOperationRecoveryPolicy::allowsAction($kind, $action),
|
||||
'Valid parameterized snapshot action was rejected.');
|
||||
foreach ([$action . "\n", $action . ':extra', strtoupper($action),
|
||||
str_replace($key, substr($key, 1), $action)] as $invalid) {
|
||||
$assert(!CloudOperationRecoveryPolicy::allowsAction($kind, $invalid),
|
||||
'Malformed parameterized snapshot action was accepted.');
|
||||
}
|
||||
$assert(!CloudOperationRecoveryPolicy::allowsAction('instance_settings', $action),
|
||||
'An action can escape its owning kind.');
|
||||
}
|
||||
|
||||
echo "PHP/Agent generated recovery inventory contract passed.\n";
|
||||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue