package api import ( "bytes" "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "strings" "testing" "g.luoli.live/root/virt/agent/internal/capability" "g.luoli.live/root/virt/agent/internal/config" "g.luoli.live/root/virt/agent/internal/domaincreateplan" "g.luoli.live/root/virt/agent/internal/domainpreflight" "g.luoli.live/root/virt/agent/internal/hypervisor" "g.luoli.live/root/virt/agent/internal/operation" ) func createPlanRequest() domaincreateplan.Request { readonly := true secureBoot := false return domaincreateplan.Request{ Domain: domainpreflight.Request{ UUID: "00000000-0000-4000-8000-000000000951", Firmware: "efi", Architecture: "x86_64", Machine: "q35", OSType: "hvm", Loader: domainpreflight.LoaderPolicy{Type: "pflash", Readonly: &readonly, SecureBoot: &secureBoot}, }, Seed: domaincreateplan.SeedRequest{ ArtifactID: "00000000-0000-4000-8000-000000000952", InstanceID: "instance-951", Hostname: "vm-951", NetworkConfig: `{"version":2,"ethernets":{}}`, StartupScript: "#!/bin/sh\necho panel-secret\n", }, Image: domaincreateplan.ImageRef{ID: "image-951", SHA256: strings.Repeat("c", 64)}, } } func createPlanBody(t *testing.T, operationID, idempotency string, request domaincreateplan.Request) []byte { t.Helper() payload, err := json.Marshal(request) if err != nil { t.Fatal(err) } return []byte(fmt.Sprintf(`{"operation_id":%q,"idempotency_key":%q,"kind":"domain_create_plan","target":%q,"payload":%s}`, operationID, idempotency, request.Domain.UUID, payload)) } func TestDomainCreatePlanIsReadOnlyAndRedactsJournal(t *testing.T) { store := operation.NewMemory() backend := hypervisor.NewFakeBackend(hypervisor.DefaultCapabilitySnapshot()) c := config.Defaults() c.AgentID = "host-create-plan" s, err := New(Options{ Config: c, Store: store, Capabilities: capability.BackendProvider{Backend: backend, AgentID: c.AgentID, ProtocolVersion: c.ProtocolVersion}, Backend: backend, HostBackendReady: true, }) if err != nil { t.Fatal(err) } request := createPlanRequest() id := "00000000-0000-4000-8000-000000000953" body := createPlanBody(t, id, "create-plan-0953", request) first := httptest.NewRecorder() s.Handler().ServeHTTP(first, httptest.NewRequest(http.MethodPost, "/v1/operations", bytes.NewReader(body))) if first.Code != http.StatusOK { t.Fatalf("status=%d body=%s", first.Code, first.Body.String()) } var record operation.Record if err := json.Unmarshal(first.Body.Bytes(), &record); err != nil { t.Fatal(err) } if record.Status != operation.StatusSucceeded || record.CommitBoundary != "domain_create_plan_confirmed" { t.Fatalf("record=%+v", record) } for _, forbidden := range []string{request.Seed.StartupScript, request.Seed.NetworkConfig, "source", "/var/lib", `"normalized_xml"`, "