diff --git a/agent/cmd/virt-cloud-agent/main.go b/agent/cmd/virt-cloud-agent/main.go
index 7ceffa99..d13d984b 100644
--- a/agent/cmd/virt-cloud-agent/main.go
+++ b/agent/cmd/virt-cloud-agent/main.go
@@ -176,7 +176,7 @@ func buildProvider(cfg config.Config, getenv func(string) string, goos string) (
}
connection := strings.TrimSpace(getenv("VIRT_CLOUD_AGENT_LIBVIRT_URI"))
binary := strings.TrimSpace(getenv("VIRT_CLOUD_AGENT_VIRSH"))
- backend, err := hypervisor.NewVirshBackend(connection, binary)
+ backend, err := hypervisor.NewVirshBackendWithStorageRoots(connection, binary, cfg.StorageRoots)
if err != nil {
return capability.StaticProvider{AgentID: cfg.AgentID, ProtocolVersion: cfg.ProtocolVersion}, redactedBackendError(err)
}
diff --git a/agent/internal/api/server.go b/agent/internal/api/server.go
index 9d67d6dd..624a0df9 100644
--- a/agent/internal/api/server.go
+++ b/agent/internal/api/server.go
@@ -168,7 +168,7 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
// Keep this warning stable and non-sensitive for monitoring clients.
warnings = append(warnings, config.Warning{Code: "agent_identity_missing", Message: "agent identity is not configured; mutating requests remain disabled"})
}
- if s.cfg.RequireSigned && !s.auth.Ready() {
+ if s.cfg.RequireSigned && (s.auth == nil || !s.auth.Ready()) {
warnings = append(warnings, config.Warning{Code: "request_signing_not_ready", Message: "signed request verification is not ready; protected requests remain disabled"})
}
if s.cfg.RequireMTLS && len(s.cfg.ClientCertFingerprints) == 0 {
@@ -201,7 +201,7 @@ func (s *Server) readiness() config.Readiness {
if s.cfg.RequireMTLS && len(s.cfg.ClientCertFingerprints) == 0 {
return config.ReadinessDegraded
}
- if s.cfg.RequireSigned && !s.auth.Ready() {
+ if s.cfg.RequireSigned && (s.auth == nil || !s.auth.Ready()) {
return config.ReadinessDegraded
}
return config.ReadinessReady
@@ -282,9 +282,6 @@ func (s *Server) agentTest(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) createOperation(w http.ResponseWriter, r *http.Request) {
- if !s.writeAllowed(w, r.Context()) {
- return
- }
body, err := readBody(r, s.cfg.MaxBodyBytes)
if err != nil {
writeJSON(w, http.StatusBadRequest, errorResponse{Error: "invalid operation request body"})
@@ -303,6 +300,19 @@ func (s *Server) createOperation(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusNotImplemented, errorResponse{Error: "operation kind is not implemented by the agent"})
return
}
+ // A domain preflight is deliberately the escape hatch from a stale host
+ // readiness result: its purpose is to obtain the fresh capability
+ // observation that can repair that result. It still requires the complete
+ // control-plane gate (authenticated transport, agent identity and a
+ // durable journal), but it must not require a successful Probe() first.
+ // Every other operation remains behind the normal host readiness gate.
+ if request.Kind == "domain_preflight" {
+ if !s.preflightAllowed(w) {
+ return
+ }
+ } else if !s.writeAllowed(w, r.Context()) {
+ return
+ }
if request.Kind == "domain_preflight" {
preflightRequest, parseErr := parseDomainPreflightRequest(request.Payload)
if parseErr != nil || !targetMatchesUUID(request.Target, preflightRequest.UUID) {
@@ -378,6 +388,13 @@ func (s *Server) createOperation(w http.ResponseWriter, r *http.Request) {
s.completeCapabilityProbe(w, record, ctx)
return
}
+ // domain_preflight owns its own typed nil-backend/unavailable result. Keep
+ // it ahead of the generic backend guard so the durable operation contains
+ // domain_preflight_host_unavailable rather than backend_unavailable.
+ if request.Kind == "domain_preflight" {
+ s.completeDomainPreflight(w, record, request, ctx)
+ return
+ }
if s.backend == nil {
_, _ = s.store.Update(record.OperationID, operation.StatusFailed, nil, "backend_unavailable", "host backend is not configured")
writeJSON(w, http.StatusServiceUnavailable, errorResponse{Error: "host backend is not configured"})
@@ -395,10 +412,6 @@ func (s *Server) createOperation(w http.ResponseWriter, r *http.Request) {
s.completeSeedPrepare(w, record, request, ctx)
return
}
- if request.Kind == "domain_preflight" {
- s.completeDomainPreflight(w, record, request, ctx)
- return
- }
s.completeDomainDefine(w, record, request, ctx)
}
@@ -1029,14 +1042,23 @@ func (s *Server) getOperation(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) reconcileOperation(w http.ResponseWriter, r *http.Request) {
- if !s.writeAllowed(w, r.Context()) {
- return
- }
record, err := s.storeRecord(r.PathValue("id"))
if err != nil {
writeJSON(w, http.StatusNotFound, errorResponse{Error: "operation not found"})
return
}
+ // Reconciliation of a preflight is another read-only capability
+ // observation. Allow it through the control-plane gate while the host
+ // readiness bit is degraded; otherwise an unavailable/policy result could
+ // never be durably re-observed. Mutating or lifecycle reconciliation keeps
+ // the normal fail-closed host readiness gate.
+ if record.Kind == "domain_preflight" {
+ if !s.preflightAllowed(w) {
+ return
+ }
+ } else if !s.writeAllowed(w, r.Context()) {
+ return
+ }
if record.Status != operation.StatusUncertain {
writeJSON(w, http.StatusOK, record)
return
@@ -1345,6 +1367,35 @@ func (s *Server) writeAllowed(w http.ResponseWriter, ctx context.Context) bool {
return false
}
+// preflightAllowed is the narrower gate for a domain_preflight operation.
+// Preflight is read-only and exists to obtain a fresh capability observation,
+// so requiring hostReady here would make a failed/stale host probe impossible
+// to diagnose or reconcile. Transport authentication is enforced by Handler;
+// this method covers the remaining local control-plane invariants and keeps
+// the durable journal mandatory.
+func (s *Server) preflightAllowed(w http.ResponseWriter) bool {
+ if s == nil || s.store == nil || !s.store.Writable() || s.cfg.AgentID == "" {
+ writeJSON(w, http.StatusServiceUnavailable, errorResponse{Error: "agent control plane is degraded and preflight is disabled"})
+ return false
+ }
+ s.stateMu.RLock()
+ tlsReady := s.tlsReady
+ s.stateMu.RUnlock()
+ if s.cfg.RequireMTLS && (!s.cfg.TLSComplete() || !tlsReady) {
+ writeJSON(w, http.StatusServiceUnavailable, errorResponse{Error: "agent TLS is not ready for preflight"})
+ return false
+ }
+ if s.cfg.RequireMTLS && len(s.cfg.ClientCertFingerprints) == 0 {
+ writeJSON(w, http.StatusServiceUnavailable, errorResponse{Error: "agent client certificate policy is not ready for preflight"})
+ return false
+ }
+ if s.cfg.RequireSigned && (s.auth == nil || !s.auth.Ready()) {
+ writeJSON(w, http.StatusServiceUnavailable, errorResponse{Error: "agent request signing is not ready for preflight"})
+ return false
+ }
+ return true
+}
+
func (s *Server) authorized(r *http.Request) bool {
if !s.cfg.RequireMTLS && s.cfg.IsLoopbackListen() {
return true
diff --git a/agent/internal/api/server_test.go b/agent/internal/api/server_test.go
index d412ab91..d0cf8efc 100644
--- a/agent/internal/api/server_test.go
+++ b/agent/internal/api/server_test.go
@@ -276,6 +276,159 @@ func TestDomainPreflightIsTypedReadOnlyAndReturnsPolicyHash(t *testing.T) {
}
}
+// preflightProbeBackend lets the API tests distinguish the initial host
+// readiness probe from the capability observation that preflight itself must
+// perform. The fake backend's normal Probe and Capabilities methods share an
+// error knob, so this wrapper models a stale/unavailable Probe independently.
+type preflightProbeBackend struct {
+ *hypervisor.FakeBackend
+ probeErr error
+ capabilityErr error
+ probeCalls int
+ capabilityCalls int
+}
+
+func (b *preflightProbeBackend) Probe(ctx context.Context) (hypervisor.ProbeResult, error) {
+ b.probeCalls++
+ if b.probeErr != nil {
+ return hypervisor.ProbeResult{}, b.probeErr
+ }
+ return b.FakeBackend.Probe(ctx)
+}
+
+func (b *preflightProbeBackend) Capabilities(ctx context.Context) (hypervisor.CapabilitySnapshot, error) {
+ b.capabilityCalls++
+ if b.capabilityErr != nil {
+ return hypervisor.CapabilitySnapshot{}, b.capabilityErr
+ }
+ return b.FakeBackend.Capabilities(ctx)
+}
+
+func preflightOperationBody(operationID, idempotencyKey, uuid string) []byte {
+ return []byte(`{"operation_id":"` + operationID + `","idempotency_key":"` + idempotencyKey + `","kind":"domain_preflight","target":"` + uuid + `","payload":{"uuid":"` + uuid + `","firmware":"efi","architecture":"x86_64","machine":"q35","os_type":"hvm","loader":{"type":"pflash","readonly":true,"secure_boot":false}}}`)
+}
+
+func TestDomainPreflightBypassesStaleHostReadinessGate(t *testing.T) {
+ store := operation.NewMemory()
+ backend := &preflightProbeBackend{
+ FakeBackend: hypervisor.NewFakeBackend(hypervisor.DefaultCapabilitySnapshot()),
+ probeErr: context.DeadlineExceeded,
+ }
+ c := config.Defaults()
+ c.AgentID = "host-preflight-stale"
+ s, err := New(Options{
+ Config: c,
+ Store: store,
+ Capabilities: capability.BackendProvider{Backend: backend, AgentID: c.AgentID, ProtocolVersion: c.ProtocolVersion},
+ Backend: backend,
+ HostBackendReady: false,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ uuid := "00000000-0000-4000-8000-000000000045"
+ recorder := httptest.NewRecorder()
+ s.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/operations", bytes.NewReader(preflightOperationBody(
+ "00000000-0000-4000-8000-000000000046", "idem-preflight-stale-0046", uuid,
+ ))))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("preflight status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ var record operation.Record
+ if err := json.Unmarshal(recorder.Body.Bytes(), &record); err != nil {
+ t.Fatal(err)
+ }
+ if record.Status != operation.StatusSucceeded || record.ErrorCode != "" {
+ t.Fatalf("preflight record=%+v", record)
+ }
+ if backend.probeCalls != 0 || backend.capabilityCalls != 1 {
+ t.Fatalf("backend calls probe=%d capabilities=%d; preflight must skip stale readiness probe", backend.probeCalls, backend.capabilityCalls)
+ }
+}
+
+func TestDomainPreflightHostUnavailableIsDurableAndReconciles(t *testing.T) {
+ store := operation.NewMemory()
+ backend := &preflightProbeBackend{
+ FakeBackend: hypervisor.NewFakeBackend(hypervisor.DefaultCapabilitySnapshot()),
+ capabilityErr: errors.New("libvirt capability transport unavailable"),
+ }
+ c := config.Defaults()
+ c.AgentID = "host-preflight-unavailable"
+ s, err := New(Options{
+ Config: c,
+ Store: store,
+ Capabilities: capability.BackendProvider{Backend: backend, AgentID: c.AgentID, ProtocolVersion: c.ProtocolVersion},
+ Backend: backend,
+ HostBackendReady: false,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ uuid := "00000000-0000-4000-8000-000000000047"
+ id := "00000000-0000-4000-8000-000000000048"
+ recorder := httptest.NewRecorder()
+ s.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/operations", bytes.NewReader(preflightOperationBody(id, "idem-preflight-unavailable-0048", uuid))))
+ if recorder.Code != http.StatusServiceUnavailable {
+ t.Fatalf("preflight status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ record, err := store.Get(id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if record.Status != operation.StatusUncertain || record.ErrorCode != "domain_preflight_host_unavailable" {
+ t.Fatalf("unavailable preflight record=%+v", record)
+ }
+
+ reconcile := httptest.NewRecorder()
+ s.Handler().ServeHTTP(reconcile, httptest.NewRequest(http.MethodPost, "/v1/operations/"+id+"/reconcile", nil))
+ if reconcile.Code != http.StatusServiceUnavailable {
+ t.Fatalf("reconcile status=%d body=%s", reconcile.Code, reconcile.Body.String())
+ }
+ reconciled, err := store.Get(id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if reconciled.Status != operation.StatusUncertain || reconciled.ErrorCode != "domain_preflight_host_unavailable" {
+ t.Fatalf("reconciled unavailable preflight record=%+v", reconciled)
+ }
+ if backend.capabilityCalls != 2 {
+ t.Fatalf("capability calls=%d, want initial + reconcile", backend.capabilityCalls)
+ }
+}
+
+func TestDomainPreflightHostPolicyRejectionIsDurable(t *testing.T) {
+ store := operation.NewMemory()
+ badCaps := hypervisor.DefaultCapabilitySnapshot()
+ badCaps.SecureBootDisabled = false
+ backend := &preflightProbeBackend{FakeBackend: hypervisor.NewFakeBackend(badCaps)}
+ c := config.Defaults()
+ c.AgentID = "host-preflight-policy"
+ s, err := New(Options{
+ Config: c,
+ Store: store,
+ Capabilities: capability.BackendProvider{Backend: backend, AgentID: c.AgentID, ProtocolVersion: c.ProtocolVersion},
+ Backend: backend,
+ HostBackendReady: false,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ uuid := "00000000-0000-4000-8000-000000000049"
+ id := "00000000-0000-4000-8000-000000000050"
+ recorder := httptest.NewRecorder()
+ s.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/operations", bytes.NewReader(preflightOperationBody(id, "idem-preflight-policy-0050", uuid))))
+ if recorder.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("preflight status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ record, err := store.Get(id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if record.Status != operation.StatusFailed || record.ErrorCode != "domain_preflight_host_policy_rejected" {
+ t.Fatalf("policy preflight record=%+v", record)
+ }
+}
+
func TestDomainPreflightRejectsXMLAndDoesNotEnterJournal(t *testing.T) {
store := operation.NewMemory()
s := testBackendServer(t, "host-103", store)
diff --git a/agent/internal/capability/provider.go b/agent/internal/capability/provider.go
index 277e8c1f..eb5947a6 100644
--- a/agent/internal/capability/provider.go
+++ b/agent/internal/capability/provider.go
@@ -90,7 +90,14 @@ func snapshotFromCapabilities(agentID, protocol string, caps hypervisor.Capabili
"qga": caps.QGA,
"snapshots": caps.Snapshots,
"cloud_init": caps.CloudInit,
- "startup_script": caps.StartupScript,
+ // The NoCloud renderer and immutable artifact publisher are Agent
+ // capabilities, not facts that libvirt's domcapabilities XML can
+ // prove. Keep the raw host/guest observation separate so a host
+ // probe cannot accidentally hide a feature the Agent implements.
+ "startup_script": true,
+ "startup_script_agent": true,
+ "startup_script_host": caps.StartupScript,
+ "nocloud_seed_artifact": true,
},
Checks: map[string]string{
"backend": caps.Backend,
diff --git a/agent/internal/capability/provider_test.go b/agent/internal/capability/provider_test.go
new file mode 100644
index 00000000..6715a0bf
--- /dev/null
+++ b/agent/internal/capability/provider_test.go
@@ -0,0 +1,37 @@
+package capability
+
+import (
+ "context"
+ "testing"
+
+ "g.luoli.live/root/virt/agent/internal/hypervisor"
+)
+
+func TestBackendProviderSeparatesAgentStartupScriptFromHostObservation(t *testing.T) {
+ caps := hypervisor.DefaultCapabilitySnapshot()
+ caps.Backend = "libvirt-domcapabilities"
+ caps.CloudInit = false
+ caps.StartupScript = false
+ snapshot := snapshotFromCapabilities("host-103", "v1", caps)
+ if snapshot.Features["cloud_init"] {
+ t.Fatal("cloud_init must remain the unproven host/guest observation")
+ }
+ for _, key := range []string{"startup_script", "startup_script_agent", "nocloud_seed_artifact"} {
+ if !snapshot.Features[key] {
+ t.Fatalf("feature %q = false, Agent artifact implementation should advertise it", key)
+ }
+ }
+ if snapshot.Features["startup_script_host"] {
+ t.Fatal("startup_script_host must preserve the false host observation")
+ }
+}
+
+func TestBackendProviderDoesNotUseStaticProviderForHostFeatures(t *testing.T) {
+ snapshot, err := (StaticProvider{AgentID: "host-103", ProtocolVersion: "v1"}).Snapshot(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if snapshot.Features["startup_script"] || snapshot.Features["nocloud_seed_artifact"] {
+ t.Fatal("static development provider must remain conservative")
+ }
+}
diff --git a/agent/internal/config/config.go b/agent/internal/config/config.go
index 354eab23..b14194e6 100644
--- a/agent/internal/config/config.go
+++ b/agent/internal/config/config.go
@@ -46,10 +46,16 @@ type Warning struct {
// Config is deliberately small. Host-specific libvirt settings belong behind
// the host capability layer rather than in the panel-facing transport.
type Config struct {
- ListenAddr string
- AgentID string
- JournalPath string
- ArtifactRoot string
+ ListenAddr string
+ AgentID string
+ JournalPath string
+ ArtifactRoot string
+ // StorageRoots is the explicit allowlist for existing file-backed disk
+ // images. An empty list is intentional fail-closed behavior: the agent
+ // may still expose read-only capability and seed operations, but a domain
+ // definition that references a host file is rejected until an operator
+ // provisions and registers a root.
+ StorageRoots []string
TLSCertFile string
TLSKeyFile string
TLSCAFile string
@@ -98,6 +104,15 @@ func Load(getenv func(string) string) (Config, []Warning, error) {
setString("VIRT_CLOUD_AGENT_ID", &c.AgentID)
setString("VIRT_CLOUD_AGENT_JOURNAL", &c.JournalPath)
setString("VIRT_CLOUD_AGENT_ARTIFACT_ROOT", &c.ArtifactRoot)
+ if raw := strings.TrimSpace(getenv("VIRT_CLOUD_AGENT_STORAGE_ROOTS")); raw != "" {
+ for _, item := range strings.Split(raw, ",") {
+ item = strings.TrimSpace(item)
+ if item == "" {
+ return Config{}, nil, fmt.Errorf("VIRT_CLOUD_AGENT_STORAGE_ROOTS contains an empty entry")
+ }
+ c.StorageRoots = append(c.StorageRoots, item)
+ }
+ }
setString("VIRT_CLOUD_AGENT_TLS_CERT", &c.TLSCertFile)
setString("VIRT_CLOUD_AGENT_TLS_KEY", &c.TLSKeyFile)
setString("VIRT_CLOUD_AGENT_TLS_CA", &c.TLSCAFile)
@@ -203,6 +218,16 @@ func (c Config) Validate() error {
if c.ArtifactRoot == "" || !filepath.IsAbs(c.ArtifactRoot) || filepath.Clean(c.ArtifactRoot) != c.ArtifactRoot || strings.ContainsAny(c.ArtifactRoot, "\x00\r\n") {
return fmt.Errorf("artifact root must be an absolute path")
}
+ seenStorageRoots := make(map[string]struct{}, len(c.StorageRoots))
+ for _, root := range c.StorageRoots {
+ if root == "" || !filepath.IsAbs(root) || filepath.Clean(root) != root || strings.ContainsAny(root, "\x00\r\n\t\\") {
+ return fmt.Errorf("storage roots must be canonical absolute paths")
+ }
+ if _, exists := seenStorageRoots[root]; exists {
+ return fmt.Errorf("duplicate storage root %q", root)
+ }
+ seenStorageRoots[root] = struct{}{}
+ }
if c.MaxBodyBytes < 1024 {
return fmt.Errorf("max body bytes must be >= 1024")
}
diff --git a/agent/internal/config/config_test.go b/agent/internal/config/config_test.go
index 169a7d6f..c27540ba 100644
--- a/agent/internal/config/config_test.go
+++ b/agent/internal/config/config_test.go
@@ -1,6 +1,7 @@
package config
import (
+ "path/filepath"
"strings"
"testing"
)
@@ -129,3 +130,33 @@ func TestValidateRejectsUnsafeAgentIdentity(t *testing.T) {
}
}
}
+
+func TestLoadParsesExplicitStorageRoots(t *testing.T) {
+ root := filepath.Join("/var", "lib", "virt-cloud", "images")
+ c, _, err := Load(env(map[string]string{
+ "VIRT_CLOUD_AGENT_STORAGE_ROOTS": root + ",/srv/libvirt/images",
+ }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(c.StorageRoots) != 2 || c.StorageRoots[0] != root || c.StorageRoots[1] != "/srv/libvirt/images" {
+ t.Fatalf("storage roots = %#v", c.StorageRoots)
+ }
+}
+
+func TestLoadRejectsEmptyStorageRootEntry(t *testing.T) {
+ _, _, err := Load(env(map[string]string{
+ "VIRT_CLOUD_AGENT_STORAGE_ROOTS": "/srv/images,,/srv/other",
+ }))
+ if err == nil {
+ t.Fatal("expected empty storage root entry to be rejected")
+ }
+}
+
+func TestValidateRejectsNonCanonicalStorageRoot(t *testing.T) {
+ c := Defaults()
+ c.StorageRoots = []string{"/srv/images/../images"}
+ if err := c.Validate(); err == nil {
+ t.Fatal("accepted non-canonical storage root")
+ }
+}
diff --git a/agent/internal/domainpreflight/preflight.go b/agent/internal/domainpreflight/preflight.go
index 91915ad0..87eb5857 100644
--- a/agent/internal/domainpreflight/preflight.go
+++ b/agent/internal/domainpreflight/preflight.go
@@ -65,23 +65,28 @@ type Result struct {
// CapabilitySummary is the journal-safe projection of a host capability
// snapshot. It intentionally avoids the generic `startup_script` key: the
// operation journal treats that key as tenant-provided script content and
-// redacts it. `FirstBootScript` is the same boolean capability under a stable,
-// non-secret name, so a result remains type-correct after journal sanitizing.
+// redacts it. `FirstBootScript` describes the Agent's immutable NoCloud
+// artifact implementation; the raw host/guest observation is exposed
+// separately as `FirstBootScriptHost` so a domcapabilities probe cannot hide
+// the implemented transport or imply that every guest image contains
+// cloud-init.
type CapabilitySummary struct {
- Backend string `json:"backend,omitempty"`
- LibvirtVersion string `json:"libvirt_version,omitempty"`
- QEMUVersion string `json:"qemu_version,omitempty"`
- Architecture string `json:"architecture,omitempty"`
- UEFI bool `json:"uefi"`
- Q35 bool `json:"q35"`
- SecureBootCapable bool `json:"secure_boot_capable"`
- SecureBootDisabled bool `json:"secure_boot_disabled"`
- QGA bool `json:"qga"`
- Snapshots bool `json:"snapshots"`
- CloudInit bool `json:"cloud_init"`
- FirstBootScript bool `json:"first_boot_script"`
- Policy string `json:"policy"`
- ObservedAt time.Time `json:"observed_at"`
+ Backend string `json:"backend,omitempty"`
+ LibvirtVersion string `json:"libvirt_version,omitempty"`
+ QEMUVersion string `json:"qemu_version,omitempty"`
+ Architecture string `json:"architecture,omitempty"`
+ UEFI bool `json:"uefi"`
+ Q35 bool `json:"q35"`
+ SecureBootCapable bool `json:"secure_boot_capable"`
+ SecureBootDisabled bool `json:"secure_boot_disabled"`
+ QGA bool `json:"qga"`
+ Snapshots bool `json:"snapshots"`
+ CloudInit bool `json:"cloud_init"`
+ FirstBootScript bool `json:"first_boot_script"`
+ FirstBootScriptHost bool `json:"first_boot_script_host"`
+ NoCloudSeedArtifact bool `json:"nocloud_seed_artifact"`
+ Policy string `json:"policy"`
+ ObservedAt time.Time `json:"observed_at"`
}
var (
@@ -239,20 +244,22 @@ func summarizeCapabilities(caps hypervisor.CapabilitySnapshot) CapabilitySummary
policy = "efi-q35-no-secure-boot"
}
return CapabilitySummary{
- Backend: caps.Backend,
- LibvirtVersion: caps.LibvirtVersion,
- QEMUVersion: caps.QEMUVersion,
- Architecture: caps.Architecture,
- UEFI: caps.UEFI,
- Q35: caps.Q35,
- SecureBootCapable: caps.SecureBootCapable,
- SecureBootDisabled: caps.SecureBootDisabled,
- QGA: caps.QGA,
- Snapshots: caps.Snapshots,
- CloudInit: caps.CloudInit,
- FirstBootScript: caps.StartupScript,
- Policy: policy,
- ObservedAt: caps.ObservedAt,
+ Backend: caps.Backend,
+ LibvirtVersion: caps.LibvirtVersion,
+ QEMUVersion: caps.QEMUVersion,
+ Architecture: caps.Architecture,
+ UEFI: caps.UEFI,
+ Q35: caps.Q35,
+ SecureBootCapable: caps.SecureBootCapable,
+ SecureBootDisabled: caps.SecureBootDisabled,
+ QGA: caps.QGA,
+ Snapshots: caps.Snapshots,
+ CloudInit: caps.CloudInit,
+ FirstBootScript: true,
+ FirstBootScriptHost: caps.StartupScript,
+ NoCloudSeedArtifact: true,
+ Policy: policy,
+ ObservedAt: caps.ObservedAt,
}
}
diff --git a/agent/internal/domainpreflight/preflight_test.go b/agent/internal/domainpreflight/preflight_test.go
index fb24862b..8e4a7301 100644
--- a/agent/internal/domainpreflight/preflight_test.go
+++ b/agent/internal/domainpreflight/preflight_test.go
@@ -43,6 +43,12 @@ func TestRunReturnsReadOnlyNormalizedPolicyAndHash(t *testing.T) {
if result.Capabilities.Architecture != ArchitectureX86 {
t.Fatalf("capabilities architecture = %q", result.Capabilities.Architecture)
}
+ if !result.Capabilities.FirstBootScript || !result.Capabilities.NoCloudSeedArtifact {
+ t.Fatalf("agent startup-script artifact capability was not advertised: %+v", result.Capabilities)
+ }
+ if !result.Capabilities.FirstBootScriptHost {
+ t.Fatal("fake backend's host startup-script observation should remain true")
+ }
if !strings.Contains(result.NormalizedXML, ""+testUUID+"") ||
!strings.Contains(result.NormalizedXML, `firmware="efi"`) ||
!strings.Contains(result.NormalizedXML, `arch="x86_64"`) ||
diff --git a/agent/internal/domainxml/domainxml.go b/agent/internal/domainxml/domainxml.go
index 51cedf48..2a3f723f 100644
--- a/agent/internal/domainxml/domainxml.go
+++ b/agent/internal/domainxml/domainxml.go
@@ -186,6 +186,63 @@ func Validate(input []byte) error {
return validateRoot(doc.root, true)
}
+// FileBackedDiskPaths returns the host paths used by file-backed disk
+// sources. It is intentionally a parser-level operation rather than a
+// regexp: XML escaping, element ordering and namespace-qualified elements
+// must not let a path skip the storage policy. The returned paths are still
+// untrusted strings; callers must pass them through a host storage allowlist
+// before invoking libvirt.
+func FileBackedDiskPaths(input []byte) ([]string, error) {
+ doc, err := parse(input)
+ if err != nil {
+ return nil, err
+ }
+ paths := make([]string, 0, 1)
+ var walk func(*element) error
+ walk = func(node *element) error {
+ if node == nil {
+ return nil
+ }
+ if node.name.Space == "" && node.name.Local == "disk" {
+ diskType, err := node.singleAttr("type", "disk")
+ if err != nil {
+ return err
+ }
+ sources := node.childrenNamed("source")
+ if len(sources) > 1 {
+ return fmt.Errorf("%w: disk contains %d elements", ErrPolicyViolation, len(sources))
+ }
+ if len(sources) == 1 {
+ filePath, err := sources[0].singleAttr("file", "disk/source")
+ if err != nil {
+ return err
+ }
+ if strings.TrimSpace(filePath) != "" {
+ if diskType != "" && diskType != "file" {
+ return fmt.Errorf("%w: disk type=%q cannot contain a file-backed source", ErrPolicyViolation, diskType)
+ }
+ if strings.TrimSpace(filePath) != filePath {
+ return fmt.Errorf("%w: disk source path has surrounding whitespace", ErrPolicyViolation)
+ }
+ paths = append(paths, filePath)
+ }
+ }
+ }
+ for _, child := range node.children {
+ if child.kind == contentElement {
+ if err := walk(child.elem); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+ }
+ if err := walk(doc.root); err != nil {
+ return nil, err
+ }
+ return paths, nil
+}
+
func normalizeOS(osNode *element) error {
firmware, err := osNode.singleAttr("firmware", "os")
if err != nil {
diff --git a/agent/internal/domainxml/domainxml_test.go b/agent/internal/domainxml/domainxml_test.go
index 09b8cefc..75ff9022 100644
--- a/agent/internal/domainxml/domainxml_test.go
+++ b/agent/internal/domainxml/domainxml_test.go
@@ -5,6 +5,7 @@ import (
"encoding/xml"
"errors"
"fmt"
+ "reflect"
"strings"
"testing"
)
@@ -90,6 +91,59 @@ func TestNormalizeDomainPlatformPolicy(t *testing.T) {
}
}
+func TestFileBackedDiskPathsExtractsOnlyFileSources(t *testing.T) {
+ input := `` +
+ `` +
+ `` +
+ ``
+ paths, err := FileBackedDiskPaths([]byte(input))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{"/var/lib/libvirt/images/a.qcow2", "/var/lib/libvirt/images/install.iso"}
+ if !reflect.DeepEqual(paths, want) {
+ t.Fatalf("FileBackedDiskPaths() = %v, want %v", paths, want)
+ }
+}
+
+func TestFileBackedDiskPathsRejectsAmbiguousSources(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ }{
+ {
+ name: "network disk with file source",
+ input: ``,
+ },
+ {
+ name: "duplicate source elements",
+ input: ``,
+ },
+ {
+ name: "surrounding whitespace",
+ input: ``,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if _, err := FileBackedDiskPaths([]byte(tt.input)); !errors.Is(err, ErrPolicyViolation) {
+ t.Fatalf("FileBackedDiskPaths() error = %v, want ErrPolicyViolation", err)
+ }
+ })
+ }
+}
+
+func TestFileBackedDiskPathsIgnoresNonFileSource(t *testing.T) {
+ input := ``
+ paths, err := FileBackedDiskPaths([]byte(input))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(paths) != 0 {
+ t.Fatalf("FileBackedDiskPaths() = %v, want no file paths", paths)
+ }
+}
+
func TestNormalizeRejectsExplicitPlatformDowngrade(t *testing.T) {
tests := []struct {
name string
diff --git a/agent/internal/hypervisor/backend.go b/agent/internal/hypervisor/backend.go
index eedf1abf..a30636e2 100644
--- a/agent/internal/hypervisor/backend.go
+++ b/agent/internal/hypervisor/backend.go
@@ -18,6 +18,7 @@ import (
"time"
"g.luoli.live/root/virt/agent/internal/domainxml"
+ "g.luoli.live/root/virt/agent/internal/storagepolicy"
)
var (
@@ -60,6 +61,7 @@ func IsDefinitive(err error) bool {
errors.Is(err, ErrPowerActionRejected) ||
errors.Is(err, ErrCapabilityPolicy) ||
errors.Is(err, ErrDomainNotFound) ||
+ storagepolicy.IsDefinitive(err) ||
errors.Is(err, domainxml.ErrInvalidXML) ||
errors.Is(err, domainxml.ErrUnsupportedPlatform) ||
errors.Is(err, domainxml.ErrPolicyViolation)
@@ -73,19 +75,23 @@ func IsDefinitive(err error) bool {
// fields separate prevents a host that supports Secure Boot from accidentally
// turning it on when the product policy requires it to remain off.
type CapabilitySnapshot struct {
- Backend string `json:"backend,omitempty"`
- LibvirtVersion string `json:"libvirt_version,omitempty"`
- QEMUVersion string `json:"qemu_version,omitempty"`
- Architecture string `json:"architecture,omitempty"`
- UEFI bool `json:"uefi"`
- Q35 bool `json:"q35"`
- SecureBootCapable bool `json:"secure_boot_capable"`
- SecureBootDisabled bool `json:"secure_boot_disabled"`
- QGA bool `json:"qga"`
- Snapshots bool `json:"snapshots"`
- CloudInit bool `json:"cloud_init"`
- StartupScript bool `json:"startup_script"`
- ObservedAt time.Time `json:"observed_at"`
+ Backend string `json:"backend,omitempty"`
+ LibvirtVersion string `json:"libvirt_version,omitempty"`
+ QEMUVersion string `json:"qemu_version,omitempty"`
+ Architecture string `json:"architecture,omitempty"`
+ UEFI bool `json:"uefi"`
+ Q35 bool `json:"q35"`
+ SecureBootCapable bool `json:"secure_boot_capable"`
+ SecureBootDisabled bool `json:"secure_boot_disabled"`
+ QGA bool `json:"qga"`
+ Snapshots bool `json:"snapshots"`
+ CloudInit bool `json:"cloud_init"`
+ // StartupScript is a raw host/guest observation when a backend can prove
+ // it. The Agent-side NoCloud artifact implementation is advertised by the
+ // capability provider separately; this field must not be used as a proxy
+ // for that implementation.
+ StartupScript bool `json:"startup_script"`
+ ObservedAt time.Time `json:"observed_at"`
}
// DefaultCapabilitySnapshot is useful for an in-memory backend and documents
diff --git a/agent/internal/hypervisor/virsh.go b/agent/internal/hypervisor/virsh.go
index b7b7f61b..19f68a82 100644
--- a/agent/internal/hypervisor/virsh.go
+++ b/agent/internal/hypervisor/virsh.go
@@ -20,6 +20,7 @@ import (
"time"
"g.luoli.live/root/virt/agent/internal/domainxml"
+ "g.luoli.live/root/virt/agent/internal/storagepolicy"
)
const (
@@ -124,6 +125,10 @@ type VirshBackend struct {
// constructor uses the platform temporary directory, which is commonly
// mode 01777; it still receives the symlink/type/existence checks.
strictStaging bool
+ // storagePolicy scopes every file-backed disk source before `virsh
+ // define`. An empty policy is intentionally fail-closed when XML contains
+ // any file-backed disk, while firmware-only definitions do not need it.
+ storagePolicy storagepolicy.Policy
// mutationMu serializes host-side domain definitions and lifecycle
// commands. libvirt may expose each command as an independent process,
// but a define/read-back or power/read-back sequence is one logical host
@@ -136,6 +141,15 @@ type VirshBackend struct {
}
func NewVirshBackend(connection, binary string) (*VirshBackend, error) {
+ return NewVirshBackendWithStorageRoots(connection, binary, nil)
+}
+
+// NewVirshBackendWithStorageRoots constructs the production Linux adapter
+// with an explicit allowlist for existing file-backed disk images. Roots are
+// syntax-checked here and their filesystem identity is checked again at each
+// define boundary. A missing/empty root list never becomes an allow-all
+// fallback.
+func NewVirshBackendWithStorageRoots(connection, binary string, storageRoots []string) (*VirshBackend, error) {
if strings.TrimSpace(connection) == "" {
connection = defaultLibvirtURI
}
@@ -149,17 +163,29 @@ func NewVirshBackend(connection, binary string) (*VirshBackend, error) {
if !validVirshBinary(binary) {
return nil, fmt.Errorf("%w: virsh executable is not allowlisted", ErrVirshUnavailable)
}
+ storagePolicy, err := storagepolicy.New(storageRoots)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrVirshUnavailable, err)
+ }
return &VirshBackend{
runner: ExecRunner{Binary: binary},
connection: connection,
stagingDir: defaultDomainXMLStagingDir,
strictStaging: true,
+ storagePolicy: storagePolicy,
}, nil
}
// NewVirshBackendWithRunner is intended for deterministic tests and local
// protocol simulations. It does not bypass any XML or UUID policy checks.
func NewVirshBackendWithRunner(connection string, runner CommandRunner) (*VirshBackend, error) {
+ return NewVirshBackendWithRunnerAndStorageRoots(connection, runner, nil)
+}
+
+// NewVirshBackendWithRunnerAndStorageRoots is the injectable equivalent of
+// NewVirshBackendWithStorageRoots. It exists for tests and local simulations;
+// it retains the exact same file-backed disk gate.
+func NewVirshBackendWithRunnerAndStorageRoots(connection string, runner CommandRunner, storageRoots []string) (*VirshBackend, error) {
if runner == nil {
return nil, fmt.Errorf("%w: command runner is nil", ErrVirshUnavailable)
}
@@ -169,7 +195,11 @@ func NewVirshBackendWithRunner(connection string, runner CommandRunner) (*VirshB
if !validLibvirtConnection(connection) {
return nil, fmt.Errorf("%w: only local qemu:///system is allowed", ErrVirshUnavailable)
}
- return &VirshBackend{runner: runner, connection: connection, stagingDir: filepath.Clean(os.TempDir())}, nil
+ storagePolicy, err := storagepolicy.New(storageRoots)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrVirshUnavailable, err)
+ }
+ return &VirshBackend{runner: runner, connection: connection, stagingDir: filepath.Clean(os.TempDir()), storagePolicy: storagePolicy}, nil
}
func validLibvirtConnection(value string) bool {
@@ -299,6 +329,13 @@ func (b *VirshBackend) DefineDomain(ctx context.Context, request DefineRequest)
if err != nil {
return Definition{}, err
}
+ filePaths, err := domainxml.FileBackedDiskPaths(normalized)
+ if err != nil {
+ return Definition{}, err
+ }
+ if err := b.storagePolicy.ValidatePaths(filePaths); err != nil {
+ return Definition{}, err
+ }
if err := validateDomainXMLStagingDir(b.stagingDir, b.strictStaging); err != nil {
return Definition{}, err
}
@@ -381,6 +418,17 @@ func (b *VirshBackend) ReadDomainXML(ctx context.Context, uuid string) ([]byte,
// ErrDomainNotFound explicitly when it can prove that condition.
return nil, err
}
+ // Read-back is part of the storage policy boundary too. A domain that was
+ // changed out-of-band must not be reported as a valid Agent definition just
+ // because its UUID and firmware still look correct; file-backed sources are
+ // rechecked before the XML leaves the host adapter.
+ filePaths, err := domainxml.FileBackedDiskPaths(data)
+ if err != nil {
+ return nil, err
+ }
+ if err := b.storagePolicy.ValidatePaths(filePaths); err != nil {
+ return nil, err
+ }
observed, err := domainUUID(data)
if err != nil || observed != canonical {
return nil, fmt.Errorf("%w: requested %s", ErrReadbackMismatch, canonical)
diff --git a/agent/internal/hypervisor/virsh_test.go b/agent/internal/hypervisor/virsh_test.go
index d346331b..436fccbc 100644
--- a/agent/internal/hypervisor/virsh_test.go
+++ b/agent/internal/hypervisor/virsh_test.go
@@ -10,6 +10,8 @@ import (
"sync"
"testing"
"time"
+
+ "g.luoli.live/root/virt/agent/internal/storagepolicy"
)
const testDomainCapabilities = `
@@ -114,6 +116,77 @@ func TestVirshBackendUsesFixedArgumentsAndReadback(t *testing.T) {
}
}
+func TestVirshBackendFileDiskRequiresConfiguredStorageRoot(t *testing.T) {
+ root := t.TempDir()
+ canonicalRoot, err := filepath.EvalSymlinks(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ disk := filepath.Join(canonicalRoot, "disk.qcow2")
+ if err := os.WriteFile(disk, []byte("image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ xmlWithDisk := strings.Replace(string(testDomainXML(testUUID)), "",
+ ``, 1)
+
+ withoutRoot, err := NewVirshBackendWithRunner("qemu:///system", &recordingRunner{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := withoutRoot.DefineDomain(context.Background(), DefineRequest{UUID: testUUID, XML: []byte(xmlWithDisk)}); !errors.Is(err, storagepolicy.ErrNotConfigured) {
+ t.Fatalf("define without storage root error = %v, want ErrNotConfigured", err)
+ }
+
+ runner := &recordingRunner{}
+ withRoot, err := NewVirshBackendWithRunnerAndStorageRoots("qemu:///system", runner, []string{canonicalRoot})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := withRoot.DefineDomain(context.Background(), DefineRequest{UUID: testUUID, XML: []byte(xmlWithDisk)}); err != nil {
+ t.Fatalf("define with explicit storage root failed: %v", err)
+ }
+}
+
+type fileReadbackRunner struct {
+ xml []byte
+}
+
+func (r fileReadbackRunner) Run(_ context.Context, args ...string) ([]byte, error) {
+ if len(args) >= 3 && args[2] == "dumpxml" {
+ return append([]byte(nil), r.xml...), nil
+ }
+ return nil, errors.New("unexpected command")
+}
+
+func TestVirshBackendReadbackRechecksFileStoragePolicy(t *testing.T) {
+ root := t.TempDir()
+ canonicalRoot, err := filepath.EvalSymlinks(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ disk := filepath.Join(canonicalRoot, "disk.qcow2")
+ if err := os.WriteFile(disk, []byte("image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ readbackXML := []byte(`` + testUUID + `hvm/usr/share/OVMF/OVMF_CODE_4M.fd`)
+
+ withoutRoot, err := NewVirshBackendWithRunner("qemu:///system", fileReadbackRunner{xml: readbackXML})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := withoutRoot.ReadDomainXML(context.Background(), testUUID); !errors.Is(err, storagepolicy.ErrNotConfigured) {
+ t.Fatalf("readback without storage root error = %v, want ErrNotConfigured", err)
+ }
+
+ withRoot, err := NewVirshBackendWithRunnerAndStorageRoots("qemu:///system", fileReadbackRunner{xml: readbackXML}, []string{canonicalRoot})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := withRoot.ReadDomainXML(context.Background(), testUUID); err != nil {
+ t.Fatalf("readback with configured storage root failed: %v", err)
+ }
+}
+
func TestFixedVirshEnvPinsLocaleWithoutDuplicates(t *testing.T) {
for key, value := range map[string]string{
"LC_ALL": "de_DE.UTF-8",
diff --git a/agent/internal/startup/artifact.go b/agent/internal/startup/artifact.go
index 231cee88..d467a018 100644
--- a/agent/internal/startup/artifact.go
+++ b/agent/internal/startup/artifact.go
@@ -439,6 +439,13 @@ func validateArtifactParent(parent string) error {
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return fmt.Errorf("%w: artifact parent must be a directory", ErrArtifactPath)
}
+ // Publication uses a sibling temporary directory followed by rename. A
+ // group/world-writable or special-bit parent would let another local user
+ // race that boundary, replace the staging entry, or observe tenant seed
+ // material before the immutable target is verified.
+ if info.Mode().Perm()&0o022 != 0 || info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 {
+ return fmt.Errorf("%w: artifact parent must not be group/world writable or carry special mode bits", ErrArtifactPath)
+ }
return nil
}
diff --git a/agent/internal/startup/startup_test.go b/agent/internal/startup/startup_test.go
index 086eae9e..f41bac36 100644
--- a/agent/internal/startup/startup_test.go
+++ b/agent/internal/startup/startup_test.go
@@ -449,6 +449,20 @@ func TestWriteSeedDirectoryRejectsUnsafeTargets(t *testing.T) {
}
}
+func TestWriteSeedDirectoryRejectsPermissiveParent(t *testing.T) {
+ files, err := BuildCreateSeed("instance-001", "vm-001", "", "echo ok\n")
+ if err != nil {
+ t.Fatal(err)
+ }
+ parent := t.TempDir()
+ if err := os.Chmod(parent, 0o770); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := WriteSeedDirectory(filepath.Join(parent, "seed"), files); !errors.Is(err, ErrArtifactPath) {
+ t.Fatalf("permissive artifact parent error = %v, want ErrArtifactPath", err)
+ }
+}
+
func TestVerifySeedDirectoryDetectsTampering(t *testing.T) {
parent := t.TempDir()
target := filepath.Join(parent, "seed")
diff --git a/agent/internal/storagepolicy/storagepolicy.go b/agent/internal/storagepolicy/storagepolicy.go
new file mode 100644
index 00000000..bdd28248
--- /dev/null
+++ b/agent/internal/storagepolicy/storagepolicy.go
@@ -0,0 +1,213 @@
+// Package storagepolicy validates host paths referenced by file-backed
+// libvirt disks. The panel may submit domain XML, but it must never be able
+// to choose an arbitrary host path. A policy is immutable after construction
+// and every validation re-checks the host filesystem immediately before the
+// caller hands the XML to libvirt.
+package storagepolicy
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+var (
+ // ErrPolicyViolation identifies a definitive, pre-host rejection. Callers
+ // should not retry a request with the same path after this error.
+ ErrPolicyViolation = errors.New("storage path policy violation")
+ // ErrNotConfigured means that a domain references a file-backed disk while
+ // the agent has no explicitly configured storage root. Empty roots are a
+ // deliberate fail-closed posture, not an implicit allow-all mode.
+ ErrNotConfigured = errors.New("file-backed storage roots are not configured")
+ // ErrRootUnavailable means that a configured root cannot be proven to be a
+ // real directory at validation time.
+ ErrRootUnavailable = errors.New("configured storage root is unavailable")
+ // ErrPathUnavailable means that a referenced disk path cannot be proven to
+ // be an existing regular file.
+ ErrPathUnavailable = errors.New("file-backed disk path is unavailable")
+ // ErrPathSymlink means that the root, a root ancestor, a disk path, or a
+ // disk path ancestor is a symbolic link. Rejecting aliases prevents a
+ // later replacement from redirecting libvirt outside the allowlist.
+ ErrPathSymlink = errors.New("file-backed storage path contains a symbolic link")
+ // ErrPathOutsideRoot means that realpath resolution leaves every configured
+ // root, including the root itself.
+ ErrPathOutsideRoot = errors.New("file-backed disk path is outside configured storage roots")
+)
+
+// IsDefinitive reports path errors that prove a define request is not
+// acceptable under the agent's current storage contract. Callers should
+// record these as a typed rejection rather than an ambiguous host timeout;
+// a later request may only proceed after its XML or host storage policy has
+// changed. ErrRootUnavailable is intentionally excluded because an operator
+// may still mount/provision the configured root and then reconcile safely.
+func IsDefinitive(err error) bool {
+ return errors.Is(err, ErrPolicyViolation) ||
+ errors.Is(err, ErrNotConfigured) ||
+ errors.Is(err, ErrPathUnavailable) ||
+ errors.Is(err, ErrPathSymlink) ||
+ errors.Is(err, ErrPathOutsideRoot)
+}
+
+// Policy is an immutable list of canonical, absolute storage roots. The
+// roots are syntax-checked by New and filesystem-checked by ValidatePaths so a
+// host can mount a configured directory after process startup without making
+// configuration loading itself perform I/O.
+type Policy struct {
+ roots []string
+}
+
+// New constructs a policy from absolute, canonical paths. It deliberately
+// does not follow or create roots; the existence and symlink checks happen at
+// each define boundary in ValidatePaths.
+func New(roots []string) (Policy, error) {
+ if len(roots) == 0 {
+ return Policy{}, nil
+ }
+ result := make([]string, 0, len(roots))
+ seen := make(map[string]struct{}, len(roots))
+ for _, raw := range roots {
+ root := strings.TrimSpace(raw)
+ if root == "" {
+ return Policy{}, fmt.Errorf("%w: storage root is empty", ErrPolicyViolation)
+ }
+ if err := validateCanonicalAbsolute(root, "storage root"); err != nil {
+ return Policy{}, err
+ }
+ if root == string(filepath.Separator) {
+ return Policy{}, fmt.Errorf("%w: storage root may not be the filesystem root", ErrPolicyViolation)
+ }
+ if _, exists := seen[root]; exists {
+ return Policy{}, fmt.Errorf("%w: duplicate storage root %q", ErrPolicyViolation, root)
+ }
+ seen[root] = struct{}{}
+ result = append(result, root)
+ }
+ return Policy{roots: result}, nil
+}
+
+// Roots returns a defensive copy for diagnostics and configuration tests.
+func (p Policy) Roots() []string {
+ return append([]string(nil), p.roots...)
+}
+
+// ValidatePaths checks every file-backed disk source against the configured
+// roots. No paths means no storage access is required, so firmware-only
+// definitions remain usable even when storage has not been configured yet.
+// A referenced path must already exist as a regular file. VM image creation
+// belongs to a separate, explicitly scoped storage operation; accepting a
+// missing path here would make a later libvirt start depend on an unreviewed
+// path-creation boundary.
+func (p Policy) ValidatePaths(paths []string) error {
+ if len(paths) == 0 {
+ return nil
+ }
+ if len(p.roots) == 0 {
+ return fmt.Errorf("%w: %w", ErrPolicyViolation, ErrNotConfigured)
+ }
+
+ rootRealpaths := make([]string, 0, len(p.roots))
+ for _, root := range p.roots {
+ realRoot, err := verifyRoot(root)
+ if err != nil {
+ return err
+ }
+ rootRealpaths = append(rootRealpaths, realRoot)
+ }
+ for _, rawPath := range paths {
+ path := strings.TrimSpace(rawPath)
+ if path == "" {
+ return fmt.Errorf("%w: empty disk path", ErrPolicyViolation)
+ }
+ if err := validateCanonicalAbsolute(path, "disk path"); err != nil {
+ return err
+ }
+ info, err := os.Lstat(path)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("%w: %q", ErrPathUnavailable, path)
+ }
+ return fmt.Errorf("%w: inspect %q: %v", ErrPathUnavailable, path, err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("%w: %q", ErrPathSymlink, path)
+ }
+ if !info.Mode().IsRegular() {
+ return fmt.Errorf("%w: %q is not a regular file", ErrPathUnavailable, path)
+ }
+ if info.Mode().Perm()&0o022 != 0 || info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 {
+ return fmt.Errorf("%w: %q is writable by group/other or has special mode bits", ErrPathUnavailable, path)
+ }
+ realPath, err := filepath.EvalSymlinks(path)
+ if err != nil {
+ return fmt.Errorf("%w: resolve %q: %v", ErrPathUnavailable, path, err)
+ }
+ if realPath != path {
+ return fmt.Errorf("%w: %q resolves to %q", ErrPathSymlink, path, realPath)
+ }
+
+ inside := false
+ for _, realRoot := range rootRealpaths {
+ if pathWithinRoot(realRoot, realPath) {
+ inside = true
+ break
+ }
+ }
+ if !inside {
+ return fmt.Errorf("%w: %q", ErrPathOutsideRoot, path)
+ }
+ }
+ return nil
+}
+
+// validateCanonicalAbsolute rejects paths that filepath.Clean would silently
+// reinterpret. This keeps the path presented in XML identical to the path
+// checked by the policy and makes traversal attempts auditable.
+func validateCanonicalAbsolute(value, label string) error {
+ if !filepath.IsAbs(value) || filepath.Clean(value) != value || strings.ContainsAny(value, "\x00\r\n\t\\") {
+ return fmt.Errorf("%w: %s must be a canonical absolute path", ErrPolicyViolation, label)
+ }
+ for _, component := range strings.Split(value, string(filepath.Separator)) {
+ if component == "." || component == ".." {
+ return fmt.Errorf("%w: %s contains a traversal component", ErrPolicyViolation, label)
+ }
+ }
+ return nil
+}
+
+func verifyRoot(root string) (string, error) {
+ info, err := os.Lstat(root)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return "", fmt.Errorf("%w: %q", ErrRootUnavailable, root)
+ }
+ return "", fmt.Errorf("%w: inspect %q: %v", ErrRootUnavailable, root, err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return "", fmt.Errorf("%w: root %q", ErrPathSymlink, root)
+ }
+ if !info.IsDir() {
+ return "", fmt.Errorf("%w: root %q is not a directory", ErrRootUnavailable, root)
+ }
+ if info.Mode().Perm()&0o022 != 0 || info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 {
+ return "", fmt.Errorf("%w: root %q is writable by group/other or has special mode bits", ErrRootUnavailable, root)
+ }
+ realRoot, err := filepath.EvalSymlinks(root)
+ if err != nil {
+ return "", fmt.Errorf("%w: resolve root %q: %v", ErrRootUnavailable, root, err)
+ }
+ if realRoot != root {
+ return "", fmt.Errorf("%w: root %q resolves to %q", ErrPathSymlink, root, realRoot)
+ }
+ return realRoot, nil
+}
+
+func pathWithinRoot(root, candidate string) bool {
+ rel, err := filepath.Rel(root, candidate)
+ if err != nil || rel == "." || rel == ".." {
+ return false
+ }
+ parent := ".." + string(filepath.Separator)
+ return !strings.HasPrefix(rel, parent)
+}
diff --git a/agent/internal/storagepolicy/storagepolicy_test.go b/agent/internal/storagepolicy/storagepolicy_test.go
new file mode 100644
index 00000000..f71793d2
--- /dev/null
+++ b/agent/internal/storagepolicy/storagepolicy_test.go
@@ -0,0 +1,194 @@
+package storagepolicy
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func canonicalTempDir(t *testing.T) string {
+ t.Helper()
+ path := t.TempDir()
+ resolved, err := filepath.EvalSymlinks(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return resolved
+}
+
+func TestNewRejectsNonCanonicalOrDuplicateRoots(t *testing.T) {
+ base := canonicalTempDir(t)
+ tests := []struct {
+ name string
+ roots []string
+ }{
+ {name: "relative", roots: []string{"relative/root"}},
+ {name: "traversal", roots: []string{base + string(filepath.Separator) + ".." + string(filepath.Separator) + filepath.Base(base)}},
+ {name: "duplicate", roots: []string{base, base}},
+ {name: "empty entry", roots: []string{base, ""}},
+ {name: "backslash", roots: []string{base + `\\escape`}},
+ {name: "filesystem root", roots: []string{string(filepath.Separator)}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if _, err := New(tt.roots); !errors.Is(err, ErrPolicyViolation) {
+ t.Fatalf("New(%v) error = %v, want ErrPolicyViolation", tt.roots, err)
+ }
+ })
+ }
+}
+
+func TestValidatePathsRequiresConfiguredRoot(t *testing.T) {
+ path := filepath.Join(canonicalTempDir(t), "disk.qcow2")
+ if err := os.WriteFile(path, []byte("image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := (Policy{}).ValidatePaths([]string{path}); !errors.Is(err, ErrNotConfigured) {
+ t.Fatalf("ValidatePaths() error = %v, want ErrNotConfigured", err)
+ }
+}
+
+func TestIsDefinitiveDistinguishesPolicyAndUnavailableRoot(t *testing.T) {
+ if !IsDefinitive(fmt.Errorf("wrapped: %w", ErrNotConfigured)) {
+ t.Fatal("ErrNotConfigured must be a definitive request rejection")
+ }
+ if !IsDefinitive(fmt.Errorf("wrapped: %w", ErrPathOutsideRoot)) {
+ t.Fatal("ErrPathOutsideRoot must be a definitive request rejection")
+ }
+ if IsDefinitive(fmt.Errorf("wrapped: %w", ErrRootUnavailable)) {
+ t.Fatal("ErrRootUnavailable should remain retryable after host provisioning")
+ }
+}
+
+func TestValidatePathsAcceptsExistingRegularFileInsideRoot(t *testing.T) {
+ root := canonicalTempDir(t)
+ path := filepath.Join(root, "vm", "disk.qcow2")
+ if err := os.Mkdir(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte("image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ policy, err := New([]string{root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := policy.ValidatePaths([]string{path}); err != nil {
+ t.Fatalf("ValidatePaths() error = %v", err)
+ }
+}
+
+func TestValidatePathsRejectsOutsideTraversalMissingAndNonRegular(t *testing.T) {
+ root := canonicalTempDir(t)
+ outside := filepath.Join(canonicalTempDir(t), "outside.qcow2")
+ if err := os.WriteFile(outside, []byte("image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ inside := filepath.Join(root, "disk.qcow2")
+ if err := os.WriteFile(inside, []byte("image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ policy, err := New([]string{root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ tests := []struct {
+ name string
+ path string
+ want error
+ }{
+ {name: "outside", path: outside, want: ErrPathOutsideRoot},
+ {name: "traversal", path: root + string(filepath.Separator) + "nested" + string(filepath.Separator) + ".." + string(filepath.Separator) + "disk.qcow2", want: ErrPolicyViolation},
+ {name: "missing", path: filepath.Join(root, "missing.qcow2"), want: ErrPathUnavailable},
+ {name: "directory", path: root, want: ErrPathUnavailable},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if err := policy.ValidatePaths([]string{tt.path}); !errors.Is(err, tt.want) {
+ t.Fatalf("ValidatePaths(%q) error = %v, want %v", tt.path, err, tt.want)
+ }
+ })
+ }
+ if err := policy.ValidatePaths([]string{inside}); err != nil {
+ t.Fatalf("valid path became invalid after negative cases: %v", err)
+ }
+}
+
+func TestValidatePathsRejectsSymlinkRootAndDiskAliases(t *testing.T) {
+ root := canonicalTempDir(t)
+ actual := filepath.Join(root, "actual")
+ if err := os.Mkdir(actual, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ disk := filepath.Join(actual, "disk.qcow2")
+ if err := os.WriteFile(disk, []byte("image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(root, "disk-link.qcow2")
+ if err := os.Symlink(disk, link); err != nil {
+ t.Fatal(err)
+ }
+ policy, err := New([]string{actual})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := policy.ValidatePaths([]string{link}); !errors.Is(err, ErrPathSymlink) {
+ t.Fatalf("symlink disk error = %v, want ErrPathSymlink", err)
+ }
+
+ rootLink := filepath.Join(root, "root-link")
+ if err := os.Symlink(actual, rootLink); err != nil {
+ t.Fatal(err)
+ }
+ linkedPolicy, err := New([]string{rootLink})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := linkedPolicy.ValidatePaths([]string{disk}); !errors.Is(err, ErrPathSymlink) {
+ t.Fatalf("symlink root error = %v, want ErrPathSymlink", err)
+ }
+
+ parentLink := filepath.Join(root, "parent-link")
+ if err := os.Symlink(actual, parentLink); err != nil {
+ t.Fatal(err)
+ }
+ parentLinkedPath := filepath.Join(parentLink, "disk.qcow2")
+ if err := policy.ValidatePaths([]string{parentLinkedPath}); !errors.Is(err, ErrPathSymlink) {
+ t.Fatalf("symlink parent error = %v, want ErrPathSymlink", err)
+ }
+}
+
+func TestValidatePathsAllowsNoPathWithoutFilesystemRoot(t *testing.T) {
+ if err := (Policy{}).ValidatePaths(nil); err != nil {
+ t.Fatalf("ValidatePaths(nil) error = %v", err)
+ }
+}
+
+func TestValidatePathsRejectsGroupWritableRootAndDisk(t *testing.T) {
+ root := canonicalTempDir(t)
+ disk := filepath.Join(root, "disk.qcow2")
+ if err := os.WriteFile(disk, []byte("image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ policy, err := New([]string{root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(root, 0o770); err != nil {
+ t.Fatal(err)
+ }
+ if err := policy.ValidatePaths([]string{disk}); !errors.Is(err, ErrRootUnavailable) {
+ t.Fatalf("group-writable root error = %v, want ErrRootUnavailable", err)
+ }
+ if err := os.Chmod(root, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(disk, 0o660); err != nil {
+ t.Fatal(err)
+ }
+ if err := policy.ValidatePaths([]string{disk}); !errors.Is(err, ErrPathUnavailable) {
+ t.Fatalf("group-writable disk error = %v, want ErrPathUnavailable", err)
+ }
+}
diff --git a/deploy/virt-cloud-agent.env.example b/deploy/virt-cloud-agent.env.example
index c1457e2f..34231b4c 100644
--- a/deploy/virt-cloud-agent.env.example
+++ b/deploy/virt-cloud-agent.env.example
@@ -14,6 +14,11 @@ VIRT_CLOUD_AGENT_JOURNAL=/var/lib/virt-cloud-agent/operations.json
VIRT_CLOUD_AGENT_ARTIFACT_ROOT=/var/lib/virt-cloud-agent/artifacts
VIRT_CLOUD_AGENT_BACKEND=virsh
VIRT_CLOUD_AGENT_LIBVIRT_URI=qemu:///system
+# Optional explicit allowlist for existing file-backed VM images. Empty means
+# fail-closed for ; it is never an allow-all fallback.
+# Use canonical absolute paths only, comma-separated, and provision each root
+# as a real root-owned directory before enabling domain_define.
+# VIRT_CLOUD_AGENT_STORAGE_ROOTS=/var/lib/libvirt/images/virt-cloud
# File paths only. Provision the actual files out of band with root-only
# ownership; the HMAC key specifically must be a regular 0400/0600 file with
diff --git a/docs/GO_AGENT_API_V1.md b/docs/GO_AGENT_API_V1.md
index 3294969e..e5c66e7d 100644
--- a/docs/GO_AGENT_API_V1.md
+++ b/docs/GO_AGENT_API_V1.md
@@ -18,8 +18,9 @@
PHP `CloudSecrets::key('engine_hmac_key')` 返回解码后的 raw bytes。`CloudAgentClient` 只接受
该 raw key,不能把 44 字符的 base64 文本直接拿来做 HMAC。
- `GET /v1/health` 是 liveness;配置 mode/owner 宽松时仍返回 200,但
- `readiness=degraded`,所有写操作返回 503。身份、证书、journal 不可用时
- 不得以匿名或明文方式放行写操作。
+ `readiness=degraded`。除只读 `domain_preflight` 外,写操作在宿主 readiness
+ 降级时返回 503;preflight 仍必须通过认证传输、Agent 身份和 durable journal
+ gate,不能借此绕过 TLS/HMAC 或匿名放行。
## 请求信封
@@ -72,6 +73,15 @@ readback、清理清单和 commit boundary 完成前,Agent 会返回“未实
误报为完全相同。面板若要求精确 desired XML 比对,应等待后续 XML intent digest
契约完成。
+`domain_define` 对 `` 还会在 host-bound
+阶段执行存储路径 allowlist:每个路径必须是现有 regular file、不能是 symlink 或
+路径别名,并且必须位于 Agent 配置的 `VIRT_CLOUD_AGENT_STORAGE_ROOTS` 之一。
+空 allowlist 不表示允许任意路径,而是对 file-backed 磁盘 fail-closed;存储根的
+创建、owner 和挂载生命周期由宿主部署负责。该检查不能替代后续的全祖先 owner/TOCTOU
+验收,所以在对应门槛完成前不要把 domain define 当作生产存储编排。定义前可证明的
+路径策略拒绝会记录为 definitive failure;定义后读回发现路径漂移仍保留操作证据,
+不会把不受控 XML 报告为成功。
+
每个 destructive operation 都必须定义 commit boundary、清理清单和
readback 证据;未知结果只能通过该 operation 类型的只读 reconcile 核对。
@@ -91,13 +101,16 @@ payload;未知字段(包括 XML、磁盘、卷、网卡、网络配置和 lo
}
```
-预检执行阶段只读取宿主 capability(HTTP 写入前的通用 readiness probe 仍会按运行时策略执行),不调用 define/power,也不分配磁盘或修改
-网络。成功结果包含宿主能力摘要、规范化的 pre-host XML、`xml_hash` 和
+预检执行阶段只读取宿主 capability,不先依赖通用 host readiness probe;这使得
+宿主 probe 过期或失败时仍能取得新的能力事实。它不调用 define/power,也不分配
+磁盘或修改网络。成功结果包含宿主能力摘要、规范化的 pre-host XML、`xml_hash` 和
`loader_pending=true`;loader 的绝对路径必须在后续 host-bound define 阶段从
新鲜 `domcapabilities` 选择,预检不会猜测或接受调用方路径。失败使用稳定码:
`domain_preflight_invalid_uuid`、`domain_preflight_*_rejected`、
`domain_preflight_host_policy_rejected`、`domain_preflight_host_unavailable` 或
-`domain_preflight_canceled`。预检通过不等于 VM 已创建。
+`domain_preflight_canceled`。host unavailable 会以 `uncertain` 写入 operation
+journal,并可在 readiness 仍降级时通过同一 operation ID 的 reconcile 再次只读
+核对;host policy rejection 是 definitive `failed`。预检通过不等于 VM 已创建。
## 固件与启动脚本不变量
@@ -131,3 +144,9 @@ SHA-256。写入在同级临时目录完成并 fsync 后发布;`artifact_id`
artifact ID 与 manifest,不返回宿主机绝对路径;PHP 负责把该 artifact 与新
schema 中的实例/镜像 desired state 关联。旧 seed、旧 operation 或旧数据库
字段不会被自动识别。
+
+能力响应中的 `startup_script`/`startup_script_agent` 和
+`nocloud_seed_artifact` 表示 Agent 已实现 NoCloud seed 与一次性脚本 artifact
+发布;`startup_script_host`(以及 `cloud_init`)仍是宿主或来宾镜像事实,不能
+仅凭 Agent 能发布 seed 就推断镜像一定安装了 cloud-init。`seed_prepare` 成功只
+证明 immutable artifact 已发布,不证明来宾已经执行脚本。
diff --git a/docs/GO_AGENT_DEPLOYMENT.md b/docs/GO_AGENT_DEPLOYMENT.md
index bbd04581..06780b0a 100644
--- a/docs/GO_AGENT_DEPLOYMENT.md
+++ b/docs/GO_AGENT_DEPLOYMENT.md
@@ -11,8 +11,9 @@
- Agent 默认只监听 `127.0.0.1:8787`。远程面板必须把监听地址改成宿主机管理
地址,并保留双向 TLS 和签名请求校验;不要用 `0.0.0.0` 代替入站访问控制。
- `GET /v1/health` 是 liveness。配置文件、目录 mode/owner、journal、身份或
- TLS/HMAC 文件不可用时,进程仍应尽量启动并返回 `readiness=degraded`;所有
- 需要持久化或改动宿主机的请求必须拒绝(通常为 `503`)。这不是删除 OS 安全
+ TLS/HMAC 文件不可用时,进程仍应尽量启动并返回 `readiness=degraded`;除认证后
+ 只读的 `domain_preflight` 外,所有需要持久化或改动宿主机的请求必须拒绝(通常为
+ `503`)。这不是删除 OS 安全
边界:密钥仍由 root-only 文件或受控 secret provider 管理,journal 仍拒绝
symlink,远程写请求仍必须 mTLS/签名。
- systemd unit 不执行权限预检,避免“权限告警导致 liveness 消失”。它只允许
@@ -26,6 +27,11 @@
但仍拒绝 symlink 和非目录。
- Go Agent 是绿地系统:新 schema 与新 operation UUID/idempotency 规则独立于
旧数据库;不能把旧 job id 或旧加密字段直接塞进 journal。
+- `` 的每个 `source file` 必须落在
+ `VIRT_CLOUD_AGENT_STORAGE_ROOTS` 的显式逗号分隔 allowlist 中。根目录必须由
+ root 预先创建为真实目录;Agent 不创建或跟随 symlink,也不把空配置解释成
+ “允许所有路径”。未配置 storage root 时,包含 file-backed 磁盘的 define 会
+ fail-closed,避免面板把任意宿主路径交给 libvirt。
## 文件模板
@@ -69,6 +75,22 @@ install -o root -g root -m 0640 \
```
编辑 `agent.env` 时只填入通过受控证书/secret 流程取得的路径和 Agent ID。
+如果要启用已有 file-backed 镜像的 define,另行准备经过审核的根目录,例如:
+
+```bash
+install -d -o root -g root -m 0700 /var/lib/libvirt/images/virt-cloud
+```
+
+并在 `agent.env` 中设置:
+
+```ini
+VIRT_CLOUD_AGENT_STORAGE_ROOTS=/var/lib/libvirt/images/virt-cloud
+```
+
+多个根目录用逗号分隔;每个路径必须是规范绝对路径,不能包含 `..`、反斜杠或
+symlink。Agent 每次 define 前都会重新检查根、文件和 realpath;目录替换或路径
+竞态会使 operation 保持失败/不确定,而不会扩大访问范围;读回 XML 时会再次执行
+同一 allowlist 检查,防止宿主外部改写定义后被误报为 Agent 成功。
`request.hmac` 文件必须写入 canonical standard base64 的 32 个随机 raw bytes
(44 个 ASCII 字符,可带一个末尾换行),且必须是 owner 可读、无 group/other
权限位的 regular file(`0400` 或 `0600`,不能是 symlink);Go Agent 启动时严格
@@ -107,7 +129,9 @@ curl --fail-with-body --silent --show-error \
API 返回 `401/503`;不能因为回退到明文而执行写操作。
3. **能力探测**:`GET /v1/capabilities` 或 `POST /v1/agent/test` 只能读取
libvirt capabilities。核对 x86_64、EFI、Q35、普通(非 Secure Boot)OVMF;
- 不要求、不接受 `secure=yes` loader。
+ 不要求、不接受 `secure=yes` loader。`startup_script_agent=true` 只表示
+ Agent 的 NoCloud artifact writer 已就绪;还需在代表性云镜像内回读一次性
+ marker,不能把它当作 guest cloud-init 已安装的证明。
4. **operation 持久化**:使用全新的 UUID + idempotency key 发起无破坏性的
`capability_probe`,确认重复请求返回同一记录;检查 journal 原子更新和
`0600` 权限。不要用旧 Python job id 试探。
@@ -143,8 +167,8 @@ VIRT_CLOUD_AGENT_BACKEND=virsh \
service。当前模板没有实现 artifact 上传、完整 VM 生命周期、专用 service
account、自动证书注册,也不宣称生产就绪。
-启用 `domain_define` 前还必须补齐两项宿主机安全门槛:为 `` 建立受控的 storage-root allowlist(不能把面板传入的任意绝对路径
-交给 libvirt),并让 journal、artifact root、TLS/HMAC 文件及其所有祖先目录执行
-symlink、owner 和权限校验。当前代码只在最终文件/目录和固定 XML staging 目录上做
-部分检查;在这些门槛完成前,`domain_define` 只能用于隔离测试,不能视为生产可用。
+启用 `domain_define` 前仍需完成 journal、artifact root、TLS/HMAC 文件及其所有
+祖先目录的 symlink、owner、权限和 TOCTOU 校验。当前代码已对 file-backed 磁盘做
+显式 root/realpath/regular-file gate,并对固定 XML staging 目录做部分检查;祖先
+owner 与校验到 `virsh define` 之间的竞态仍是生产门槛。在这些门槛完成前,
+`domain_define` 只能用于隔离测试,不能视为生产可用。
diff --git a/docs/GO_AGENT_MIGRATION.md b/docs/GO_AGENT_MIGRATION.md
index 813b620a..05950ac2 100644
--- a/docs/GO_AGENT_MIGRATION.md
+++ b/docs/GO_AGENT_MIGRATION.md
@@ -48,7 +48,7 @@ HMAC。
- 每个写请求携带 `request_id/operation_id`、body digest、时间戳、nonce 和注册的
`agent_id`;`agent_id` 参与 HMAC canonical 文本并必须等于当前宿主身份。重复请求返回
同一 durable operation,不重放不确定的破坏性动作。
-- 配置文件、目录 mode 或 owner 检查不再阻止进程启动;启动时记录 warning 并将 readiness 标为 `degraded`。缺少监听地址、证书、Agent 身份或操作日志等必需运行时能力时,进程仍可提供健康/诊断接口,但拒绝写操作。
+- 配置文件、目录 mode 或 owner 检查不再阻止进程启动;启动时记录 warning 并将 readiness 标为 `degraded`。缺少监听地址、证书、Agent 身份或操作日志等必需运行时能力时,进程仍可提供健康/诊断接口;除认证后只读的 `domain_preflight` 外,写操作仍拒绝。`domain_preflight` 也必须通过 TLS/HMAC、Agent 身份和 durable journal gate。
- 这不等于删除 OS 安全边界:mTLS 私钥、操作日志、libvirt socket 和运行目录仍必须防 symlink、路径穿越和非授权替换。
- PHP `web/bootstrap.php` 只选择并加载面板配置,不执行配置 mode/owner 预检,也不读取
Python `engine.json`;因此面板 liveness 不依赖旧 Engine 配置文件的权限。操作系统本身
@@ -87,6 +87,10 @@ HMAC。
5. 103 宿主机只做只读能力、域 XML、存储和 Agent API 验证;任何 bridge、地址、路由、nftables、firewalld、WireGuard 或网络 manager 写操作均禁止,除非另行明确授权。
6. 所有 PHP/Agent/Go 测试、`go test -race ./...`、静态安全扫描和真实宿主机验收通过后,才在独立提交中删除 Python Engine、SSH 配置和旧 schema 迁移路径。
+当前 PHP shadow 仅实现 registry health 的显式注入服务,见
+[`GO_AGENT_PHP_SHADOW.md`](GO_AGENT_PHP_SHADOW.md);它尚未接入旧管理员路由,
+不会替换 Python readiness,也不能作为删除 Python/SSH 的证据。
+
## 回滚边界
`go-agent` 分支不向 `dev` 推送。每个切换阶段独立提交,保留 Python fallback 和旧服务单元直到下一阶段验收完成;任何未知 destructive result 以 operation id 重新核对,不自动重放。
diff --git a/docs/GO_AGENT_OPERATION_MATRIX.md b/docs/GO_AGENT_OPERATION_MATRIX.md
index 23dd6e24..8eff50b4 100644
--- a/docs/GO_AGENT_OPERATION_MATRIX.md
+++ b/docs/GO_AGENT_OPERATION_MATRIX.md
@@ -6,11 +6,11 @@
| 能力 | Go Agent 当前状态 | 进入生产前的必要证据 |
| --- | --- | --- |
| 健康、能力、EFI/Q35/非 Secure Boot | 已实现 | 真实宿主 `domcapabilities` 回读、TLS/签名验收 |
-| 域创建预检(`domain_preflight`) | 已实现只读首版 | 严格 UUID/EFI/x86_64/q35/loader policy;只读 capability、规范 XML/hash;不分配存储、不改网络、不 define;loader 路径仍待 host-bound 阶段选择 |
+| 域创建预检(`domain_preflight`) | 已实现只读首版 | 严格 UUID/EFI/x86_64/q35/loader policy;只读 capability、规范 XML/hash;不分配存储、不改网络、不 define;不依赖先前 host readiness probe,但仍要求认证/TLS/HMAC、Agent 身份和 durable journal;loader 路径仍待 host-bound 阶段选择 |
| 域 XML 读取/定义 | 已实现 | UUID、loader、机器类型和 inactive XML 读回一致;未知 define 结果当前只做同 UUID/固件策略的只读核对,不重放 XML |
| 电源 start/shutdown/destroy/reboot/suspend/resume | 已实现首版 | 固定 argv、动作后状态回读;未知结果只读 reconcile,reboot 不以 running 单态确认 |
| NoCloud seed 与云镜像首次启动脚本 | 已实现 artifact 首版 | 目录 manifest/hash、CIDATA 消费链、guest 一次性 marker 验收 |
-| 完整 VM 创建/磁盘/镜像绑定 | 未实现 | 存储池/卷 CAS、磁盘 owner、定义与清理证据 |
+| 完整 VM 创建/磁盘/镜像绑定 | 未实现(define 已有 file-backed 路径 allowlist gate) | 存储池/卷 CAS、磁盘 owner、定义与清理证据;`VIRT_CLOUD_AGENT_STORAGE_ROOTS` 的全祖先 owner/TOCTOU 验收 |
| 重装、救援、退出救援 | 未实现 | pre/post commit boundary、旧卷/新卷清理清单、QGA/电源回读 |
| 快照创建/恢复/删除 | 未实现 | libvirt job 状态、卷身份、冻结/解冻和取消后的恢复证据 |
| 防火墙规则 | 未实现 | nft/firewalld owner marker、revision/digest、只读 live 规则回读 |
diff --git a/docs/GO_AGENT_PHP_SHADOW.md b/docs/GO_AGENT_PHP_SHADOW.md
new file mode 100644
index 00000000..583ff71a
--- /dev/null
+++ b/docs/GO_AGENT_PHP_SHADOW.md
@@ -0,0 +1,35 @@
+# PHP 面板 Go Agent shadow 边界
+
+本阶段只增加一个可显式注入的、只读 `cloud_agents` registry health shadow:
+`CloudAgentRegistryHealthService`。它不替换现有 `CloudRuntimeHealthService` 的
+Python/Engine 检查,不改变任何 VM 写路由,也不把结果当作宿主可写 readiness。
+当前没有把它接入生产路由;在完成 enrollment、secret provider 和真实 mTLS
+握手验收前,默认面板响应保持不变。
+
+## 身份与密钥边界
+
+- `CloudAgent` 只映射新 schema 的明文注册元数据;它不读取 SSH 字段、旧 Engine
+ endpoint、旧密文或 operation 状态。
+- `CloudAgentSecretResolver` 是唯一凭据注入边界。实现必须从 root-only 文件、
+ systemd credential 或受控 secret provider 返回 raw 32-byte HMAC key 及完整
+ mTLS CA/client cert/key 路径;`cloud_agents` 表不能存放这些值。
+- registry `status` 只有 `active`/`degraded` 才允许发起 health 请求;`enrolling`、
+ `disabled`、`revoked` 不联网。未知状态、重复 `host_id`/`agent_id` 和 resolver
+ 缺失都返回 `unknown`/`disabled`,不做隐式回退。
+
+## Endpoint/SSRF 边界
+
+`CloudAgentEndpointPolicy` 只接受无凭据、无路径/query、HTTPS endpoint,并要求
+注入 `CloudAgentHostResolver`。解析结果必须全部是 public、非保留 IP;PHP 不使用
+ambient DNS。shadow 会把同一次显式解析结果传给 `CloudAgentClient`,由 Guzzle
+的 `resolve` 选项固定请求目的地址,避免校验后再次走环境 DNS。endpoint 主机名仍
+作为 TLS SNI/Host 身份,因此部署仍需完成证书 SAN、出口策略和真实 mTLS 握手;
+在这些生产证据齐全前,shadow 只能作为诊断信号,不能用于调度、授权或切换旧
+Engine。
+
+## 验收边界
+
+`web/tests/CloudAgentRegistryHealthContractTest.php` 是静态/契约测试,覆盖状态
+allowlist、重复身份、endpoint 和 resolver fail-closed 行为。当前开发环境没有
+PHP CLI/Composer,因此 PHP 语法、Eloquent 查询、真实数据库和 mTLS 握手仍需在
+CI 或部署环境执行;不能把 Go race/vet 结果当作 PHP 或生产宿主验收。
diff --git a/web/app/Models/CloudAgent.php b/web/app/Models/CloudAgent.php
new file mode 100644
index 00000000..7f829ced
--- /dev/null
+++ b/web/app/Models/CloudAgent.php
@@ -0,0 +1,19 @@
+ 'int',
+ 'host_id' => 'int',
+ 'desired_revision' => 'int',
+ 'observed_revision' => 'int',
+ 'last_seen_at' => 'int',
+ 'created_at' => 'int',
+ 'updated_at' => 'int',
+ ];
+}
diff --git a/web/app/Services/Cloud/CloudAgentClient.php b/web/app/Services/Cloud/CloudAgentClient.php
index ffc86adb..1e43f80c 100644
--- a/web/app/Services/Cloud/CloudAgentClient.php
+++ b/web/app/Services/Cloud/CloudAgentClient.php
@@ -31,12 +31,18 @@ final class CloudAgentClient
private float $timeoutSeconds;
+ /** @var list */
+ private array $resolvedAddresses;
+
/** @var array{ca_file:string,cert_file:string,key_file:string} */
private array $tls;
/**
* @param array{ca_file?:string,cert_file?:string,key_file?:string} $tls
- * @param string $hmacKey decoded raw 32-byte key from CloudSecrets::key()
+ * @param string $hmacKey decoded raw 32-byte key from a host-local secret resolver
+ * @param list $resolvedAddresses public IPs returned by an
+ * explicit registry resolver; when present, requests pin DNS via Guzzle's
+ * resolve option and never fall back to ambient resolver results.
*/
public function __construct(
string $endpoint,
@@ -45,6 +51,7 @@ final class CloudAgentClient
array $tls = [],
float $timeoutSeconds = 15.0,
string $agentId = '',
+ array $resolvedAddresses = [],
) {
if ($timeoutSeconds < 1 || $timeoutSeconds > 900) {
throw new \InvalidArgumentException('Agent timeout is outside the supported range');
@@ -64,6 +71,7 @@ final class CloudAgentClient
}
$this->timeoutSeconds = $timeoutSeconds;
$this->tls = self::validateTls($tls);
+ $this->resolvedAddresses = self::validateResolvedAddresses($resolvedAddresses);
$clientOptions = [
'connect_timeout' => 3,
@@ -77,6 +85,10 @@ final class CloudAgentClient
$clientOptions['cert'] = $this->tls['cert_file'];
$clientOptions['ssl_key'] = $this->tls['key_file'];
}
+ $resolve = $this->resolveOption();
+ if ($resolve !== []) {
+ $clientOptions['resolve'] = $resolve;
+ }
$this->client = $client ?? new Client($clientOptions);
}
@@ -339,23 +351,29 @@ final class CloudAgentClient
unset($headers['Content-Type']);
}
+ $requestOptions = [
+ 'headers' => $headers,
+ 'body' => $body,
+ 'timeout' => $this->timeoutSeconds,
+ 'http_errors' => false,
+ 'allow_redirects' => false,
+ 'proxy' => '',
+ // Keep these explicit for injected clients too, so a test can
+ // assert that production requests carry the intended mTLS
+ // material without opening a real socket.
+ 'verify' => $this->tls['ca_file'] !== '' ? $this->tls['ca_file'] : true,
+ ...(($this->tls['cert_file'] !== '' && $this->tls['key_file'] !== '') ? [
+ 'cert' => $this->tls['cert_file'],
+ 'ssl_key' => $this->tls['key_file'],
+ ] : []),
+ ];
+ $resolve = $this->resolveOption();
+ if ($resolve !== []) {
+ $requestOptions['resolve'] = $resolve;
+ }
+
try {
- $response = $this->client->request($method, $this->endpoint . $path, [
- 'headers' => $headers,
- 'body' => $body,
- 'timeout' => $this->timeoutSeconds,
- 'http_errors' => false,
- 'allow_redirects' => false,
- 'proxy' => '',
- // Keep these explicit for injected clients too, so a test can
- // assert that production requests carry the intended mTLS
- // material without opening a real socket.
- 'verify' => $this->tls['ca_file'] !== '' ? $this->tls['ca_file'] : true,
- ...(($this->tls['cert_file'] !== '' && $this->tls['key_file'] !== '') ? [
- 'cert' => $this->tls['cert_file'],
- 'ssl_key' => $this->tls['key_file'],
- ] : []),
- ]);
+ $response = $this->client->request($method, $this->endpoint . $path, $requestOptions);
} catch (\Throwable $exception) {
// A timeout or connection reset does not prove a destructive
// operation failed. Callers must reconcile by operation ID.
@@ -474,6 +492,42 @@ final class CloudAgentClient
return $result;
}
+ /** @param list $addresses */
+ private static function validateResolvedAddresses(array $addresses): array
+ {
+ if ($addresses === []) {
+ return [];
+ }
+ foreach ($addresses as $address) {
+ if (!is_string($address)
+ || filter_var($address, FILTER_VALIDATE_IP,
+ FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
+ throw new CloudError('宿主机 Agent 主机解析到不安全地址', 422);
+ }
+ }
+ $unique = array_values(array_unique($addresses));
+ sort($unique, SORT_STRING);
+ return $unique;
+ }
+
+ /** @return array */
+ private function resolveOption(): array
+ {
+ if ($this->resolvedAddresses === []) {
+ return [];
+ }
+ $parts = parse_url($this->endpoint);
+ if (!is_array($parts) || !is_string($parts['host'] ?? null)) {
+ throw new CloudError('宿主机 Agent 地址无效', 422);
+ }
+ $host = trim($parts['host'], '[]');
+ // Guzzle maps one host to one fixed address. The resolver is expected
+ // to return a deterministic, health-checked public endpoint; choosing
+ // the first unique address prevents a later ambient DNS lookup while
+ // keeping TLS SNI/Host bound to the registered hostname.
+ return [$host => $this->resolvedAddresses[0]];
+ }
+
private static function assertMethod(string $method): void
{
if (preg_match('/^[A-Z]{3,10}$/D', $method) !== 1) {
diff --git a/web/app/Services/Cloud/CloudAgentEndpointPolicy.php b/web/app/Services/Cloud/CloudAgentEndpointPolicy.php
new file mode 100644
index 00000000..f3ae7af4
--- /dev/null
+++ b/web/app/Services/Cloud/CloudAgentEndpointPolicy.php
@@ -0,0 +1,56 @@
+ 65535) {
+ throw new CloudError('宿主机 Agent 端口无效', 422);
+ }
+ return $endpoint;
+ }
+}
diff --git a/web/app/Services/Cloud/CloudAgentHostResolver.php b/web/app/Services/Cloud/CloudAgentHostResolver.php
new file mode 100644
index 00000000..fb0f5d84
--- /dev/null
+++ b/web/app/Services/Cloud/CloudAgentHostResolver.php
@@ -0,0 +1,10 @@
+ */
+ public function resolve(string $hostname): array;
+}
diff --git a/web/app/Services/Cloud/CloudAgentRegistryHealthService.php b/web/app/Services/Cloud/CloudAgentRegistryHealthService.php
new file mode 100644
index 00000000..3bcf9e7c
--- /dev/null
+++ b/web/app/Services/Cloud/CloudAgentRegistryHealthService.php
@@ -0,0 +1,119 @@
+ */
+ private \Closure $registry;
+
+ public function __construct(?callable $registry = null, private readonly ?CloudAgentSecretResolver $secrets = null,
+ private readonly ?CloudAgentHostResolver $hostResolver = null)
+ {
+ $this->registry = \Closure::fromCallable($registry ?? static function (): iterable {
+ try {
+ return CloudAgent::query()->get()->all();
+ } catch (\Throwable) {
+ return [];
+ }
+ });
+ }
+
+ /** @return array{key:string,label:string,status:string,message:string,checked_at:int,agents:list} */
+ public function snapshot(?int $now = null): array
+ {
+ $now ??= time();
+ $rows = [];
+ try {
+ foreach (($this->registry)() as $row) {
+ $rows[] = is_object($row)
+ ? (method_exists($row, 'toArray') ? $row->toArray() : get_object_vars($row))
+ : (is_array($row) ? $row : []);
+ }
+ } catch (\Throwable) {
+ return $this->result('unknown', '注册表读取失败,未执行 Agent 探测。', [], $now);
+ }
+ if ($rows === []) {
+ return $this->result('disabled', '未启用 Go Agent 注册表,未执行 Agent 探测。', [], $now);
+ }
+ $seenHosts = $seenAgents = [];
+ foreach ($rows as $row) {
+ $hostId = (int) ($row['host_id'] ?? 0);
+ $agentId = trim((string) ($row['agent_id'] ?? ''));
+ if ($hostId < 1 || $agentId === '' || isset($seenHosts[$hostId]) || isset($seenAgents[$agentId])) {
+ return $this->result('unknown', 'Agent 注册表身份不唯一,已停止探测。', [], $now);
+ }
+ $seenHosts[$hostId] = true;
+ $seenAgents[$agentId] = true;
+ }
+ $agents = [];
+ foreach ($rows as $row) {
+ $agents[] = $this->probe($row, $now);
+ }
+ $statuses = array_column($agents, 'status');
+ $aggregate = in_array('unknown', $statuses, true) ? 'unknown'
+ : (in_array('degraded', $statuses, true) ? 'degraded'
+ : (in_array('disabled', $statuses, true) ? 'disabled' : 'ok'));
+ return $this->result($aggregate,
+ $aggregate === 'ok' ? '已完成 Agent liveness shadow;不替代引擎检查。' : '部分 Agent 未通过安全探测。',
+ $agents, $now);
+ }
+
+ private function probe(array $row, int $now): array
+ {
+ $agentId = trim((string) ($row['agent_id'] ?? ''));
+ $base = ['host_id' => (int) ($row['host_id'] ?? 0), 'agent_id' => $agentId,
+ 'registry_status' => (string) ($row['status'] ?? 'unknown')];
+ if (!in_array($base['registry_status'], self::REGISTRY_STATUSES, true)) {
+ return $base + ['status' => 'unknown', 'message' => '注册状态不在允许范围内。', 'checked_at' => $now];
+ }
+ if ($base['registry_status'] !== 'active' && $base['registry_status'] !== 'degraded') {
+ $status = $base['registry_status'] === 'disabled' || $base['registry_status'] === 'revoked'
+ ? 'disabled' : 'unknown';
+ return $base + ['status' => $status, 'message' => 'Agent 尚未进入可探测状态,未发起网络请求。', 'checked_at' => $now];
+ }
+ try {
+ $resolvedAddresses = [];
+ $endpoint = CloudAgentEndpointPolicy::validate((string) ($row['endpoint'] ?? ''),
+ $this->hostResolver === null ? null : function (string $host) use (&$resolvedAddresses): array {
+ $resolvedAddresses = $this->hostResolver->resolve($host);
+ return $resolvedAddresses;
+ });
+ $material = $this->secrets?->resolve($agentId);
+ $tlsReady = is_array($material) && is_string($material['hmac_key'] ?? null)
+ && strlen($material['hmac_key']) === 32;
+ foreach (['ca_file', 'cert_file', 'key_file'] as $tlsKey) {
+ $tlsReady = $tlsReady && is_string($material[$tlsKey] ?? null)
+ && trim($material[$tlsKey]) !== '';
+ }
+ if (!$tlsReady) {
+ return $base + ['status' => 'unknown', 'message' => 'Agent TLS/密钥 resolver 未配置,未执行探测。', 'checked_at' => $now];
+ }
+ $client = new CloudAgentClient($endpoint, (string) ($material['hmac_key'] ?? ''), null,
+ array_intersect_key($material, array_flip(['ca_file', 'cert_file', 'key_file'])), 4.0,
+ $agentId, $resolvedAddresses);
+ $health = $client->health();
+ $status = in_array($health['status'] ?? null, self::HEALTH_STATUSES, true) ? $health['status'] : 'unknown';
+ return $base + ['status' => $status, 'message' => $status === 'ok' ? 'Agent liveness 正常。' : 'Agent readiness 需关注。', 'checked_at' => $now];
+ } catch (\Throwable) {
+ return $base + ['status' => 'unknown', 'message' => 'Agent 探测失败,未暴露上游细节。', 'checked_at' => $now];
+ }
+ }
+
+ private function result(string $status, string $message, array $agents, int $now): array
+ {
+ return ['key' => 'cloud_agent_shadow', 'label' => 'Go Agent(shadow)', 'status' => $status,
+ 'message' => $message, 'checked_at' => $now, 'agents' => $agents];
+ }
+}
diff --git a/web/app/Services/Cloud/CloudAgentSecretResolver.php b/web/app/Services/Cloud/CloudAgentSecretResolver.php
new file mode 100644
index 00000000..9d73526f
--- /dev/null
+++ b/web/app/Services/Cloud/CloudAgentSecretResolver.php
@@ -0,0 +1,14 @@
+ []))->snapshot(1700000000);
+$assert($empty['status'] === 'disabled' && $empty['agents'] === [],
+ 'An absent Agent registry must be disabled and must not probe an endpoint.');
+
+$duplicate = new CloudAgentRegistryHealthService(static fn (): array => [
+ ['host_id' => 7, 'agent_id' => 'a-1', 'endpoint' => 'https://agent.example.test'],
+ ['host_id' => 7, 'agent_id' => 'a-2', 'endpoint' => 'https://agent-2.example.test'],
+]);
+$duplicateResult = $duplicate->snapshot(1700000000);
+$assert($duplicateResult['status'] === 'unknown' && $duplicateResult['agents'] === [],
+ 'A host_id may map to exactly one registered Agent.');
+
+foreach (['http://agent.example.test', 'https://127.0.0.1', 'https://localhost',
+ 'https://[::1]', 'https://user:pass@agent.example.test', 'https://agent.example.test/path?q=1'] as $unsafe) {
+ try {
+ CloudAgentEndpointPolicy::validate($unsafe);
+ throw new RuntimeException('Unsafe Agent endpoint accepted: ' . $unsafe);
+ } catch (CloudError $expected) {
+ $assert($expected->httpStatus === 422, 'Unsafe endpoint returned an unexpected status.');
+ }
+}
+
+$resolver = new class implements CloudAgentSecretResolver {
+ public array $requested = [];
+ public function resolve(string $agentId): ?array
+ {
+ $this->requested[] = $agentId;
+ return null;
+ }
+};
+$resolverContract = new class implements CloudAgentHostResolver {
+ public function resolve(string $hostname): array { return ['8.8.8.8']; }
+};
+$noSecret = new CloudAgentRegistryHealthService(static fn (): array => [
+ ['host_id' => 8, 'agent_id' => 'a-8', 'endpoint' => 'https://agent.example.test', 'status' => 'active'],
+], $resolver, $resolverContract);
+$noSecretResult = $noSecret->snapshot(1700000000);
+$assert($noSecretResult['status'] === 'unknown'
+ && $noSecretResult['agents'][0]['status'] === 'unknown'
+ && $resolver->requested === ['a-8'],
+ 'Agent health must remain unknown when host-local secret/TLS resolution is unavailable.');
+
+$unknownStatus = new CloudAgentRegistryHealthService(static fn (): array => [
+ ['host_id' => 9, 'agent_id' => 'a-9', 'endpoint' => 'https://agent.example.test', 'status' => 'mystery'],
+]);
+$unknownStatusResult = $unknownStatus->snapshot(1700000000);
+$assert($unknownStatusResult['agents'][0]['status'] === 'unknown',
+ 'Unknown registry statuses must fail closed.');
+
+$inactive = new CloudAgentRegistryHealthService(static fn (): array => [
+ ['host_id' => 10, 'agent_id' => 'a-10', 'endpoint' => 'https://agent.example.test', 'status' => 'disabled'],
+], $resolver, $resolverContract);
+$inactiveResult = $inactive->snapshot(1700000000);
+$assert($inactiveResult['agents'][0]['status'] === 'disabled' && $resolver->requested === ['a-8'],
+ 'Disabled Agents must not make network requests and must be reported disabled.');
+
+try {
+ CloudAgentEndpointPolicy::validate('https://agent.example.test');
+ throw new RuntimeException('DNS hostname was accepted without an explicit resolver.');
+} catch (CloudError $expected) {
+ $assert($expected->httpStatus === 422, 'Missing endpoint resolver returned an unexpected status.');
+}
+
+$publicResolver = static fn (string $host): array => ['8.8.8.8'];
+$assert(CloudAgentEndpointPolicy::validate('https://8.8.8.8', $publicResolver) === 'https://8.8.8.8',
+ 'A public literal endpoint with an explicit resolver should be accepted.');
+try {
+ CloudAgentEndpointPolicy::validate('https://127.0.0.1', $publicResolver);
+ throw new RuntimeException('A private literal endpoint was accepted despite a public resolver result.');
+} catch (CloudError $expected) {
+ $assert($expected->httpStatus === 422, 'Private literal endpoint returned an unexpected status.');
+}
+try {
+ CloudAgentEndpointPolicy::validate('https://8.8.8.8', static fn (string $host): array => ['10.0.0.8']);
+ throw new RuntimeException('Resolver returned a private address but endpoint was accepted.');
+} catch (CloudError $expected) {
+ $assert($expected->httpStatus === 422, 'Private resolver result returned an unexpected status.');
+}
+
+$source = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentRegistryHealthService.php');
+$assert($source !== false && str_contains($source, 'CloudAgentSecretResolver')
+ && str_contains($source, 'CloudAgentEndpointPolicy::validate')
+ && str_contains($source, 'CloudAgentHostResolver')
+ && str_contains($source, '$resolvedAddresses')
+ && str_contains($source, 'CloudAgentClient')
+ && !str_contains($source, 'CloudEngineClient') && !str_contains($source, 'CloudSecrets')
+ && !str_contains($source, 'ssh'), 'Registry shadow crossed the legacy secret or SSH boundary.');
+
+$clientSource = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentClient.php');
+$assert($clientSource !== false
+ && str_contains($clientSource, "'resolve'")
+ && str_contains($clientSource, 'validateResolvedAddresses')
+ && str_contains($clientSource, 'FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE'),
+ 'Agent transport did not retain the explicit public-address pinning contract.');
+
+echo "Cloud Agent registry health shadow contract checks passed.\n";