From 0bdbfa80dee3fdf8a98c4cd1eb071f5ee5515196 Mon Sep 17 00:00:00 2001 From: "augmentcode[bot]" <185243770+augmentcode[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:37:57 +0000 Subject: [PATCH 1/7] feat(platform): add partial read-only project secret planning --- modules/platform/platform.go | 1 + modules/platform/project-copy.md | 73 ++++ modules/platform/project_copy.go | 95 +++++ modules/platform/project_copy_test.go | 117 +++++ modules/platform/projectcopy/inventory.go | 218 ++++++++++ .../platform/projectcopy/inventory_test.go | 399 ++++++++++++++++++ modules/platform/projectcopy/transport.go | 168 ++++++++ modules/platform/projectcopy/types.go | 59 +++ pkg/spec/platform.spec.yaml | 31 ++ 9 files changed, 1161 insertions(+) create mode 100644 modules/platform/project-copy.md create mode 100644 modules/platform/project_copy.go create mode 100644 modules/platform/project_copy_test.go create mode 100644 modules/platform/projectcopy/inventory.go create mode 100644 modules/platform/projectcopy/inventory_test.go create mode 100644 modules/platform/projectcopy/transport.go create mode 100644 modules/platform/projectcopy/types.go diff --git a/modules/platform/platform.go b/modules/platform/platform.go index b538dff2..fef4dd92 100644 --- a/modules/platform/platform.go +++ b/modules/platform/platform.go @@ -9,4 +9,5 @@ const resolvePrincipalIDFnID = "resolve_principal_id" func ModuleInit(reg registry.ModuleRegistrar) { reg.RegisterFlagResolveFn(resolvePrincipalIDFnID, resolvePrincipalID) + reg.RegisterWorkflow("project_copy", projectCopy) } diff --git a/modules/platform/project-copy.md b/modules/platform/project-copy.md new file mode 100644 index 00000000..4e8d3f1c --- /dev/null +++ b/modules/platform/project-copy.md @@ -0,0 +1,73 @@ +# PARTIAL project-copy planning: secrets only + +This release inventories source-project secrets and reports capabilities only. +**It does not create/check a destination, copy anything, or establish readiness.** +Connectors, pipelines and all other project resources are **NOT INVENTORIED**. +Apply, mappings and non-secret selections are unavailable; unsupported selections +are rejected before inventory. The destination must be distinct and explicit. + +```sh +harness migrate project:project --from source_project --to destination_project --org example_org --resources secret --dry-run +harness migrate project:project --from source_project --to destination_project --org example_org --resources secret --json --out new-report.json +``` + +Normal profile/environment authentication and `--org` resolution apply. The +profile's default project is ignored: neither `--from` nor `--to` defaults. +Explicit `--project` and non-project `--level` are rejected. Omit `--dry-run` for +the same read-only behavior; there is no apply implementation. `--apply` and +explicit `--dry-run=false` error before inventory. +No confirmation, `--force`, resource files or checkpoint/resume path exists. + +## Safe reports and exit status + +Text (default), `--format text`, `--format json` and `--json` report the same +PARTIAL scope and completion status. `--raw` cannot reveal raw definitions: only +the safe report ever reaches output. `--out` exclusively creates a **new**, mode +0600 file; existing files and symlink/hardlink aliases are never overwritten. +There is no separate report-file flag. Output errors do not print file contents +or source response text. Shell redirection remains the caller's responsibility. + +Secret entries use report-local ordinals, fixed type/capability labels and fixed +reasons, not names/identifiers, values, manager identifiers, locators, descriptions, +raw definitions or hashes. Definitions are memory-only, never debug logged. + +| Capability | Meaning in this release | +| --- | --- | +| `reference-only` | Known external SecretText Reference configuration; no value export. Manager/destination access and mapping remain unverified. | +| `mapping-required` | SecretText Inline values are non-exportable; secure provisioning or verified shared mappings are needed later. | +| `blocked` | Unsupported/missing/unknown fields or types; no copy support is claimed. | +| `copyable` | Reserved capability vocabulary; **never assigned** without proven dependency/access/apply contracts. | + +Only the documented minimal SecretText schema is classified as reference-only or +mapping-required. Additional metadata, other secret types, unknown/control fields +and unproven variants block; no writable definition is produced or retained for +apply. A complete reference inventory can exit zero, including an empty inventory; +this means only read-only inventory completion, **not copy readiness**. Required +mappings, blocked variants, denied reads or incomplete inventories exit nonzero. +A failed inventory report has `inventory_complete: false`; earlier entries are +only partial observations. A complete inventory may still contain blocked items. + +## Public contracts and offline validation + +- [List API](https://apidocs.harness.io/secrets/listsecretsv4): read-only `POST /ng/api/v2/secrets/list/secrets`, `filterType: Secret`, scoped account/org/project, zero-based `pageIndex`, maximum `pageSize: 100`, response `totalItems`, `totalPages`, `pageItemCount`, `pageSize`, `content[].secret` and `updatedAt`. +- [Detail API](https://apidocs.harness.io/secrets/getsecretv2): scoped `GET /ng/api/v2/secrets/{identifier}`, `data.secret` and `updatedAt`. +- [Harness SecretText SDK schema](https://github.com/harness/harness-go-sdk/blob/2d590feb560bb8609bef3f96e73601602b13574b/harness/nextgen/model_secret_text_spec.go): `type`, `secretManagerIdentifier`, `valueType`, optional `value` and `additionalMetadata`. Only the minimal variant without additional metadata is supported here. + +Inventory validates all pagination metadata, counts, unique identities, source +scope and list/detail type/revision agreement. It re-lists after details and +rejects observed churn. This is not an atomic server snapshot or a guarantee +against a change after the final read. Missing/restricted/inconsistent results +are never interpreted as an empty inventory. Inventories over 100,000 items or +responses over 4 MiB fail closed rather than being silently truncated. + +The module's authenticated raw transport allows only the documented list and +detail reads, disables redirects, discards response/error bodies from diagnostics, +and makes at most three attempts for network/429/502/503/504 failures. Bounded, +cancellable delays honor Retry-After; waits above ten seconds fail for a later +manual retry, not an early request. Other status/schema errors are not retried. + +Tests use synthetic public-contract fixtures and fake transports for pagination, +scope/access failures, malformed/truncated responses, churn, capabilities, +retries, no mutation paths, sensitive-marker absence and protected report files. +**No live Harness reads, profiles or resources were used.** Mocks validate local +behavior, not live API conformance, permission completeness or operational readiness. diff --git a/modules/platform/project_copy.go b/modules/platform/project_copy.go new file mode 100644 index 00000000..ce9c1524 --- /dev/null +++ b/modules/platform/project_copy.go @@ -0,0 +1,95 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package platform + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + + "github.com/harness/cli/v3/modules/platform/projectcopy" + "github.com/harness/cli/v3/pkg/cmdctx" +) + +func projectCopy(ctx *cmdctx.Ctx) error { + scope, err := projectCopyScope(ctx) + if err != nil { + return err + } + report, inventoryErr := projectcopy.Inventory(ctx.Context, projectcopy.NewTransport(ctx.Auth), scope) + if err := writeProjectCopyReport(ctx, report); err != nil { + return err + } + return inventoryErr +} + +func projectCopyScope(ctx *cmdctx.Ctx) (projectcopy.Scope, error) { + if cmdctx.GetBool(ctx.FlagValues, "apply") || (ctx.ProvidedFlags["dry-run"] && !cmdctx.GetBool(ctx.FlagValues, "dry-run")) { + return projectcopy.Scope{}, errors.New("apply unavailable: this is PARTIAL read-only secret planning") + } + if cmdctx.GetString(ctx.FlagValues, "resources") != "secret" { + return projectcopy.Scope{}, errors.New("select exactly --resources secret; other resources and apply are unavailable") + } + if ctx.Auth == nil { + return projectcopy.Scope{}, errors.New("resolved authentication required") + } + if f := ctx.FormatFlags.Format; f != "" && f != "text" && f != "json" { + return projectcopy.Scope{}, errors.New("project planning supports --format text or json") + } + if ctx.ProvidedFlags["project"] || (ctx.Level != "" && ctx.Level != "project") { + return projectcopy.Scope{}, errors.New("use explicit --from/--to projects, not --project or a different --level") + } + if len(ctx.Args) > 0 || ctx.Id != "" { + return projectcopy.Scope{}, errors.New("project planning accepts flags only") + } + scope := projectcopy.Scope{Account: ctx.Auth.AccountID, Org: ctx.Auth.OrgID, Source: ctx.MigrateFrom, Destination: ctx.MigrateTo} + return scope, scope.Validate() +} + +func writeProjectCopyReport(ctx *cmdctx.Ctx, report projectcopy.Report) error { + format := ctx.FormatFlags.Format + if format == "" { + format = "text" + } + if format != "text" && format != "json" { + return errors.New("project planning supports --format text or json") + } + var w io.Writer = os.Stdout + if ctx.FormatFlags.OutFile != "" { + // Exclusive creation also rejects symlinks/hardlinks to profiles or other inputs. + f, err := os.OpenFile(ctx.FormatFlags.OutFile, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + return errors.New("cannot create report: --out must name a new file") + } + writeErr := renderProjectCopyReport(f, format, report) + closeErr := f.Close() + if writeErr != nil || closeErr != nil { + return errors.New("cannot write project planning report") + } + return nil + } + if err := renderProjectCopyReport(w, format, report); err != nil { + return errors.New("cannot write project planning report") + } + return nil +} + +func renderProjectCopyReport(w io.Writer, format string, r projectcopy.Report) error { + if format == "json" { + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(r) + } + if _, err := fmt.Fprintf(w, "PARTIAL — read-only secret planning; apply unavailable\nAccount: %s; org: %s; source: %s; destination: %s\nSecret inventory complete: %t\nReadiness: %s\nNOT INVENTORIED: connectors, pipelines and all other project resources\n", r.Scope.Account, r.Scope.Org, r.Scope.Source, r.Scope.Destination, r.InventoryComplete, r.Readiness); err != nil { + return err + } + for _, item := range r.Secrets { + if _, err := fmt.Fprintf(w, "Secret #%d: %s — %s (%s)\n", item.Number, item.Type, item.Capability, item.Reason); err != nil { + return err + } + } + return nil +} diff --git a/modules/platform/project_copy_test.go b/modules/platform/project_copy_test.go new file mode 100644 index 00000000..aeaeb3ac --- /dev/null +++ b/modules/platform/project_copy_test.go @@ -0,0 +1,117 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package platform + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/harness/cli/v3/modules/platform/projectcopy" + "github.com/harness/cli/v3/pkg/auth" + "github.com/harness/cli/v3/pkg/cmdctx" +) + +func copyContext() *cmdctx.Ctx { + return &cmdctx.Ctx{Auth: &auth.ResolvedAuth{AccountID: "fixture_account", OrgID: "fixture_org", ProjectID: "ignored_profile_project"}, MigrateFrom: "source", MigrateTo: "destination", FlagValues: map[string]any{"resources": "secret"}, ProvidedFlags: map[string]bool{}} +} + +func TestProjectCopyRejectsUnavailableWorkBeforeTransport(t *testing.T) { + for _, tc := range []struct { + name string + modify func(*cmdctx.Ctx) + }{ + {"apply", func(c *cmdctx.Ctx) { c.SetFlag("apply", true) }}, + {"dry-run disabled", func(c *cmdctx.Ctx) { c.SetFlag("dry-run", false) }}, + {"unsupported format", func(c *cmdctx.Ctx) { c.FormatFlags.Format = "yaml" }}, + {"mixed resources", func(c *cmdctx.Ctx) { c.SetFlag("resources", "secret,pipeline") }}, + {"no selection", func(c *cmdctx.Ctx) { c.SetFlag("resources", "") }}, + {"full", func(c *cmdctx.Ctx) { c.SetFlag("resources", "all") }}, + {"identity", func(c *cmdctx.Ctx) { c.MigrateTo = c.MigrateFrom }}, + {"source omitted", func(c *cmdctx.Ctx) { c.MigrateFrom = "" }}, + {"destination omitted", func(c *cmdctx.Ctx) { c.MigrateTo = "" }}, + {"project override", func(c *cmdctx.Ctx) { c.SetFlag("project", "other") }}, + {"org level", func(c *cmdctx.Ctx) { c.Level = "org" }}, + {"positional", func(c *cmdctx.Ctx) { c.Id = "unexpected" }}, + {"malformed scope", func(c *cmdctx.Ctx) { c.MigrateFrom = "source/other" }}, + } { + t.Run(tc.name, func(t *testing.T) { + c := copyContext() + tc.modify(c) + // A nil context and invalid API URL would panic/fail if validation reached HTTP. + if err := projectCopy(c); err == nil { + t.Fatal("unsupported work accepted") + } + }) + } + c := copyContext() + s, err := projectCopyScope(c) + if err != nil || s.Source != "source" || s.Destination != "destination" { + t.Fatal("profile project replaced explicit locations") + } +} + +func TestProjectCopyReportsAndProtectedFiles(t *testing.T) { + c := copyContext() + scope, _ := projectCopyScope(c) + r := projectcopy.NewReport(scope) + r.Secrets = []projectcopy.Item{{Number: 1, Type: "SecretText", Capability: projectcopy.ReferenceOnly, Reason: "external reference configuration only"}} + for _, format := range []string{"text", "json"} { + t.Run(format, func(t *testing.T) { + var buf bytes.Buffer + if err := renderProjectCopyReport(&buf, format, r); err != nil { + t.Fatal(err) + } + if !strings.Contains(buf.String(), "PARTIAL") || !strings.Contains(buf.String(), "destination") || strings.Contains(buf.String(), "ignored_profile_project") { + t.Fatal("incorrect report scope/coverage") + } + c.FormatFlags = cmdctx.FormatFlags{Format: format, OutFile: filepath.Join(t.TempDir(), "report")} + if err := writeProjectCopyReport(c, r); err != nil { + t.Fatal(err) + } + info, _ := os.Stat(c.FormatFlags.OutFile) + if info.Mode().Perm() != 0600 { + t.Fatal("report permissions") + } + before, _ := os.ReadFile(c.FormatFlags.OutFile) + if err := writeProjectCopyReport(c, r); err == nil { + t.Fatal("existing report overwritten") + } + after, _ := os.ReadFile(c.FormatFlags.OutFile) + if !bytes.Equal(before, after) { + t.Fatal("existing data changed") + } + }) + } + dir := t.TempDir() + protected := filepath.Join(dir, "profiles.yaml") + os.WriteFile(protected, []byte("SYNTHETIC_PROTECTED_INPUT"), 0600) + for _, kind := range []string{"direct", "symlink", "hardlink"} { + t.Run(kind, func(t *testing.T) { + out := protected + if kind != "direct" { + out = filepath.Join(dir, kind) + var err error + if kind == "symlink" { + err = os.Symlink(protected, out) + } else { + err = os.Link(protected, out) + } + if err != nil { + t.Fatal(err) + } + } + c.FormatFlags = cmdctx.FormatFlags{OutFile: out} + if err := writeProjectCopyReport(c, r); err == nil { + t.Fatal("protected alias accepted") + } + data, _ := os.ReadFile(protected) + if string(data) != "SYNTHETIC_PROTECTED_INPUT" { + t.Fatal("input overwritten") + } + }) + } +} diff --git a/modules/platform/projectcopy/inventory.go b/modules/platform/projectcopy/inventory.go new file mode 100644 index 00000000..45c72ff9 --- /dev/null +++ b/modules/platform/projectcopy/inventory.go @@ -0,0 +1,218 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package projectcopy + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "sort" + "strings" +) + +type secret struct { + Identifier string `json:"identifier"` + Name string `json:"name"` + Org string `json:"orgIdentifier"` + Project string `json:"projectIdentifier"` + Type string `json:"type"` + Spec map[string]json.RawMessage `json:"spec"` + Unproven bool `json:"-"` +} + +func (s *secret) UnmarshalJSON(data []byte) error { + type plain secret + if err := json.Unmarshal(data, (*plain)(s)); err != nil { + return err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + for key := range fields { + switch key { + case "identifier", "name", "orgIdentifier", "projectIdentifier", "type", "spec", "description", "tags": + default: + s.Unproven = true + } + } + return nil +} + +type record struct { + Secret *secret `json:"secret"` + Updated *int64 `json:"updatedAt"` + Draft bool `json:"draft"` +} + +type pageData struct { + TotalPages *int `json:"totalPages"` + TotalItems *int `json:"totalItems"` + PageItemCount *int `json:"pageItemCount"` + PageSize *int `json:"pageSize"` + Content []record `json:"content"` +} + +type readFn func(context.Context, Scope, string, int, any) error + +func Inventory(ctx context.Context, t *Transport, s Scope) (Report, error) { + return inventory(ctx, t.read, s) +} + +func inventory(ctx context.Context, read readFn, s Scope) (Report, error) { + report := NewReport(s) + if err := s.Validate(); err != nil { + return report, err + } + records, err := list(ctx, read, s) + if err != nil { + return report, err + } + ids := make([]string, 0, len(records)) + for id := range records { + ids = append(ids, id) + } + sort.Strings(ids) + blocked := false + for _, id := range ids { + var detail struct { + Status string `json:"status"` + Data *record `json:"data"` + } + if err := read(ctx, s, id, 0, &detail); err != nil { + return report, err + } + before := records[id] + if detail.Status != "SUCCESS" || detail.Data == nil || !validRecord(*detail.Data, s) || detail.Data.Secret.Identifier != id || detail.Data.Secret.Type != before.Secret.Type || *detail.Data.Updated != *before.Updated { + return report, errors.New("secret inventory detail missing, changed or outside requested scope") + } + item := classify(detail.Data.Secret) + item.Number = len(report.Secrets) + 1 + report.Secrets = append(report.Secrets, item) + blocked = blocked || item.Capability == Blocked || item.Capability == MappingRequired + } + // Re-list to detect page churn during detail reads; this is not a server snapshot. + after, err := list(ctx, read, s) + if err != nil { + return report, err + } + if !reflect.DeepEqual(records, after) { + return report, errors.New("secret inventory changed during planning; retry") + } + report.InventoryComplete = true + if blocked { + return report, errors.New("secret planning blocked: unsupported definitions or secure mappings required; apply unavailable") + } + return report, nil +} + +func list(ctx context.Context, read readFn, s Scope) (map[string]record, error) { + records := map[string]record{} + total, pages := -1, -1 + for index := 0; ; index++ { + var response struct { + Status string `json:"status"` + Data *pageData `json:"data"` + } + if err := read(ctx, s, "", index, &response); err != nil { + return nil, err + } + p := response.Data + if response.Status != "SUCCESS" || p == nil || p.TotalItems == nil || p.TotalPages == nil || p.PageItemCount == nil || p.PageSize == nil || p.Content == nil { + return nil, errors.New("secret inventory pagination metadata missing") + } + if *p.TotalItems < 0 || *p.TotalItems > 100000 || *p.TotalPages < 0 || *p.PageSize != 100 || *p.PageItemCount != len(p.Content) || len(p.Content) > 100 { + return nil, errors.New("secret inventory pagination invalid") + } + expectedPages := (*p.TotalItems + 99) / 100 + if *p.TotalPages != expectedPages && !(*p.TotalItems == 0 && *p.TotalPages == 1) { + return nil, errors.New("secret inventory page totals inconsistent") + } + if index == 0 { + total, pages = *p.TotalItems, *p.TotalPages + } else if total != *p.TotalItems || pages != *p.TotalPages { + return nil, errors.New("secret inventory totals changed") + } + expectedCount := min(100, total-index*100) + if expectedCount < 0 || len(p.Content) != expectedCount { + return nil, errors.New("secret inventory truncated") + } + for _, r := range p.Content { + if !validRecord(r, s) { + return nil, errors.New("secret inventory record malformed or outside requested scope") + } + if _, exists := records[r.Secret.Identifier]; exists { + return nil, errors.New("secret inventory contains duplicate identities") + } + records[r.Secret.Identifier] = r + } + if len(records) == total { + return records, nil + } + if index+1 >= pages { + return nil, errors.New("secret inventory incomplete") + } + } +} + +func validRecord(r record, s Scope) bool { + return !r.Draft && r.Secret != nil && r.Updated != nil && *r.Updated >= 0 && ValidIdentifier(r.Secret.Identifier) && r.Secret.Name != "" && r.Secret.Org == s.Org && r.Secret.Project == s.Source && r.Secret.Type != "" && r.Secret.Spec != nil +} + +func classify(s *secret) Item { + item := Item{Type: "unknown", Capability: Blocked, Reason: "unsupported or unproven secret schema"} + switch s.Type { + case "SecretText", "SecretFile", "SSHKey", "WinRmCredentials": + item.Type = s.Type + default: + return item + } + var specType string + if s.Unproven || json.Unmarshal(s.Spec["type"], &specType) != nil || specType != s.Type { + return item + } + if s.Type != "SecretText" { + return item + } + for key, value := range s.Spec { + switch key { + case "type", "valueType", "secretManagerIdentifier", "value": + case "errorMessageForInvalidYaml": + if string(value) != `""` { + return item + } + default: + return item + } + } + var kind, manager, value string + if json.Unmarshal(s.Spec["valueType"], &kind) != nil || json.Unmarshal(s.Spec["secretManagerIdentifier"], &manager) != nil || manager == "" { + return item + } + if raw, ok := s.Spec["value"]; ok && (string(raw) == "null" || json.Unmarshal(raw, &value) != nil) { + return item + } + managerID := manager + if strings.HasPrefix(managerID, "org.") { + managerID = strings.TrimPrefix(managerID, "org.") + } else { + managerID = strings.TrimPrefix(managerID, "account.") + } + if !ValidIdentifier(managerID) { + return item + } + switch kind { + case "Inline": + item.Capability = MappingRequired + item.Reason = "non-exportable value requires secure provisioning or verified shared mapping" + case "Reference": + if value == "" || strings.Contains(value, "<+") || managerID == "harnessSecretManager" { + return item + } + item.Capability = ReferenceOnly + item.Reason = "external reference configuration only; manager access and destination mapping not verified" + } + return item +} diff --git a/modules/platform/projectcopy/inventory_test.go b/modules/platform/projectcopy/inventory_test.go new file mode 100644 index 00000000..c0a2a641 --- /dev/null +++ b/modules/platform/projectcopy/inventory_test.go @@ -0,0 +1,399 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package projectcopy + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/harness/cli/v3/pkg/auth" + "github.com/harness/cli/v3/pkg/hlog" +) + +const marker = "SYNTHETIC_SENSITIVE_MARKER" + +var testScope = Scope{Account: "fixture_account", Org: "fixture_org", Source: "source", Destination: "destination"} + +type roundTrip func(*http.Request) (*http.Response, error) + +func (fn roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return fn(r) } + +func fakeTransport(fn roundTrip) *Transport { + t := NewTransport(&auth.ResolvedAuth{APIUrl: "https://inventory.invalid/gateway", AccountID: testScope.Account}) + t.http.Transport = fn + t.wait = func(context.Context, time.Duration) error { return nil } + return t +} + +func response(status int, body string) *http.Response { + return &http.Response{StatusCode: status, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))} +} + +func fixture(id string) record { + updated := int64(17) + return record{Secret: &secret{Identifier: id, Name: marker, Org: testScope.Org, Project: testScope.Source, Type: "SecretText", Spec: map[string]json.RawMessage{"type": json.RawMessage(`"SecretText"`), "valueType": json.RawMessage(`"Reference"`), "secretManagerIdentifier": json.RawMessage(`"org.manager"`), "value": json.RawMessage(`"` + marker + `"`)}}, Updated: &updated} +} + +func fixtureReader(count int, mutate func(int, *pageData)) readFn { + records := make([]record, count) + for i := range records { + records[i] = fixture(fmt.Sprintf("secret_%03d", i)) + } + return func(_ context.Context, _ Scope, id string, index int, target any) error { + var value any + if id != "" { + for _, r := range records { + if r.Secret.Identifier == id { + value = map[string]any{"status": "SUCCESS", "data": r} + } + } + } else { + pages, total, size := (count+99)/100, count, 100 + start := min(index*100, count) + end := min(start+100, count) + n := end - start + p := pageData{TotalPages: &pages, TotalItems: &total, PageSize: &size, PageItemCount: &n, Content: append([]record{}, records[start:end]...)} + if mutate != nil { + mutate(index, &p) + } + value = map[string]any{"status": "SUCCESS", "data": p} + } + data, _ := json.Marshal(value) + return json.Unmarshal(data, target) + } +} + +func TestInventoryCompleteAndPayloadSafe(t *testing.T) { + for _, count := range []int{0, 1, 100, 101, 201} { + t.Run(fmt.Sprint(count), func(t *testing.T) { + r, err := inventory(context.Background(), fixtureReader(count, nil), testScope) + if err != nil || !r.InventoryComplete || r.ApplyAvailable || len(r.Secrets) != count { + t.Fatalf("count=%d complete=%v err=%v", len(r.Secrets), r.InventoryComplete, err) + } + data, _ := json.Marshal(r) + for _, s := range []string{marker, "org.manager", "secret_000", "valueType"} { + if bytes.Contains(data, []byte(s)) { + t.Fatal("unsafe API content in report") + } + } + for _, item := range r.Secrets { + if item.Capability != ReferenceOnly { + t.Fatal("unexpected capability") + } + } + }) + } +} + +func TestInventoryRejectsIncompletePages(t *testing.T) { + cases := map[string]func(int, *pageData){ + "missing total": func(_ int, p *pageData) { p.TotalItems = nil }, + "missing content": func(_ int, p *pageData) { p.Content = nil }, + "missing pages": func(_ int, p *pageData) { p.TotalPages = nil }, + "missing count": func(_ int, p *pageData) { p.PageItemCount = nil }, + "truncated": func(_ int, p *pageData) { p.Content = p.Content[:len(p.Content)-1] }, + "wrong scope": func(_ int, p *pageData) { p.Content[0].Secret.Project = "other" }, + "wrong org": func(_ int, p *pageData) { p.Content[0].Secret.Org = "other" }, + "duplicate": func(_ int, p *pageData) { p.Content[1] = p.Content[0] }, + "changed total": func(i int, p *pageData) { + if i > 0 { + *p.TotalItems = 102 + } + }, + "wrong page size": func(_ int, p *pageData) { *p.PageSize = 50 }, + "draft": func(_ int, p *pageData) { p.Content[0].Draft = true }, + "missing revision": func(_ int, p *pageData) { p.Content[0].Updated = nil }, + "wrong pages": func(_ int, p *pageData) { *p.TotalPages = 9 }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + r, err := inventory(context.Background(), fixtureReader(101, mutate), testScope) + if err == nil || r.InventoryComplete { + t.Fatal("invalid inventory accepted") + } + }) + } +} + +func TestCompletedInventoryStillFailsForRequiredMappings(t *testing.T) { + for _, kind := range []string{"Inline", "Unknown"} { + base := fixtureReader(1, nil) + read := func(ctx context.Context, s Scope, id string, page int, target any) error { + if id == "" { + return base(ctx, s, id, page, target) + } + r := fixture(id) + r.Secret.Spec["valueType"] = json.RawMessage(`"` + kind + `"`) + data, _ := json.Marshal(map[string]any{"status": "SUCCESS", "data": r}) + return json.Unmarshal(data, target) + } + r, err := inventory(context.Background(), read, testScope) + if err == nil || !r.InventoryComplete || r.ApplyAvailable || len(r.Secrets) != 1 { + t.Fatal("unsupported plan appeared usable") + } + } +} + +func TestInventoryDetailFailuresAndChurn(t *testing.T) { + for _, mode := range []string{"denied", "missing", "scope", "identity", "type", "revision", "churn", "status"} { + t.Run(mode, func(t *testing.T) { + base := fixtureReader(1, nil) + lists := 0 + read := func(ctx context.Context, s Scope, id string, page int, target any) error { + if id == "" { + lists++ + if lists == 2 && mode == "churn" { + return fixtureReader(0, nil)(ctx, s, id, page, target) + } + return base(ctx, s, id, page, target) + } + if mode == "denied" { + return errors.New("safe denied") + } + r := fixture(id) + status := "SUCCESS" + switch mode { + case "missing": + r.Secret = nil + case "scope": + r.Secret.Project = "other" + case "identity": + r.Secret.Identifier = "other" + case "type": + r.Secret.Type = "SecretFile" + case "revision": + *r.Updated++ + case "status": + status = "FAILURE" + } + data, _ := json.Marshal(map[string]any{"status": status, "data": r}) + return json.Unmarshal(data, target) + } + r, err := inventory(context.Background(), read, testScope) + if err == nil || r.InventoryComplete { + t.Fatal("detail inconsistency accepted") + } + }) + } +} + +func TestSecretCapabilities(t *testing.T) { + for _, tc := range []struct { + name string + modify func(*secret) + want Capability + }{ + {"reference", func(*secret) {}, ReferenceOnly}, + {"inline", func(s *secret) { s.Spec["valueType"] = json.RawMessage(`"Inline"`); delete(s.Spec, "value") }, MappingRequired}, + {"unknown value type", func(s *secret) { s.Spec["valueType"] = json.RawMessage(`"Unknown"`) }, Blocked}, + {"unknown field", func(s *secret) { s.Spec["credentials"] = json.RawMessage(`"` + marker + `"`) }, Blocked}, + {"null value", func(s *secret) { s.Spec["value"] = json.RawMessage(`null`) }, Blocked}, + {"missing locator", func(s *secret) { delete(s.Spec, "value") }, Blocked}, + {"missing manager", func(s *secret) { delete(s.Spec, "secretManagerIdentifier") }, Blocked}, + {"mismatched spec", func(s *secret) { s.Spec["type"] = json.RawMessage(`"SSHKey"`) }, Blocked}, + {"unknown type", func(s *secret) { s.Type = marker }, Blocked}, + {"file", func(s *secret) { s.Type = "SecretFile"; s.Spec["type"] = json.RawMessage(`"SecretFile"`) }, Blocked}, + {"default manager", func(s *secret) { s.Spec["secretManagerIdentifier"] = json.RawMessage(`"harnessSecretManager"`) }, Blocked}, + {"scoped default manager", func(s *secret) { s.Spec["secretManagerIdentifier"] = json.RawMessage(`"account.harnessSecretManager"`) }, Blocked}, + {"dynamic manager", func(s *secret) { s.Spec["secretManagerIdentifier"] = json.RawMessage(`"<+input>"`) }, Blocked}, + {"dynamic locator", func(s *secret) { s.Spec["value"] = json.RawMessage(`"<+input>"`) }, Blocked}, + } { + t.Run(tc.name, func(t *testing.T) { + s := fixture("sample").Secret + tc.modify(s) + got := classify(s) + if got.Capability != tc.want { + t.Fatalf("got %s want %s", got.Capability, tc.want) + } + data, _ := json.Marshal(got) + if bytes.Contains(data, []byte(marker)) { + t.Fatal("unsafe capability output") + } + }) + } +} + +func TestTransportBoundsRetriesAndSanitizes(t *testing.T) { + logPath := filepath.Join(t.TempDir(), "debug.log") + hlog.SetDebugFile(logPath) + for _, tc := range []struct { + name string + statuses []int + body string + network bool + wantCalls int + ok bool + }{ + {"success", []int{200}, `{"status":"SUCCESS"}`, false, 1, true}, + {"retry", []int{429, 503, 200}, `{"status":"SUCCESS"}`, false, 3, true}, + {"denied", []int{403}, marker, false, 1, false}, + {"unauthorized", []int{401}, marker, false, 1, false}, + {"server retries exhausted", []int{503, 503, 503}, marker, false, 3, false}, + {"network", nil, "", true, 3, false}, + {"malformed", []int{200}, `{"status":"` + marker, false, 1, false}, + {"duplicate keys", []int{200}, `{"status":"SUCCESS","status":"FAILURE"}`, false, 1, false}, + {"trailing document", []int{200}, `{} {}`, false, 1, false}, + {"too large", []int{200}, strings.Repeat("x", responseLimit+1), false, 1, false}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + transport := fakeTransport(func(r *http.Request) (*http.Response, error) { + calls++ + if r.Method != "GET" || !strings.HasSuffix(r.URL.Path, "/sample") { + t.Fatal("unexpected/mutating request") + } + if tc.network { + return nil, errors.New(marker) + } + return response(tc.statuses[min(calls-1, len(tc.statuses)-1)], tc.body), nil + }) + var target any + err := transport.read(context.Background(), testScope, "sample", 0, &target) + if (err == nil) != tc.ok || calls != tc.wantCalls { + t.Fatalf("calls=%d error=%v", calls, err) + } + if err != nil && strings.Contains(err.Error(), marker) { + t.Fatal("unsafe error") + } + }) + } + data, err := os.ReadFile(logPath) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(data, []byte(marker)) { + t.Fatal("debug payload leak") + } +} + +func TestTransportReadOnlyPaginationContract(t *testing.T) { + reader := fixtureReader(101, nil) + calls := 0 + tr := fakeTransport(func(r *http.Request) (*http.Response, error) { + calls++ + q := r.URL.Query() + if q.Get("projectIdentifier") != "source" || q.Get("orgIdentifier") != testScope.Org { + t.Fatal("scope drift") + } + id := "" + page := 0 + if r.URL.Path == "/gateway"+secretsPath+"/list/secrets" { + if r.Method != "POST" { + t.Fatal("unexpected method") + } + fmt.Sscan(q.Get("pageIndex"), &page) + } else if r.Method == "GET" && strings.HasPrefix(r.URL.Path, "/gateway"+secretsPath+"/secret_") { + id = strings.TrimPrefix(r.URL.Path, "/gateway"+secretsPath+"/") + } else { + t.Fatal("non-inventory request") + } + var target any + if err := reader(r.Context(), testScope, id, page, &target); err != nil { + t.Fatal(err) + } + data, _ := json.Marshal(target) + return response(200, string(data)), nil + }) + report, err := Inventory(context.Background(), tr, testScope) + if err != nil || !report.InventoryComplete || calls != 105 { + t.Fatalf("calls=%d err=%v", calls, err) + } +} + +func TestInventorySensitiveFailuresAcrossDiagnostics(t *testing.T) { + for _, mode := range []string{"denied", "malformed", "network", "partial"} { + t.Run(mode, func(t *testing.T) { + logPath := filepath.Join(t.TempDir(), "debug.log") + hlog.SetDebugFile(logPath) + tr := fakeTransport(func(r *http.Request) (*http.Response, error) { + if mode == "network" { + return nil, errors.New(marker) + } + if mode == "malformed" { + return response(200, `{"message":"`+marker), nil + } + if mode == "partial" && r.Method == "POST" { + var data any + if err := fixtureReader(1, nil)(r.Context(), testScope, "", 0, &data); err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(data) + return response(200, string(b)), nil + } + return response(403, `{"message":"`+marker+`","definition":"`+marker+`"}`), nil + }) + outRead, outWrite, _ := os.Pipe() + errRead, errWrite, _ := os.Pipe() + oldOut, oldErr := os.Stdout, os.Stderr + os.Stdout, os.Stderr = outWrite, errWrite + defer func() { os.Stdout, os.Stderr = oldOut, oldErr }() + r, err := Inventory(context.Background(), tr, testScope) + json.NewEncoder(os.Stdout).Encode(r) + fmt.Fprintln(os.Stderr, err) + outWrite.Close() + errWrite.Close() + stdout, _ := io.ReadAll(outRead) + stderr, _ := io.ReadAll(errRead) + outRead.Close() + errRead.Close() + debug, _ := os.ReadFile(logPath) + if err == nil || r.InventoryComplete { + t.Fatal("failed inventory claimed complete") + } + for _, surface := range [][]byte{stdout, stderr, debug} { + if bytes.Contains(surface, []byte(marker)) { + t.Fatal("sensitive marker in diagnostics") + } + } + }) + } +} + +func TestUnknownSecretRootFieldsBlock(t *testing.T) { + var s secret + if err := json.Unmarshal([]byte(`{"type":"SecretText","privateSecret":true}`), &s); err != nil { + t.Fatal(err) + } + if !s.Unproven || classify(&s).Capability != Blocked { + t.Fatal("unknown root field accepted") + } +} + +func TestTransportRetryAfterAndCancellation(t *testing.T) { + for _, delay := range []string{"2", "999999999", "invalid"} { + t.Run(delay, func(t *testing.T) { + calls, waits := 0, 0 + tr := fakeTransport(func(*http.Request) (*http.Response, error) { + calls++ + r := response(429, marker) + r.Header.Set("Retry-After", delay) + return r, nil + }) + tr.wait = func(context.Context, time.Duration) error { waits++; return errors.New(marker) } + var v any + err := tr.read(context.Background(), testScope, "sample", 0, &v) + if err == nil || calls != 1 || strings.Contains(err.Error(), marker) { + t.Fatal("unsafe retry") + } + if delay == "2" && waits != 1 { + t.Fatal("retry-after not honored") + } + }) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if wait(ctx, time.Hour) == nil { + t.Fatal("cancel ignored") + } +} diff --git a/modules/platform/projectcopy/transport.go b/modules/platform/projectcopy/transport.go new file mode 100644 index 00000000..aa5bfc2a --- /dev/null +++ b/modules/platform/projectcopy/transport.go @@ -0,0 +1,168 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package projectcopy + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/harness/cli/v3/pkg/auth" +) + +const secretsPath = "/ng/api/v2/secrets" +const responseLimit = 4 << 20 + +type Transport struct { + auth *auth.ResolvedAuth + http *http.Client + wait func(context.Context, time.Duration) error +} + +func NewTransport(a *auth.ResolvedAuth) *Transport { + return &Transport{auth: a, http: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, wait: wait} +} + +func wait(ctx context.Context, d time.Duration) error { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-timer.C: + return nil + case <-ctx.Done(): + return errors.New("secret inventory cancelled") + } +} + +// The POST below is a documented list operation, never a resource creation. +func (t *Transport) read(ctx context.Context, scope Scope, id string, page int, target any) error { + base, err := url.Parse(t.auth.APIUrl) + if err != nil || base.Scheme != "https" || base.Host == "" || base.User != nil || base.RawQuery != "" || base.Fragment != "" { + return errors.New("secret inventory requires a valid HTTPS API base URL without credentials, query or fragment") + } + method, path, body := http.MethodPost, secretsPath+"/list/secrets", `{"filterType":"Secret"}` + if id != "" { + if !ValidIdentifier(id) { + return errors.New("invalid secret inventory identity") + } + method, path, body = http.MethodGet, secretsPath+"/"+id, "" + } + base.Path = strings.TrimRight(base.Path, "/") + path + q := url.Values{"accountIdentifier": {scope.Account}, "orgIdentifier": {scope.Org}, "projectIdentifier": {scope.Source}} + if id == "" { + q.Set("pageIndex", strconv.Itoa(page)) + q.Set("pageSize", "100") + } + base.RawQuery = q.Encode() + for attempt := 0; attempt < 3; attempt++ { + req, err := http.NewRequestWithContext(ctx, method, base.String(), strings.NewReader(body)) + if err != nil { + return errors.New("cannot prepare secret inventory request") + } + t.auth.SetAuthHeader(req) + req.Header.Set("Accept", "application/json") + req.Header.Set("Content-Type", "application/json") + // Do not use the generic client: even its raw path logs URLs and network errors. + resp, err := t.http.Do(req) + if err != nil { + if attempt == 2 || ctx.Err() != nil { + return errors.New("secret inventory request failed") + } + if t.wait(ctx, time.Duration(attempt+1)*time.Second) != nil { + return errors.New("secret inventory cancelled") + } + continue + } + retry := resp.StatusCode == 429 || resp.StatusCode == 502 || resp.StatusCode == 503 || resp.StatusCode == 504 + if retry && attempt < 2 { + delay := time.Duration(attempt+1) * time.Second + if raw := resp.Header.Get("Retry-After"); raw != "" { + if seconds, e := strconv.Atoi(raw); e == nil && seconds >= 0 { + delay = time.Duration(min(seconds, 11)) * time.Second + } else if date, e := http.ParseTime(raw); e == nil { + delay = max(time.Until(date), 0) + } else { + resp.Body.Close() + return errors.New("secret inventory retry policy unavailable") + } + } + resp.Body.Close() + if delay > 10*time.Second { + return errors.New("secret inventory rate limited; retry later") + } + if t.wait(ctx, delay) != nil { + return errors.New("secret inventory cancelled") + } + continue + } + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return errors.New("secret inventory read denied or unavailable") + } + data, err := io.ReadAll(io.LimitReader(resp.Body, responseLimit+1)) + resp.Body.Close() + if err != nil || len(data) > responseLimit { + return errors.New("secret inventory response incomplete or too large") + } + if !json.Valid(data) || !unambiguousJSON(data) || json.Unmarshal(data, target) != nil { + return errors.New("malformed secret inventory response") + } + return nil + } + return errors.New("secret inventory retries exhausted") +} + +func unambiguousJSON(data []byte) bool { + dec := json.NewDecoder(strings.NewReader(string(data))) + var value func() bool + value = func() bool { + token, err := dec.Token() + if err != nil { + return false + } + delim, ok := token.(json.Delim) + if !ok { + return true + } + switch delim { + case '{': + seen := map[string]bool{} + for dec.More() { + key, e := dec.Token() + if e != nil { + return false + } + s, ok := key.(string) + if !ok || seen[s] { + return false + } + seen[s] = true + if !value() { + return false + } + } + case '[': + for dec.More() { + if !value() { + return false + } + } + default: + return false + } + end, e := dec.Token() + return e == nil && ((delim == '{' && end == json.Delim('}')) || (delim == '[' && end == json.Delim(']'))) + } + if !value() { + return false + } + _, err := dec.Token() + return err == io.EOF +} diff --git a/modules/platform/projectcopy/types.go b/modules/platform/projectcopy/types.go new file mode 100644 index 00000000..649c5975 --- /dev/null +++ b/modules/platform/projectcopy/types.go @@ -0,0 +1,59 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package projectcopy + +import ( + "errors" + "regexp" +) + +var identifier = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,127}$`) +var accountIdentifier = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`) + +func ValidIdentifier(s string) bool { return identifier.MatchString(s) } + +type Scope struct { + Account string `json:"account"` + Org string `json:"org"` + Source string `json:"source"` + Destination string `json:"destination"` +} + +func (s Scope) Validate() error { + if !accountIdentifier.MatchString(s.Account) || !ValidIdentifier(s.Org) || !ValidIdentifier(s.Source) || !ValidIdentifier(s.Destination) || s.Source == s.Destination { + return errors.New("project planning requires an account, org, and distinct explicit source/destination project identifiers") + } + return nil +} + +type Capability string + +const ( + Copyable Capability = "copyable" + ReferenceOnly Capability = "reference-only" + MappingRequired Capability = "mapping-required" + Blocked Capability = "blocked" +) + +type Item struct { + Number int `json:"number"` + Type string `json:"type"` + Capability Capability `json:"capability"` + Reason string `json:"reason"` +} + +type Report struct { + Scope Scope `json:"scope"` + Coverage string `json:"coverage"` + Mode string `json:"mode"` + InventoryComplete bool `json:"inventory_complete"` + ApplyAvailable bool `json:"apply_available"` + Readiness string `json:"readiness"` + NotInventoried []string `json:"not_inventoried"` + Secrets []Item `json:"secrets"` +} + +func NewReport(s Scope) Report { + return Report{Scope: s, Coverage: "PARTIAL", Mode: "read-only planning", Readiness: "NOT ASSESSED; destination not checked or created", NotInventoried: []string{"connectors", "pipelines", "all other project resources"}, Secrets: []Item{}} +} diff --git a/pkg/spec/platform.spec.yaml b/pkg/spec/platform.spec.yaml index cfdfcf2a..49960728 100644 --- a/pkg/spec/platform.spec.yaml +++ b/pkg/spec/platform.spec.yaml @@ -490,6 +490,37 @@ nouns: expr: epochMs(it.createdAt) commands: + - command: migrate project:project + verb: migrate + noun: project + noun_to: project + short: "PARTIAL read-only secret inventory and capability planning (no apply)" + long: | + Inventory only the source project's selected secrets. Requires explicit + source/destination projects and --resources secret. The destination is not + checked or created; connectors, pipelines and other resources are NOT INVENTORIED. + Values, locators and raw definitions are never reported. Apply is unavailable. + Reports support text/JSON and --out to a NEW file only; existing files are never overwritten. + handler_type: workflow + workflow_id: project_copy + migrate_from: + presence: required + label: Source project identifier + migrate_to: + presence: required + label: Destination project identifier (not created) + flags: + - name: resources + required: true + description: "Explicit resource selection: secret only" + - name: dry-run + is_bool: true + description: "Read-only planning (also the default; no apply implementation)" + - name: apply + is_bool: true + hidden: true + description: "Unavailable; rejected before inventory" + - command: list organization verb: list noun: organization From 16daa6ef1d9c97e17d54092eaae69a5d1b31a124 Mon Sep 17 00:00:00 2001 From: "augmentcode[bot]" <185243770+augmentcode[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:40:41 +0000 Subject: [PATCH 2/7] fix(platform): simplify inventory pagination guard for staticcheck --- modules/platform/projectcopy/inventory.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/platform/projectcopy/inventory.go b/modules/platform/projectcopy/inventory.go index 45c72ff9..85efb241 100644 --- a/modules/platform/projectcopy/inventory.go +++ b/modules/platform/projectcopy/inventory.go @@ -127,7 +127,7 @@ func list(ctx context.Context, read readFn, s Scope) (map[string]record, error) return nil, errors.New("secret inventory pagination invalid") } expectedPages := (*p.TotalItems + 99) / 100 - if *p.TotalPages != expectedPages && !(*p.TotalItems == 0 && *p.TotalPages == 1) { + if *p.TotalPages != expectedPages && (*p.TotalItems != 0 || *p.TotalPages != 1) { return nil, errors.New("secret inventory page totals inconsistent") } if index == 0 { From 4a204e27fc294174cbeb42481d4213695ce81441 Mon Sep 17 00:00:00 2001 From: "augmentcode[bot]" <185243770+augmentcode[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:54:26 +0000 Subject: [PATCH 3/7] fix(platform): reject ambiguous secret inventory controls --- modules/platform/project-copy.md | 8 +- modules/platform/projectcopy/inventory.go | 80 +++++++-- .../platform/projectcopy/inventory_test.go | 164 +++++++++++++++++- modules/platform/projectcopy/transport.go | 15 ++ 4 files changed, 249 insertions(+), 18 deletions(-) diff --git a/modules/platform/project-copy.md b/modules/platform/project-copy.md index 4e8d3f1c..bc547e4e 100644 --- a/modules/platform/project-copy.md +++ b/modules/platform/project-copy.md @@ -54,8 +54,12 @@ only partial observations. A complete inventory may still contain blocked items. - [Harness SecretText SDK schema](https://github.com/harness/harness-go-sdk/blob/2d590feb560bb8609bef3f96e73601602b13574b/harness/nextgen/model_secret_text_spec.go): `type`, `secretManagerIdentifier`, `valueType`, optional `value` and `additionalMetadata`. Only the minimal variant without additional metadata is supported here. Inventory validates all pagination metadata, counts, unique identities, source -scope and list/detail type/revision agreement. It re-lists after details and -rejects observed churn. This is not an atomic server snapshot or a guarantee +scope and list/detail type/revision agreement. Present `pageIndex` and `empty` +controls must match the requested page and content; `pageToken` must be an empty +string because token-based continuation is not supported. Unknown page controls, +case aliases, null controls and unsupported list-secret fields fail closed. +Documented optional controls may be omitted, including `draft` (default false). +It re-lists after details and rejects observed churn. This is not an atomic server snapshot or a guarantee against a change after the final read. Missing/restricted/inconsistent results are never interpreted as an empty inventory. Inventories over 100,000 items or responses over 4 MiB fail closed rather than being silently truncated. diff --git a/modules/platform/projectcopy/inventory.go b/modules/platform/projectcopy/inventory.go index 85efb241..20ad7d52 100644 --- a/modules/platform/projectcopy/inventory.go +++ b/modules/platform/projectcopy/inventory.go @@ -23,14 +23,16 @@ type secret struct { } func (s *secret) UnmarshalJSON(data []byte) error { - type plain secret - if err := json.Unmarshal(data, (*plain)(s)); err != nil { + fields, err := canonicalObject(data, "identifier", "name", "orgIdentifier", "projectIdentifier", "type", "spec") + if err != nil { return err } - var fields map[string]json.RawMessage - if err := json.Unmarshal(data, &fields); err != nil { + type plain secret + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { return err } + *s = secret(decoded) for key := range fields { switch key { case "identifier", "name", "orgIdentifier", "projectIdentifier", "type", "spec", "description", "tags": @@ -47,12 +49,67 @@ type record struct { Draft bool `json:"draft"` } +func (r *record) UnmarshalJSON(data []byte) error { + if _, err := canonicalObject(data, "secret", "updatedAt", "draft"); err != nil { + return err + } + type plain record + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *r = record(decoded) + return nil +} + type pageData struct { TotalPages *int `json:"totalPages"` TotalItems *int `json:"totalItems"` PageItemCount *int `json:"pageItemCount"` PageSize *int `json:"pageSize"` Content []record `json:"content"` + PageIndex *int `json:"pageIndex,omitempty"` + Empty *bool `json:"empty,omitempty"` + PageToken *string `json:"pageToken,omitempty"` +} + +func (p *pageData) UnmarshalJSON(data []byte) error { + fields, err := canonicalObject(data, "totalPages", "totalItems", "pageItemCount", "pageSize", "content", "pageIndex", "empty", "pageToken") + if err != nil { + return err + } + for key := range fields { + switch key { + case "totalPages", "totalItems", "pageItemCount", "pageSize", "content", "pageIndex", "empty", "pageToken": + default: + return errors.New("unproven secret inventory pagination control") + } + } + type plain pageData + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *p = pageData(decoded) + return nil +} + +type envelope[T any] struct { + Status string `json:"status"` + Data *T `json:"data"` +} + +func (e *envelope[T]) UnmarshalJSON(data []byte) error { + if _, err := canonicalObject(data, "status", "data"); err != nil { + return err + } + type plain envelope[T] + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *e = envelope[T](decoded) + return nil } type readFn func(context.Context, Scope, string, int, any) error @@ -77,10 +134,7 @@ func inventory(ctx context.Context, read readFn, s Scope) (Report, error) { sort.Strings(ids) blocked := false for _, id := range ids { - var detail struct { - Status string `json:"status"` - Data *record `json:"data"` - } + var detail envelope[record] if err := read(ctx, s, id, 0, &detail); err != nil { return report, err } @@ -112,10 +166,7 @@ func list(ctx context.Context, read readFn, s Scope) (map[string]record, error) records := map[string]record{} total, pages := -1, -1 for index := 0; ; index++ { - var response struct { - Status string `json:"status"` - Data *pageData `json:"data"` - } + var response envelope[pageData] if err := read(ctx, s, "", index, &response); err != nil { return nil, err } @@ -126,6 +177,9 @@ func list(ctx context.Context, read readFn, s Scope) (map[string]record, error) if *p.TotalItems < 0 || *p.TotalItems > 100000 || *p.TotalPages < 0 || *p.PageSize != 100 || *p.PageItemCount != len(p.Content) || len(p.Content) > 100 { return nil, errors.New("secret inventory pagination invalid") } + if (p.PageIndex != nil && *p.PageIndex != index) || (p.Empty != nil && *p.Empty != (len(p.Content) == 0)) || (p.PageToken != nil && *p.PageToken != "") { + return nil, errors.New("secret inventory page position or continuation inconsistent") + } expectedPages := (*p.TotalItems + 99) / 100 if *p.TotalPages != expectedPages && (*p.TotalItems != 0 || *p.TotalPages != 1) { return nil, errors.New("secret inventory page totals inconsistent") @@ -158,7 +212,7 @@ func list(ctx context.Context, read readFn, s Scope) (map[string]record, error) } func validRecord(r record, s Scope) bool { - return !r.Draft && r.Secret != nil && r.Updated != nil && *r.Updated >= 0 && ValidIdentifier(r.Secret.Identifier) && r.Secret.Name != "" && r.Secret.Org == s.Org && r.Secret.Project == s.Source && r.Secret.Type != "" && r.Secret.Spec != nil + return !r.Draft && r.Secret != nil && !r.Secret.Unproven && r.Updated != nil && *r.Updated >= 0 && ValidIdentifier(r.Secret.Identifier) && r.Secret.Name != "" && r.Secret.Org == s.Org && r.Secret.Project == s.Source && r.Secret.Type != "" && r.Secret.Spec != nil } func classify(s *secret) Item { diff --git a/modules/platform/projectcopy/inventory_test.go b/modules/platform/projectcopy/inventory_test.go index c0a2a641..3631366a 100644 --- a/modules/platform/projectcopy/inventory_test.go +++ b/modules/platform/projectcopy/inventory_test.go @@ -312,7 +312,7 @@ func TestTransportReadOnlyPaginationContract(t *testing.T) { } func TestInventorySensitiveFailuresAcrossDiagnostics(t *testing.T) { - for _, mode := range []string{"denied", "malformed", "network", "partial"} { + for _, mode := range []string{"denied", "malformed", "network", "partial", "ambiguous", "null control", "pagination control", "unknown list schema"} { t.Run(mode, func(t *testing.T) { logPath := filepath.Join(t.TempDir(), "debug.log") hlog.SetDebugFile(logPath) @@ -323,13 +323,24 @@ func TestInventorySensitiveFailuresAcrossDiagnostics(t *testing.T) { if mode == "malformed" { return response(200, `{"message":"`+marker), nil } - if mode == "partial" && r.Method == "POST" { + if mode != "denied" && r.Method == "POST" { var data any if err := fixtureReader(1, nil)(r.Context(), testScope, "", 0, &data); err != nil { t.Fatal(err) } b, _ := json.Marshal(data) - return response(200, string(b)), nil + body := string(b) + switch mode { + case "ambiguous": + body = strings.Replace(body, `"draft":false`, `"draft":true,"Draft":false`, 1) + case "null control": + body = strings.Replace(body, `"draft":false`, `"draft":null`, 1) + case "pagination control": + body = strings.Replace(body, `"pageSize":100`, `"pageSize":100,"pageIndex":"`+marker+`"`, 1) + case "unknown list schema": + body = strings.Replace(body, `"spec":`, `"unprovenControl":"`+marker+`","spec":`, 1) + } + return response(200, body), nil } return response(403, `{"message":"`+marker+`","definition":"`+marker+`"}`), nil }) @@ -370,6 +381,153 @@ func TestUnknownSecretRootFieldsBlock(t *testing.T) { } } +func rewriteReader(base readFn, rewrite func(string, int, []byte) []byte) readFn { + return func(ctx context.Context, s Scope, id string, page int, target any) error { + var value any + if err := base(ctx, s, id, page, &value); err != nil { + return err + } + data, err := json.Marshal(value) + if err != nil { + return err + } + return json.Unmarshal(rewrite(id, page, data), target) + } +} + +func TestInventoryRejectsAmbiguousControls(t *testing.T) { + for _, tc := range []struct{ name, from, to string }{ + {"status aliases", `"status":"SUCCESS"`, `"status":"ERROR","Status":"SUCCESS"`}, + {"status aliases reversed", `"status":"SUCCESS"`, `"Status":"SUCCESS","status":"ERROR"`}, + {"status alias only", `"status":"SUCCESS"`, `"Status":"SUCCESS"`}, + {"null status", `"status":"SUCCESS"`, `"status":null`}, + {"draft aliases", `"draft":false`, `"draft":true,"Draft":false`}, + {"draft aliases reversed", `"draft":false`, `"Draft":false,"draft":true`}, + {"draft alias only", `"draft":false`, `"Draft":false`}, + {"null draft", `"draft":false`, `"draft":null`}, + {"string draft", `"draft":false`, `"draft":"false"`}, + {"data aliases", `"data":`, `"Data":null,"data":`}, + {"revision aliases", `"updatedAt":17`, `"updatedAt":-1,"UpdatedAt":17`}, + {"scope aliases", `"projectIdentifier":"source"`, `"projectIdentifier":"other","ProjectIdentifier":"source"`}, + } { + for _, detail := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/detail=%v", tc.name, detail), func(t *testing.T) { + calls := 0 + read := rewriteReader(fixtureReader(1, nil), func(id string, _ int, data []byte) []byte { + calls++ + if (id != "") == detail { + return []byte(strings.Replace(string(data), tc.from, tc.to, 1)) + } + return data + }) + r, err := inventory(context.Background(), read, testScope) + wantCalls := 1 + if detail { + wantCalls = 2 + } + if err == nil || r.InventoryComplete || len(r.Secrets) != 0 || calls != wantCalls { + t.Fatalf("ambiguous controls accepted: calls=%d complete=%v err=%v", calls, r.InventoryComplete, err) + } + }) + } + } +} + +func TestInventoryValidatesOptionalPaginationControls(t *testing.T) { + for _, control := range []string{ + `"pageIndex":99`, `"pageIndex":null`, `"pageIndex":"0"`, `"PageIndex":0`, + `"empty":true`, `"empty":null`, `"empty":0`, + `"pageToken":{}`, `"pageToken":null`, `"pageToken":"unproven_continuation"`, + `"nextCursor":"unproven_continuation"`, + } { + t.Run(control, func(t *testing.T) { + read := rewriteReader(fixtureReader(1, nil), func(id string, _ int, data []byte) []byte { + if id == "" { + return []byte(strings.Replace(string(data), `"pageSize":100`, `"pageSize":100,`+control, 1)) + } + return data + }) + r, err := inventory(context.Background(), read, testScope) + if err == nil || r.InventoryComplete { + t.Fatal("unproven pagination accepted") + } + }) + } + for _, tc := range []struct { + name string + count int + }{ + {"wrong later page", 101}, {"false empty page", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + read := fixtureReader(tc.count, func(_ int, p *pageData) { + zero, empty := 0, false + p.PageIndex, p.Empty = &zero, &empty + }) + r, err := inventory(context.Background(), read, testScope) + if err == nil || r.InventoryComplete { + t.Fatal("inconsistent page controls accepted") + } + }) + } +} + +func TestInventoryPreservesDocumentedPaginationAndOptionalDraft(t *testing.T) { + for _, tc := range []struct { + count int + legacyZero bool + }{ + {0, false}, {0, true}, {201, false}, + } { + t.Run(fmt.Sprintf("count=%d/legacyZero=%v", tc.count, tc.legacyZero), func(t *testing.T) { + base := fixtureReader(tc.count, func(index int, p *pageData) { + empty, token := len(p.Content) == 0, "" + p.PageIndex, p.Empty, p.PageToken = &index, &empty, &token + if tc.legacyZero { + *p.TotalPages = 1 + } + }) + read := rewriteReader(base, func(_ string, _ int, data []byte) []byte { + body := strings.ReplaceAll(string(data), `"draft":false,`, "") + return []byte(strings.ReplaceAll(body, `"name":`, `"tags":{"Owner":"one","owner":"two"},"name":`)) + }) + r, err := inventory(context.Background(), read, testScope) + if err != nil || !r.InventoryComplete || len(r.Secrets) != tc.count { + t.Fatalf("documented pagination rejected: complete=%v err=%v", r.InventoryComplete, err) + } + }) + } +} + +func TestInventoryDoesNotEraseUnknownListSchema(t *testing.T) { + for _, tc := range []struct { + name string + count int + page int + relist bool + }{ + {"first page", 1, 0, false}, {"later page", 101, 1, false}, {"relist", 1, 0, true}, + } { + t.Run(tc.name, func(t *testing.T) { + lists := 0 + read := rewriteReader(fixtureReader(tc.count, nil), func(id string, page int, data []byte) []byte { + if id == "" { + lists++ + isRelist := lists > (tc.count+99)/100 + if page == tc.page && isRelist == tc.relist { + return []byte(strings.Replace(string(data), `"spec":`, `"unprovenControl":true,"spec":`, 1)) + } + } + return data + }) + r, err := inventory(context.Background(), read, testScope) + if err == nil || r.InventoryComplete { + t.Fatal("unknown list schema erased by minimal detail") + } + }) + } +} + func TestTransportRetryAfterAndCancellation(t *testing.T) { for _, delay := range []string{"2", "999999999", "invalid"} { t.Run(delay, func(t *testing.T) { diff --git a/modules/platform/projectcopy/transport.go b/modules/platform/projectcopy/transport.go index aa5bfc2a..ec89a81f 100644 --- a/modules/platform/projectcopy/transport.go +++ b/modules/platform/projectcopy/transport.go @@ -119,6 +119,21 @@ func (t *Transport) read(ctx context.Context, scope Scope, id string, page int, return errors.New("secret inventory retries exhausted") } +func canonicalObject(data []byte, controls ...string) (map[string]json.RawMessage, error) { + var fields map[string]json.RawMessage + if !unambiguousJSON(data) || json.Unmarshal(data, &fields) != nil || fields == nil { + return nil, errors.New("malformed secret inventory object") + } + for key, value := range fields { + for _, control := range controls { + if strings.EqualFold(key, control) && (key != control || string(value) == "null") { + return nil, errors.New("ambiguous or null secret inventory control") + } + } + } + return fields, nil +} + func unambiguousJSON(data []byte) bool { dec := json.NewDecoder(strings.NewReader(string(data))) var value func() bool From 94223c2e441c71b49b8f5b90c19a82859a6914b4 Mon Sep 17 00:00:00 2001 From: Dewan Ahmed Date: Fri, 23 Oct 2026 21:46:06 -0300 Subject: [PATCH 4/7] feat(platform): copy CD-core project resources within an org Extend migrate project:project from secret planning to a same-org copy of pipelines and their platform dependencies, creating the destination project when needed and leaving inline secret values for the user to replace. Co-authored-by: Cursor --- modules/platform/project-copy.md | 142 +- modules/platform/project_copy.go | 50 +- modules/platform/project_copy_test.go | 8 +- modules/platform/projectcopy/copy.go | 1220 +++++++++++++++++ modules/platform/projectcopy/copy_test.go | 371 +++++ modules/platform/projectcopy/inventory.go | 16 +- .../platform/projectcopy/inventory_test.go | 3 + modules/platform/projectcopy/rewrite.go | 181 +++ modules/platform/projectcopy/transport.go | 73 + modules/platform/projectcopy/types.go | 53 +- pkg/spec/platform.spec.yaml | 33 +- 11 files changed, 2048 insertions(+), 102 deletions(-) create mode 100644 modules/platform/projectcopy/copy.go create mode 100644 modules/platform/projectcopy/copy_test.go create mode 100644 modules/platform/projectcopy/rewrite.go diff --git a/modules/platform/project-copy.md b/modules/platform/project-copy.md index bc547e4e..4b21a88e 100644 --- a/modules/platform/project-copy.md +++ b/modules/platform/project-copy.md @@ -1,77 +1,75 @@ -# PARTIAL project-copy planning: secrets only +# Copy a project (CD core) -This release inventories source-project secrets and reports capabilities only. -**It does not create/check a destination, copy anything, or establish readiness.** -Connectors, pipelines and all other project resources are **NOT INVENTORIED**. -Apply, mappings and non-secret selections are unavailable; unsupported selections -are rejected before inventory. The destination must be distinct and explicit. +`harness migrate project:project` copies project-scoped CD configuration from one project to another in the same org. The CLI reads the source and writes the destination. Delegates, executions, code repositories, GitOps, and feature flags are not copied. ```sh -harness migrate project:project --from source_project --to destination_project --org example_org --resources secret --dry-run -harness migrate project:project --from source_project --to destination_project --org example_org --resources secret --json --out new-report.json +harness migrate project:project \ + --from source_project \ + --to destination_project \ + --org example_org \ + --resources cd-core + +harness migrate project:project \ + --from source_project \ + --to destination_project \ + --org example_org \ + --resources cd-core \ + --apply +``` + +The first command is a plan. Nothing is written. `--apply` creates the destination project when it does not exist, then copies resources. `--from` and `--to` are required and must differ. The profile's default project is not used. Pass `--org` for the shared org. + +## What is copied + +Order: project, secrets, connectors, services, environments, infrastructures, service overrides, templates, pipelines, input sets, triggers, policies, policy sets. + +- Inline `SecretText` is created with the placeholder value `123456`. The source value is not read. Update each listed secret before running the destination project. +- Reference secrets copy the secret manager and reference path. +- Other secret types are reported as blocked and skipped. +- Triggers are created disabled. +- Git-backed entities are skipped. +- Org and account references, including `account.` and `org.` identifiers, are reported and left in place. +- Delegate selectors are checked against connected delegates. Delegates themselves are not installed. +- Identical destination resources are skipped. A same identifier with different content aborts the copy before any write. + +## Test against a source project + +Use a project in an org your token can read and write. Pick a destination identifier that does not already exist. + +```sh +task build +./bin/harness migrate project:project \ + --from YOUR_SOURCE_PROJECT \ + --to YOUR_DESTINATION_PROJECT \ + --org YOUR_ORG \ + --resources cd-core ``` -Normal profile/environment authentication and `--org` resolution apply. The -profile's default project is ignored: neither `--from` nor `--to` defaults. -Explicit `--project` and non-project `--level` are rejected. Omit `--dry-run` for -the same read-only behavior; there is no apply implementation. `--apply` and -explicit `--dry-run=false` error before inventory. -No confirmation, `--force`, resource files or checkpoint/resume path exists. - -## Safe reports and exit status - -Text (default), `--format text`, `--format json` and `--json` report the same -PARTIAL scope and completion status. `--raw` cannot reveal raw definitions: only -the safe report ever reaches output. `--out` exclusively creates a **new**, mode -0600 file; existing files and symlink/hardlink aliases are never overwritten. -There is no separate report-file flag. Output errors do not print file contents -or source response text. Shell redirection remains the caller's responsibility. - -Secret entries use report-local ordinals, fixed type/capability labels and fixed -reasons, not names/identifiers, values, manager identifiers, locators, descriptions, -raw definitions or hashes. Definitions are memory-only, never debug logged. - -| Capability | Meaning in this release | -| --- | --- | -| `reference-only` | Known external SecretText Reference configuration; no value export. Manager/destination access and mapping remain unverified. | -| `mapping-required` | SecretText Inline values are non-exportable; secure provisioning or verified shared mappings are needed later. | -| `blocked` | Unsupported/missing/unknown fields or types; no copy support is claimed. | -| `copyable` | Reserved capability vocabulary; **never assigned** without proven dependency/access/apply contracts. | - -Only the documented minimal SecretText schema is classified as reference-only or -mapping-required. Additional metadata, other secret types, unknown/control fields -and unproven variants block; no writable definition is produced or retained for -apply. A complete reference inventory can exit zero, including an empty inventory; -this means only read-only inventory completion, **not copy readiness**. Required -mappings, blocked variants, denied reads or incomplete inventories exit nonzero. -A failed inventory report has `inventory_complete: false`; earlier entries are -only partial observations. A complete inventory may still contain blocked items. - -## Public contracts and offline validation - -- [List API](https://apidocs.harness.io/secrets/listsecretsv4): read-only `POST /ng/api/v2/secrets/list/secrets`, `filterType: Secret`, scoped account/org/project, zero-based `pageIndex`, maximum `pageSize: 100`, response `totalItems`, `totalPages`, `pageItemCount`, `pageSize`, `content[].secret` and `updatedAt`. -- [Detail API](https://apidocs.harness.io/secrets/getsecretv2): scoped `GET /ng/api/v2/secrets/{identifier}`, `data.secret` and `updatedAt`. -- [Harness SecretText SDK schema](https://github.com/harness/harness-go-sdk/blob/2d590feb560bb8609bef3f96e73601602b13574b/harness/nextgen/model_secret_text_spec.go): `type`, `secretManagerIdentifier`, `valueType`, optional `value` and `additionalMetadata`. Only the minimal variant without additional metadata is supported here. - -Inventory validates all pagination metadata, counts, unique identities, source -scope and list/detail type/revision agreement. Present `pageIndex` and `empty` -controls must match the requested page and content; `pageToken` must be an empty -string because token-based continuation is not supported. Unknown page controls, -case aliases, null controls and unsupported list-secret fields fail closed. -Documented optional controls may be omitted, including `draft` (default false). -It re-lists after details and rejects observed churn. This is not an atomic server snapshot or a guarantee -against a change after the final read. Missing/restricted/inconsistent results -are never interpreted as an empty inventory. Inventories over 100,000 items or -responses over 4 MiB fail closed rather than being silently truncated. - -The module's authenticated raw transport allows only the documented list and -detail reads, disables redirects, discards response/error bodies from diagnostics, -and makes at most three attempts for network/429/502/503/504 failures. Bounded, -cancellable delays honor Retry-After; waits above ten seconds fail for a later -manual retry, not an early request. Other status/schema errors are not retried. - -Tests use synthetic public-contract fixtures and fake transports for pagination, -scope/access failures, malformed/truncated responses, churn, capabilities, -retries, no mutation paths, sensitive-marker absence and protected report files. -**No live Harness reads, profiles or resources were used.** Mocks validate local -behavior, not live API conformance, permission completeness or operational readiness. +Read the plan. Then apply: + +```sh +./bin/harness migrate project:project \ + --from YOUR_SOURCE_PROJECT \ + --to YOUR_DESTINATION_PROJECT \ + --org YOUR_ORG \ + --resources cd-core \ + --apply +``` + +After apply, replace each inline secret: + +```sh +./bin/harness update secret SECRET_ID --org YOUR_ORG --project YOUR_DESTINATION_PROJECT --set value='the-real-value' +``` + +Check the destination in the UI, or: + +```sh +./bin/harness list pipeline --org YOUR_ORG --project YOUR_DESTINATION_PROJECT +./bin/harness list connector --org YOUR_ORG --project YOUR_DESTINATION_PROJECT +./bin/harness list secret --org YOUR_ORG --project YOUR_DESTINATION_PROJECT +``` + +Run the same `--apply` command again. Resources that match should be reported as `skip`, and inline secrets you already updated should not be reset to `123456`. + +`--out report.json` writes the report to a new file and refuses to overwrite an existing one. `--format json` prints the same report to stdout. diff --git a/modules/platform/project_copy.go b/modules/platform/project_copy.go index ce9c1524..4ed12098 100644 --- a/modules/platform/project_copy.go +++ b/modules/platform/project_copy.go @@ -19,19 +19,19 @@ func projectCopy(ctx *cmdctx.Ctx) error { if err != nil { return err } - report, inventoryErr := projectcopy.Inventory(ctx.Context, projectcopy.NewTransport(ctx.Auth), scope) + report, copyErr := projectcopy.Copy(ctx.Context, projectcopy.NewTransport(ctx.Auth), scope, cmdctx.GetBool(ctx.FlagValues, "apply")) if err := writeProjectCopyReport(ctx, report); err != nil { return err } - return inventoryErr + return copyErr } func projectCopyScope(ctx *cmdctx.Ctx) (projectcopy.Scope, error) { - if cmdctx.GetBool(ctx.FlagValues, "apply") || (ctx.ProvidedFlags["dry-run"] && !cmdctx.GetBool(ctx.FlagValues, "dry-run")) { - return projectcopy.Scope{}, errors.New("apply unavailable: this is PARTIAL read-only secret planning") + if ctx.ProvidedFlags["dry-run"] && !cmdctx.GetBool(ctx.FlagValues, "dry-run") && !cmdctx.GetBool(ctx.FlagValues, "apply") { + return projectcopy.Scope{}, errors.New("pass --apply to copy; --dry-run=false does not write") } - if cmdctx.GetString(ctx.FlagValues, "resources") != "secret" { - return projectcopy.Scope{}, errors.New("select exactly --resources secret; other resources and apply are unavailable") + if cmdctx.GetString(ctx.FlagValues, "resources") != "cd-core" { + return projectcopy.Scope{}, errors.New("select --resources cd-core") } if ctx.Auth == nil { return projectcopy.Scope{}, errors.New("resolved authentication required") @@ -83,6 +83,9 @@ func renderProjectCopyReport(w io.Writer, format string, r projectcopy.Report) e enc.SetIndent("", " ") return enc.Encode(r) } + if r.Coverage == "cd-core" { + return renderCDCoreReport(w, r) + } if _, err := fmt.Fprintf(w, "PARTIAL — read-only secret planning; apply unavailable\nAccount: %s; org: %s; source: %s; destination: %s\nSecret inventory complete: %t\nReadiness: %s\nNOT INVENTORIED: connectors, pipelines and all other project resources\n", r.Scope.Account, r.Scope.Org, r.Scope.Source, r.Scope.Destination, r.InventoryComplete, r.Readiness); err != nil { return err } @@ -93,3 +96,38 @@ func renderProjectCopyReport(w io.Writer, format string, r projectcopy.Report) e } return nil } + +func renderCDCoreReport(w io.Writer, r projectcopy.Report) error { + if _, err := fmt.Fprintf(w, "cd-core %s\nAccount: %s; org: %s; source: %s; destination: %s\nReadiness: %s\n", r.Mode, r.Scope.Account, r.Scope.Org, r.Scope.Source, r.Scope.Destination, r.Readiness); err != nil { + return err + } + for _, item := range r.Results { + if _, err := fmt.Fprintf(w, "%s %s: %s", item.Kind, item.Identifier, item.Action); err != nil { + return err + } + if item.Reason != "" { + if _, err := fmt.Fprintf(w, " — %s", item.Reason); err != nil { + return err + } + } + if _, err := fmt.Fprintln(w); err != nil { + return err + } + } + for _, item := range r.DelegateSelectors { + if _, err := fmt.Fprintf(w, "delegate selector %s: %s — %s\n", item.Identifier, item.Action, item.Reason); err != nil { + return err + } + } + if len(r.SecretsPendingValue) > 0 { + if _, err := fmt.Fprintf(w, "Inline secrets were stored with placeholder value %s. Update each one before running the destination project:\n", projectcopy.InlineSecretPlaceholder); err != nil { + return err + } + for _, id := range r.SecretsPendingValue { + if _, err := fmt.Fprintf(w, "harness update secret %s --org %s --project %s --set value='...'\n", id, r.Scope.Org, r.Scope.Destination); err != nil { + return err + } + } + } + return nil +} diff --git a/modules/platform/project_copy_test.go b/modules/platform/project_copy_test.go index aeaeb3ac..37421d91 100644 --- a/modules/platform/project_copy_test.go +++ b/modules/platform/project_copy_test.go @@ -16,7 +16,7 @@ import ( ) func copyContext() *cmdctx.Ctx { - return &cmdctx.Ctx{Auth: &auth.ResolvedAuth{AccountID: "fixture_account", OrgID: "fixture_org", ProjectID: "ignored_profile_project"}, MigrateFrom: "source", MigrateTo: "destination", FlagValues: map[string]any{"resources": "secret"}, ProvidedFlags: map[string]bool{}} + return &cmdctx.Ctx{Auth: &auth.ResolvedAuth{AccountID: "fixture_account", OrgID: "fixture_org", ProjectID: "ignored_profile_project"}, MigrateFrom: "source", MigrateTo: "destination", FlagValues: map[string]any{"resources": "cd-core"}, ProvidedFlags: map[string]bool{}} } func TestProjectCopyRejectsUnavailableWorkBeforeTransport(t *testing.T) { @@ -24,7 +24,6 @@ func TestProjectCopyRejectsUnavailableWorkBeforeTransport(t *testing.T) { name string modify func(*cmdctx.Ctx) }{ - {"apply", func(c *cmdctx.Ctx) { c.SetFlag("apply", true) }}, {"dry-run disabled", func(c *cmdctx.Ctx) { c.SetFlag("dry-run", false) }}, {"unsupported format", func(c *cmdctx.Ctx) { c.FormatFlags.Format = "yaml" }}, {"mixed resources", func(c *cmdctx.Ctx) { c.SetFlag("resources", "secret,pipeline") }}, @@ -48,6 +47,11 @@ func TestProjectCopyRejectsUnavailableWorkBeforeTransport(t *testing.T) { }) } c := copyContext() + c.SetFlag("apply", true) + if _, err := projectCopyScope(c); err != nil { + t.Fatal(err) + } + c = copyContext() s, err := projectCopyScope(c) if err != nil || s.Source != "source" || s.Destination != "destination" { t.Fatal("profile project replaced explicit locations") diff --git a/modules/platform/projectcopy/copy.go b/modules/platform/projectcopy/copy.go new file mode 100644 index 00000000..597ebf0f --- /dev/null +++ b/modules/platform/projectcopy/copy.go @@ -0,0 +1,1220 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package projectcopy + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + + "go.yaml.in/yaml/v3" +) + +// Copy plans a same-org CD-core copy from scope.Source to scope.Destination. +// apply creates the destination project when it is missing and writes resources. +// Conflicting destination content aborts before any write. +func Copy(ctx context.Context, t *Transport, scope Scope, apply bool) (Report, error) { + c := &copier{ctx: ctx, transport: t, scope: scope, apply: apply, report: NewCopyReport(scope, apply), selectors: map[string]struct{}{}, shared: map[string]struct{}{}} + err := c.run() + return c.report, err +} + +type copier struct { + ctx context.Context + transport *Transport + scope Scope + apply bool + report Report + selectors map[string]struct{} + shared map[string]struct{} + plans []work + conflict bool + blocked bool + envIDs []string + pipelineIDs []string +} + +type work struct { + result Result + write func() error +} + +func (c *copier) run() error { + if err := c.scope.Validate(); err != nil { + return err + } + if err := c.planProject(); err != nil { + return err + } + if err := c.planSecrets(); err != nil { + return err + } + if err := c.planConnectors(); err != nil { + return err + } + if err := c.planYAMLList("service", "/ng/api/servicesV2", "service", "", nil); err != nil { + return err + } + if err := c.planYAMLList("environment", "/ng/api/environmentsV2", "environment", "", nil); err != nil { + return err + } + c.envIDs = c.idsOf("environment", ActionCreate, ActionSkip) + if err := c.planChildren("infrastructure", c.envIDs, c.planInfrastructures); err != nil { + return err + } + if err := c.planChildren("service_override", c.envIDs, c.planOverrides); err != nil { + return err + } + if err := c.planTemplates(); err != nil { + return err + } + if err := c.planPipelines(); err != nil { + return err + } + c.pipelineIDs = c.idsOf("pipeline", ActionCreate, ActionSkip) + if err := c.planChildren("input_set", c.pipelineIDs, c.planInputSets); err != nil { + return err + } + if err := c.planChildren("trigger", c.pipelineIDs, c.planTriggers); err != nil { + return err + } + if err := c.planPolicies(); err != nil { + return err + } + if err := c.planPolicySets(); err != nil { + return err + } + if err := c.planDelegates(); err != nil { + return err + } + c.finishShared() + c.report.InventoryComplete = true + if c.conflict || !c.apply { + for _, item := range c.plans { + c.report.Results = append(c.report.Results, item.result) + } + if c.conflict { + c.report.Readiness = "blocked by conflicts; nothing written" + return errors.New("project copy aborted before any write: destination content differs") + } + if c.blocked { + c.report.Readiness = "plan incomplete: blocked resources will be skipped on apply" + return errors.New("project copy plan incomplete: blocked resources were not included") + } + c.report.Readiness = "plan only; pass --apply to copy" + return nil + } + for _, item := range c.plans { + if item.write == nil { + c.report.Results = append(c.report.Results, item.result) + continue + } + if err := item.write(); err != nil { + item.result.Action = ActionBlocked + item.result.Reason = "create failed" + c.report.Results = append(c.report.Results, item.result) + c.report.Readiness = "copy stopped after a create failure; re-run to continue" + return err + } + c.report.Results = append(c.report.Results, item.result) + } + if c.blocked { + c.report.Readiness = "copied with blocked resources skipped" + return errors.New("project copy incomplete: blocked resources were not copied") + } + c.report.Readiness = "copied" + if len(c.report.SecretsPendingValue) > 0 { + c.report.Readiness = "copied; update inline secrets before running the destination project" + } + return nil +} + +func (c *copier) planProject() error { + source, found, err := c.getObject("/ng/api/projects/"+url.PathEscape(c.scope.Source), c.query("")) + if err != nil { + return err + } + if !found { + return errors.New("source project not found") + } + project, _ := digMap(source, "data", "project") + if project == nil { + project = source + } + _, destFound, err := c.getObject("/ng/api/projects/"+url.PathEscape(c.scope.Destination), c.query("")) + if err != nil { + return err + } + if destFound { + c.keep(Result{Kind: "project", Identifier: c.scope.Destination, Action: ActionSkip, Reason: "destination project already exists; metadata left unchanged"}) + return nil + } + fields := map[string]any{ + "identifier": c.scope.Destination, + "name": c.scope.Destination, + "orgIdentifier": c.scope.Org, + } + if description := stringField(project, "description"); description != "" { + fields["description"] = description + } + if color := stringField(project, "color"); color != "" { + fields["color"] = color + } + if project["tags"] != nil { + fields["tags"] = project["tags"] + } + if project["modules"] != nil { + fields["modules"] = project["modules"] + } + body := map[string]any{"project": fields} + raw, _ := json.Marshal(body) + c.queue(Result{Kind: "project", Identifier: c.scope.Destination, Action: ActionCreate, Reason: "created with destination identifier as the project name"}, func() error { + return c.postJSON("/ng/api/projects", c.query(""), string(raw)) + }) + return nil +} + +func (c *copier) planSecrets() error { + items, err := c.list(http.MethodPost, secretsPath+"/list/secrets", c.query(c.scope.Source), `{"filterType":"Secret"}`, "pageIndex", "pageSize", "secret") + if err != nil { + return err + } + sort.Slice(items, func(i, j int) bool { return stringField(items[i], "identifier") < stringField(items[j], "identifier") }) + for _, item := range items { + raw, _ := json.Marshal(item) + var secret secret + if json.Unmarshal(raw, &secret) != nil || secret.Identifier == "" { + c.block("secret", stringField(item, "identifier"), "unsupported or unproven secret schema") + continue + } + if (secret.Org != "" && secret.Org != c.scope.Org) || (secret.Project != "" && secret.Project != c.scope.Source) { + c.block("secret", secret.Identifier, "secret is outside the source project") + continue + } + id := secret.Identifier + classified := classify(&secret) + switch classified.Capability { + case ReferenceOnly: + spec, err := specObject(secret.Spec, false) + if err != nil { + c.block("secret", id, "reference secret could not be prepared") + continue + } + c.planSecret(id, secret.Name, spec, "external reference copied; value path was not printed", false) + case MappingRequired: + if secret.Type != "SecretText" { + c.block("secret", id, "unsupported secret type") + continue + } + spec, err := specObject(secret.Spec, true) + if err != nil { + c.block("secret", id, "inline secret could not be prepared") + continue + } + c.planSecret(id, secret.Name, spec, "placeholder value "+InlineSecretPlaceholder+"; update before use", true) + default: + c.block("secret", id, "unsupported or unproven secret schema") + } + } + return nil +} + +func (c *copier) planSecret(id, name string, spec map[string]any, reason string, pending bool) { + dest, found, err := c.getObject("/ng/api/v2/secrets/"+url.PathEscape(id), c.query(c.scope.Destination)) + if err != nil { + c.block("secret", id, "destination secret could not be read") + return + } + payload := map[string]any{"secret": map[string]any{ + "identifier": id, "name": name, "orgIdentifier": c.scope.Org, "projectIdentifier": c.scope.Destination, + "type": "SecretText", "spec": spec, + }} + if found { + got, _ := digMap(dest, "data", "secret") + if secretMetaMatches(payload["secret"].(map[string]any), got) { + c.keep(Result{Kind: "secret", Identifier: id, Action: ActionSkip, Reason: "destination secret metadata matches"}) + return + } + c.conflictResult("secret", id) + return + } + raw, _ := json.Marshal(payload) + if pending { + c.report.SecretsPendingValue = append(c.report.SecretsPendingValue, id) + } + c.queue(Result{Kind: "secret", Identifier: id, Action: ActionCreate, Reason: reason}, func() error { + return c.postJSON("/ng/api/v2/secrets", c.query(c.scope.Destination), string(raw)) + }) +} + +func secretMetaMatches(want, got map[string]any) bool { + if got == nil || stringField(got, "name") != stringField(want, "name") || stringField(got, "type") != "SecretText" { + return false + } + wantSpec, _ := want["spec"].(map[string]any) + gotSpec, _ := got["spec"].(map[string]any) + if gotSpec == nil || stringField(gotSpec, "valueType") != stringField(wantSpec, "valueType") { + return false + } + return stringField(gotSpec, "secretManagerIdentifier") == stringField(wantSpec, "secretManagerIdentifier") +} + +func specObject(spec map[string]json.RawMessage, inline bool) (map[string]any, error) { + var manager, kind string + if json.Unmarshal(spec["secretManagerIdentifier"], &manager) != nil || manager == "" { + return nil, errors.New("missing secret manager") + } + if json.Unmarshal(spec["valueType"], &kind) != nil || kind == "" { + return nil, errors.New("missing value type") + } + if inline { + return map[string]any{"type": "SecretText", "valueType": "Inline", "secretManagerIdentifier": manager, "value": InlineSecretPlaceholder}, nil + } + var value string + if json.Unmarshal(spec["value"], &value) != nil || value == "" { + return nil, errors.New("missing reference path") + } + return map[string]any{"type": "SecretText", "valueType": "Reference", "secretManagerIdentifier": manager, "value": value}, nil +} + +func (c *copier) planConnectors() error { + items, err := c.list(http.MethodPost, "/ng/api/connectors/listV2", c.query(c.scope.Source), `{"filterType":"Connector"}`, "pageIndex", "pageSize", "connector") + if err != nil { + return err + } + for _, item := range items { + id := stringField(item, "identifier") + if id == "" { + c.block("connector", "", "connector identifier missing") + continue + } + if isRemote(item) { + c.keep(Result{Kind: "connector", Identifier: id, Action: ActionSkipped, Reason: "git-backed connector skipped"}) + continue + } + if id == "harnessSecretManager" || truthy(item["harnessManaged"]) { + c.keep(Result{Kind: "connector", Identifier: id, Action: ActionSkipped, Reason: "harness-managed connector; not copied"}) + continue + } + if project := stringField(item, "projectIdentifier"); project != "" && project != c.scope.Source { + c.noteShared("connector " + id) + continue + } + source := cleanRoot(item) + c.observe(source) + rewriteTree(source, c.scope.Org, c.scope.Destination, false) + destRaw, found, err := c.getObject("/ng/api/connectors/"+url.PathEscape(id), c.query(c.scope.Destination)) + if err != nil { + return err + } + if found { + dest, _ := digMap(destRaw, "data", "connector") + cleaned := cleanRoot(dest) + rewriteTree(cleaned, c.scope.Org, c.scope.Destination, false) + if canonicalJSON(cleaned) == canonicalJSON(source) { + c.keep(Result{Kind: "connector", Identifier: id, Action: ActionSkip, Reason: "destination matches"}) + continue + } + c.conflictResult("connector", id) + continue + } + body, _ := json.Marshal(map[string]any{"connector": source}) + payload := string(body) + c.queue(Result{Kind: "connector", Identifier: id, Action: ActionCreate}, func() error { + return c.postJSON("/ng/api/connectors", c.query(c.scope.Destination), payload) + }) + } + return nil +} + +func (c *copier) planYAMLList(kind, path, root, parent string, extra url.Values) error { + query := c.query(c.scope.Source) + for key, values := range extra { + for _, value := range values { + query.Set(key, value) + } + } + items, err := c.list(http.MethodGet, path, query, "", "page", "size", root) + if err != nil { + return err + } + for _, item := range items { + id := stringField(item, "identifier") + if id == "" { + c.block(kind, "", kind+" identifier missing") + continue + } + if isRemote(item) { + c.keep(Result{Kind: kind, Identifier: id, Action: ActionSkipped, Reason: "git-backed resource skipped"}) + continue + } + sourceDoc, err := c.yamlFor(kind, id, item, root, extra, c.scope.Source) + if err != nil { + return err + } + if sourceDoc == "" { + c.block(kind, id, "definition missing") + continue + } + rewritten, err := rewriteYAML(sourceDoc, c.scope.Org, c.scope.Destination, false) + if err != nil { + c.block(kind, id, "definition could not be rewritten") + continue + } + c.observeDoc(rewritten) + destDoc, found, err := c.destYAML(kind, id, root, extra) + if err != nil { + return err + } + reportID := id + if parent != "" { + reportID = parent + "/" + id + } + if !found { + doc := rewritten + createPath, createQuery := yamlCreate(kind, id, parent) + c.queue(Result{Kind: kind, Identifier: reportID, Action: ActionCreate}, func() error { + return c.postYAML(createPath, createQuery, doc) + }) + continue + } + destRewritten, err := rewriteYAML(destDoc, c.scope.Org, c.scope.Destination, false) + if err != nil || !sameDocument(rewritten, destRewritten) { + c.conflictResult(kind, reportID) + continue + } + c.keep(Result{Kind: kind, Identifier: reportID, Action: ActionSkip, Reason: "destination matches"}) + } + return nil +} + +func yamlCreate(kind, id, parent string) (string, url.Values) { + switch kind { + case "service": + return "/ng/api/servicesV2", nil + case "environment": + return "/ng/api/environmentsV2", nil + case "infrastructure": + return "/ng/api/infrastructures", nil + default: + return "", nil + } +} + +func (c *copier) yamlFor(kind, id string, listed map[string]any, root string, extra url.Values, project string) (string, error) { + if doc := stringField(listed, "yaml", "yamlPipeline", "inputSetYaml"); doc != "" { + return doc, nil + } + path := yamlGetPath(kind, id) + query := c.query(project) + for key, values := range extra { + for _, value := range values { + query.Set(key, value) + } + } + obj, found, err := c.getObject(path, query) + if err != nil || !found { + if err != nil { + return "", err + } + return entityDocument(listed, root) + } + entity, _ := digMap(obj, "data", root) + if entity == nil { + entity, _ = digMap(obj, "data") + } + if entity == nil { + entity = obj + } + if doc := stringField(entity, "yaml", "yamlPipeline", "inputSetYaml"); doc != "" { + return doc, nil + } + return entityDocument(entity, root) +} + +func (c *copier) destYAML(kind, id, root string, extra url.Values) (string, bool, error) { + obj, found, err := c.getObject(yamlGetPath(kind, id), mergeQuery(c.query(c.scope.Destination), extra)) + if err != nil || !found { + return "", false, err + } + entity, _ := digMap(obj, "data", root) + if entity == nil { + entity, _ = digMap(obj, "data") + } + if doc := stringField(entity, "yaml", "yamlPipeline", "inputSetYaml"); doc != "" { + return doc, true, nil + } + doc, err := entityDocument(entity, root) + return doc, true, err +} + +func yamlGetPath(kind, id string) string { + switch kind { + case "service": + return "/ng/api/servicesV2/" + url.PathEscape(id) + case "environment": + return "/ng/api/environmentsV2/" + url.PathEscape(id) + case "infrastructure": + return "/ng/api/infrastructures/" + url.PathEscape(id) + default: + return "" + } +} + +func entityDocument(entity map[string]any, root string) (string, error) { + if entity == nil { + return "", nil + } + cleaned := cleanRoot(entity) + out, err := yamlMarshal(map[string]any{root: cleaned}) + return out, err +} + +func yamlMarshal(v any) (string, error) { + data, err := json.Marshal(v) + if err != nil { + return "", err + } + var plain any + if err := json.Unmarshal(data, &plain); err != nil { + return "", err + } + out, err := yaml.Marshal(plain) + if err != nil { + return "", err + } + return string(out), nil +} + +func (c *copier) planInfrastructures(env string) error { + return c.planYAMLList("infrastructure", "/ng/api/infrastructures", "infrastructure", env, url.Values{"environmentIdentifier": {env}}) +} + +func (c *copier) planOverrides(env string) error { + items, err := c.list(http.MethodGet, "/ng/api/environmentsV2/serviceOverrides", mergeQuery(c.query(c.scope.Source), url.Values{"environmentIdentifier": {env}}), "", "page", "size", "") + if err != nil { + return err + } + for _, item := range items { + id := stringField(item, "identifier") + if id == "" { + id = env + "/" + stringField(item, "serviceRef", "serviceIdentifier") + } + if isRemote(item) { + c.keep(Result{Kind: "service_override", Identifier: id, Action: ActionSkipped, Reason: "git-backed resource skipped"}) + continue + } + source := cleanRoot(item) + c.observe(source) + rewriteTree(source, c.scope.Org, c.scope.Destination, false) + destRaw, found, err := c.getObject("/ng/api/serviceOverrides/"+url.PathEscape(stringField(item, "identifier")), c.query(c.scope.Destination)) + if err != nil { + return err + } + if found { + dest, _ := digMap(destRaw, "data") + cleaned := cleanRoot(dest) + rewriteTree(cleaned, c.scope.Org, c.scope.Destination, false) + if canonicalJSON(cleaned) == canonicalJSON(source) { + c.keep(Result{Kind: "service_override", Identifier: id, Action: ActionSkip, Reason: "destination matches"}) + continue + } + c.conflictResult("service_override", id) + continue + } + body, _ := json.Marshal(source) + payload := string(body) + c.queue(Result{Kind: "service_override", Identifier: id, Action: ActionCreate}, func() error { + return c.postJSON("/ng/api/serviceOverrides", c.query(c.scope.Destination), payload) + }) + } + return nil +} + +func (c *copier) planTemplates() error { + items, err := c.list(http.MethodPost, "/template/api/templates/list", mergeQuery(c.query(c.scope.Source), url.Values{"templateListType": {"ALL"}}), `{"filterType":"Template"}`, "page", "size", "") + if err != nil { + return err + } + sort.Slice(items, func(i, j int) bool { + if stringField(items[i], "identifier") != stringField(items[j], "identifier") { + return stringField(items[i], "identifier") < stringField(items[j], "identifier") + } + return versionLess(stringField(items[i], "versionLabel", "version"), stringField(items[j], "versionLabel", "version")) + }) + for _, item := range items { + id := stringField(item, "identifier") + version := stringField(item, "versionLabel", "version") + reportID := id + "/" + version + if isRemote(item) { + c.keep(Result{Kind: "template", Identifier: reportID, Action: ActionSkipped, Reason: "git-backed template skipped"}) + continue + } + query := mergeQuery(c.query(c.scope.Source), url.Values{"versionLabel": {version}}) + obj, found, err := c.getObject("/template/api/templates/"+url.PathEscape(id), query) + if err != nil { + return err + } + if !found { + c.block("template", reportID, "template version not found") + continue + } + data, _ := digMap(obj, "data") + doc := stringField(data, "yaml") + if doc == "" { + doc = stringField(obj, "yaml") + } + rewritten, err := rewriteYAML(doc, c.scope.Org, c.scope.Destination, false) + if err != nil || rewritten == "" { + c.block("template", reportID, "template definition missing") + continue + } + c.observeDoc(rewritten) + destObj, destFound, err := c.getObject("/template/api/templates/"+url.PathEscape(id), mergeQuery(c.query(c.scope.Destination), url.Values{"versionLabel": {version}})) + if err != nil { + return err + } + if destFound { + destData, _ := digMap(destObj, "data") + destDoc := stringField(destData, "yaml") + destRewritten, rerr := rewriteYAML(destDoc, c.scope.Org, c.scope.Destination, false) + if rerr != nil || !sameDocument(rewritten, destRewritten) { + c.conflictResult("template", reportID) + continue + } + c.keep(Result{Kind: "template", Identifier: reportID, Action: ActionSkip, Reason: "destination matches"}) + continue + } + stable := truthy(item["stableTemplate"]) || truthy(item["stable"]) + docCopy := rewritten + c.queue(Result{Kind: "template", Identifier: reportID, Action: ActionCreate}, func() error { + if err := c.postYAML("/template/api/templates", c.query(c.scope.Destination), docCopy); err != nil { + return err + } + if !stable { + return nil + } + stablePath := "/template/api/templates/updateStableTemplate/" + url.PathEscape(id) + "/" + url.PathEscape(version) + // The version is already stored. A rejected stable-label call does not roll that back. + _ = c.postJSON(stablePath, c.query(c.scope.Destination), "") + return nil + }) + } + return nil +} + +func (c *copier) planPipelines() error { + items, err := c.list(http.MethodPost, "/pipeline/api/pipelines/list", c.query(c.scope.Source), `{"filterType":"PipelineSetup"}`, "page", "size", "") + if err != nil { + return err + } + for _, item := range items { + id := stringField(item, "identifier") + if isRemote(item) { + c.keep(Result{Kind: "pipeline", Identifier: id, Action: ActionSkipped, Reason: "git-backed pipeline skipped"}) + continue + } + doc, found, err := c.pipelineYAML(id, c.scope.Source) + if err != nil { + return err + } + if !found || doc == "" { + c.block("pipeline", id, "pipeline definition missing") + continue + } + rewritten, err := rewriteYAML(doc, c.scope.Org, c.scope.Destination, false) + if err != nil { + c.block("pipeline", id, "pipeline definition could not be rewritten") + continue + } + c.observeDoc(rewritten) + destDoc, destFound, err := c.pipelineYAML(id, c.scope.Destination) + if err != nil { + return err + } + if !destFound { + body := rewritten + c.queue(Result{Kind: "pipeline", Identifier: id, Action: ActionCreate}, func() error { + return c.postYAML("/pipeline/api/pipelines/v2", c.query(c.scope.Destination), body) + }) + continue + } + destRewritten, rerr := rewriteYAML(destDoc, c.scope.Org, c.scope.Destination, false) + if rerr != nil || !sameDocument(rewritten, destRewritten) { + c.conflictResult("pipeline", id) + continue + } + c.keep(Result{Kind: "pipeline", Identifier: id, Action: ActionSkip, Reason: "destination matches"}) + } + return nil +} + +func (c *copier) pipelineYAML(id, project string) (string, bool, error) { + obj, found, err := c.getObject("/pipeline/api/pipelines/"+url.PathEscape(id), c.query(project)) + if err != nil || !found { + return "", false, err + } + data, _ := digMap(obj, "data") + doc := stringField(data, "yamlPipeline", "yaml") + if doc == "" { + doc = stringField(obj, "yamlPipeline", "yaml") + } + return doc, doc != "", nil +} + +func (c *copier) planInputSets(pipeline string) error { + return c.planPipelineDocs("input_set", pipeline, "/pipeline/api/inputSets", "inputSetYaml", false) +} + +func (c *copier) planTriggers(pipeline string) error { + return c.planPipelineDocs("trigger", pipeline, "/pipeline/api/triggers", "yaml", true) +} + +func (c *copier) planPipelineDocs(kind, pipeline, path, yamlKey string, disable bool) error { + queryKey := "pipelineIdentifier" + if kind == "trigger" { + queryKey = "targetIdentifier" + } + page, size := "pageIndex", "pageSize" + if kind == "trigger" { + page, size = "page", "size" + } + items, err := c.list(http.MethodGet, path, mergeQuery(c.query(c.scope.Source), url.Values{queryKey: {pipeline}}), "", page, size, "") + if err != nil { + return err + } + for _, item := range items { + id := stringField(item, "identifier") + reportID := pipeline + "/" + id + if isRemote(item) { + c.keep(Result{Kind: kind, Identifier: reportID, Action: ActionSkipped, Reason: "git-backed resource skipped"}) + continue + } + doc := stringField(item, yamlKey, "yaml", "inputSetYaml") + if doc == "" { + obj, found, err := c.getObject(path+"/"+url.PathEscape(id), mergeQuery(c.query(c.scope.Source), url.Values{queryKey: {pipeline}})) + if err != nil { + return err + } + if !found { + c.block(kind, reportID, "definition missing") + continue + } + data, _ := digMap(obj, "data") + doc = stringField(data, yamlKey, "yaml", "inputSetYaml") + } + rewritten, err := rewriteYAML(doc, c.scope.Org, c.scope.Destination, disable) + if err != nil || rewritten == "" { + c.block(kind, reportID, "definition could not be rewritten") + continue + } + c.observeDoc(rewritten) + destObj, destFound, err := c.getObject(path+"/"+url.PathEscape(id), mergeQuery(c.query(c.scope.Destination), url.Values{queryKey: {pipeline}})) + if err != nil { + return err + } + if destFound { + destData, _ := digMap(destObj, "data") + destDoc := stringField(destData, yamlKey, "yaml", "inputSetYaml") + destRewritten, rerr := rewriteYAML(destDoc, c.scope.Org, c.scope.Destination, disable) + if rerr != nil || !sameDocument(rewritten, destRewritten) { + c.conflictResult(kind, reportID) + continue + } + c.keep(Result{Kind: kind, Identifier: reportID, Action: ActionSkip, Reason: "destination matches"}) + continue + } + body := rewritten + reason := "" + if disable { + reason = "created disabled" + } + c.queue(Result{Kind: kind, Identifier: reportID, Action: ActionCreate, Reason: reason}, func() error { + return c.postYAML(path, mergeQuery(c.query(c.scope.Destination), url.Values{queryKey: {pipeline}}), body) + }) + } + return nil +} + +func (c *copier) planPolicies() error { + return c.planGovernance("policy", "/pm/api/v1/policies", func(item map[string]any) (map[string]any, string) { + id := stringField(item, "identifier") + return map[string]any{"identifier": id, "name": firstNonEmpty(stringField(item, "name"), id), "rego": stringField(item, "rego")}, id + }) +} + +func (c *copier) planPolicySets() error { + return c.planGovernance("policy_set", "/pm/api/v1/policysets", func(item map[string]any) (map[string]any, string) { + id := stringField(item, "identifier") + body := map[string]any{ + "identifier": id, "name": firstNonEmpty(stringField(item, "name"), id), + "type": stringField(item, "type"), "action": stringField(item, "action"), + "enabled": item["enabled"], "policies": item["policies"], + } + return body, id + }) +} + +func (c *copier) planGovernance(kind, path string, bodyOf func(map[string]any) (map[string]any, string)) error { + items, err := c.list(http.MethodGet, path, c.query(c.scope.Source), "", "page", "per_page", "") + if err != nil { + return err + } + for _, item := range items { + if project := stringField(item, "projectIdentifier", "project_id"); project != "" && project != c.scope.Source { + c.noteShared(kind + " " + stringField(item, "identifier")) + continue + } + if regoMissing(kind, item) { + full, found, err := c.getObject(path+"/"+url.PathEscape(stringField(item, "identifier")), c.query(c.scope.Source)) + if err != nil { + return err + } + if found { + if data, ok := digMap(full, "data"); ok { + item = data + } else { + item = full + } + } + } + body, id := bodyOf(item) + if id == "" { + c.block(kind, "", kind+" identifier missing") + continue + } + dest, found, err := c.getObject(path+"/"+url.PathEscape(id), c.query(c.scope.Destination)) + if err != nil { + return err + } + if found { + got := dest + if data, ok := digMap(dest, "data"); ok { + got = data + } + gotBody, _ := bodyOf(got) + if canonicalJSON(gotBody) == canonicalJSON(body) { + c.keep(Result{Kind: kind, Identifier: id, Action: ActionSkip, Reason: "destination matches"}) + continue + } + c.conflictResult(kind, id) + continue + } + raw, _ := json.Marshal(body) + payload := string(raw) + c.queue(Result{Kind: kind, Identifier: id, Action: ActionCreate}, func() error { + return c.postJSON(path, c.query(c.scope.Destination), payload) + }) + } + return nil +} + +func regoMissing(kind string, item map[string]any) bool { + if kind != "policy" { + return item["policies"] == nil + } + return stringField(item, "rego") == "" +} + +func (c *copier) planDelegates() error { + if len(c.selectors) == 0 { + return nil + } + items, err := c.list(http.MethodPost, "/ng/api/delegate-setup/listDelegates", c.query(""), `{"filterType":"Delegate"}`, "page", "size", "") + if err != nil { + return err + } + names := make([]string, 0, len(c.selectors)) + for name := range c.selectors { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + matched := "" + for _, item := range items { + if !delegateConnected(item) || !delegateMatches(item, name) { + continue + } + matched = firstNonEmpty(stringField(item, "groupName"), stringField(item, "delegateGroupIdentifier")) + break + } + result := Result{Kind: "delegate", Identifier: name, Action: ActionShared, Reason: "no connected delegate matches this selector"} + if matched != "" { + result.Reason = "matched connected delegate " + matched + "; delegates are not copied" + } + c.report.DelegateSelectors = append(c.report.DelegateSelectors, result) + } + return nil +} + +func delegateConnected(item map[string]any) bool { + return strings.Contains(strings.ToLower(stringField(item, "connectivityStatus", "status")), "connected") +} + +func delegateMatches(item map[string]any, selector string) bool { + if stringField(item, "groupName", "name", "delegateGroupIdentifier") == selector { + return true + } + switch tags := item["tags"].(type) { + case []any: + for _, tag := range tags { + switch value := tag.(type) { + case string: + if value == selector { + return true + } + case map[string]any: + if stringField(value, "key", "name", "value") == selector { + return true + } + } + } + } + return false +} + +func (c *copier) planChildren(kind string, parents []string, fn func(string) error) error { + for _, parent := range parents { + if err := fn(parent); err != nil { + return err + } + } + return nil +} + +func (c *copier) idsOf(kind string, actions ...Action) []string { + want := map[Action]bool{} + for _, action := range actions { + want[action] = true + } + var ids []string + seen := map[string]bool{} + consider := func(result Result) { + if result.Kind != kind || !want[result.Action] || seen[result.Identifier] { + return + } + seen[result.Identifier] = true + ids = append(ids, result.Identifier) + } + for _, item := range c.report.Results { + consider(item) + } + for _, item := range c.plans { + consider(item.result) + } + return ids +} + +func (c *copier) queue(result Result, write func() error) { + c.plans = append(c.plans, work{result: result, write: write}) +} + +func (c *copier) keep(result Result) { + c.report.Results = append(c.report.Results, result) +} + +func (c *copier) block(kind, id, reason string) { + c.blocked = true + c.keep(Result{Kind: kind, Identifier: id, Action: ActionBlocked, Reason: reason}) +} + +func (c *copier) conflictResult(kind, id string) { + c.conflict = true + c.keep(Result{Kind: kind, Identifier: id, Action: ActionConflict, Reason: "destination content differs"}) +} + +func (c *copier) noteShared(id string) { + c.shared[id] = struct{}{} +} + +func (c *copier) finishShared() { + ids := make([]string, 0, len(c.shared)) + for id := range c.shared { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + c.report.Results = append(c.report.Results, Result{Kind: "reference", Identifier: id, Action: ActionShared, Reason: "org or account reference; not copied"}) + } +} + +func (c *copier) observe(v any) { + walk(v, func(key string, value any) { + if key == "delegateSelectors" { + if items, ok := asSlice(value); ok { + for _, item := range items { + if s, ok := item.(string); ok && s != "" { + c.selectors[s] = struct{}{} + } + } + } + } + if s, ok := value.(string); ok && scopedRef.MatchString(s) { + c.shared[s] = struct{}{} + } + }) +} + +func (c *copier) observeDoc(doc string) { + var node any + if yaml.Unmarshal([]byte(doc), &node) != nil { + return + } + c.observe(yamlToPlain(node)) +} + +func (c *copier) query(project string) url.Values { + q := url.Values{"accountIdentifier": {c.scope.Account}, "orgIdentifier": {c.scope.Org}} + if project != "" { + q.Set("projectIdentifier", project) + } + return q +} + +func mergeQuery(base, extra url.Values) url.Values { + out := url.Values{} + for key, values := range base { + for _, value := range values { + out.Add(key, value) + } + } + for key, values := range extra { + for _, value := range values { + out.Set(key, value) + } + } + return out +} + +func (c *copier) getObject(path string, query url.Values) (map[string]any, bool, error) { + status, body, err := c.transport.exchange(c.ctx, http.MethodGet, path, query, "", "") + if err != nil { + return nil, false, err + } + if isNotFound(status, body) { + return nil, false, nil + } + if status != http.StatusOK { + return nil, false, fmt.Errorf("project copy read failed: status %d", status) + } + if len(body) == 0 { + return nil, false, errors.New("project copy read returned an empty body") + } + var raw any + if err := json.Unmarshal(body, &raw); err != nil { + return nil, false, errors.New("malformed project copy response") + } + obj, ok := asMap(raw) + if !ok { + return nil, false, errors.New("malformed project copy response") + } + if statusField := stringField(obj, "status"); statusField != "" && !strings.EqualFold(statusField, "SUCCESS") { + if isNotFound(status, body) { + return nil, false, nil + } + return nil, false, errors.New("project copy read failed") + } + return obj, true, nil +} + +func (c *copier) postJSON(path string, query url.Values, body string) error { + method := http.MethodPost + if strings.Contains(path, "updateStableTemplate") { + method = http.MethodPut + } + return c.write(method, path, query, body, "application/json") +} + +func (c *copier) postYAML(path string, query url.Values, body string) error { + if query == nil { + query = c.query(c.scope.Destination) + } + return c.write(http.MethodPost, path, query, body, "application/yaml") +} + +func (c *copier) write(method, path string, query url.Values, body, contentType string) error { + status, _, err := c.transport.exchange(c.ctx, method, path, query, body, contentType) + if err != nil { + return err + } + if status < 200 || status >= 300 { + return fmt.Errorf("project copy write failed: status %d", status) + } + return nil +} + +func (c *copier) list(method, path string, query url.Values, body, pageParam, sizeParam, wrap string) ([]map[string]any, error) { + var all []map[string]any + seen := map[string]bool{} + for page := 0; page < 1000; page++ { + q := mergeQuery(query, url.Values{pageParam: {strconv.Itoa(page)}, sizeParam: {"100"}}) + status, data, err := c.transport.exchange(c.ctx, method, path, q, body, "application/json") + if err != nil { + return nil, err + } + if status != http.StatusOK { + if page > 0 && (status == http.StatusBadRequest || status == http.StatusNotFound) { + return all, nil + } + return nil, fmt.Errorf("project copy list failed: status %d", status) + } + items, totalPages, err := extractItems(data) + if err != nil { + return nil, err + } + if wrap != "" { + unwrapped := make([]map[string]any, 0, len(items)) + for _, item := range items { + if inner, ok := asMap(item[wrap]); ok { + unwrapped = append(unwrapped, inner) + continue + } + unwrapped = append(unwrapped, item) + } + items = unwrapped + } + fresh := 0 + for _, item := range items { + id := stringField(item, "identifier") + version := stringField(item, "versionLabel", "version") + key := id + "/" + version + if id == "" { + key = canonicalJSON(item) + } + if seen[key] { + continue + } + seen[key] = true + fresh++ + all = append(all, item) + } + if len(items) == 0 || len(items) < 100 || (totalPages > 0 && page+1 >= totalPages) || fresh == 0 { + return all, nil + } + if len(all) > 100000 { + return nil, errors.New("project copy list exceeded 100000 items") + } + } + return nil, errors.New("project copy list exceeded page limit") +} + +func extractItems(body []byte) ([]map[string]any, int, error) { + if len(body) == 0 { + return nil, 0, errors.New("project copy list returned an empty body") + } + var top any + if err := json.Unmarshal(body, &top); err != nil { + return nil, 0, errors.New("malformed project copy list") + } + switch node := top.(type) { + case []any: + return mapsOf(node), 1, nil + case map[string]any: + if !strings.EqualFold(stringField(node, "status"), "") && !strings.EqualFold(stringField(node, "status"), "SUCCESS") && stringField(node, "status") != "" { + if !strings.EqualFold(stringField(node, "status"), "SUCCESS") { + return nil, 0, errors.New("project copy list failed") + } + } + data := node + if inner, ok := asMap(node["data"]); ok { + data = inner + } + for _, key := range []string{"content", "policies", "policy_sets", "policysets", "resource"} { + if items, ok := asSlice(data[key]); ok { + return mapsOf(items), intFrom(data["totalPages"]), nil + } + if items, ok := asSlice(node[key]); ok { + return mapsOf(items), intFrom(node["totalPages"]), nil + } + } + if intFrom(data["totalItems"]) == 0 && intFrom(data["totalElements"]) == 0 && data["content"] == nil && node["resource"] == nil { + return nil, intFrom(data["totalPages"]), nil + } + return nil, 0, errors.New("unrecognized project copy list") + default: + return nil, 0, errors.New("unrecognized project copy list") + } +} + +func mapsOf(items []any) []map[string]any { + out := make([]map[string]any, 0, len(items)) + for _, item := range items { + if m, ok := asMap(item); ok { + out = append(out, m) + } + } + return out +} + +func digMap(obj map[string]any, keys ...string) (map[string]any, bool) { + var current any = obj + for _, key := range keys { + m, ok := asMap(current) + if !ok { + return nil, false + } + current = m[key] + } + return asMap(current) +} + +func isNotFound(status int, body []byte) bool { + if status == http.StatusNotFound { + return true + } + text := strings.ToUpper(string(body)) + return strings.Contains(text, "NOT_FOUND") || strings.Contains(text, "DOES NOT EXIST") || strings.Contains(text, "NOT FOUND") +} + +func intFrom(v any) int { + switch n := v.(type) { + case float64: + return int(n) + case int: + return n + default: + return 0 + } +} + +func truthy(v any) bool { + switch n := v.(type) { + case bool: + return n + case string: + return strings.EqualFold(n, "true") + default: + return false + } +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if value != "" { + return value + } + } + return "" +} + +func versionLess(a, b string) bool { + ai, aok := versionNum(a) + bi, bok := versionNum(b) + if aok && bok && ai != bi { + return ai < bi + } + return a < b +} + +func versionNum(s string) (int, bool) { + s = strings.TrimPrefix(strings.TrimPrefix(s, "v"), "V") + n, err := strconv.Atoi(s) + return n, err == nil +} diff --git a/modules/platform/projectcopy/copy_test.go b/modules/platform/projectcopy/copy_test.go new file mode 100644 index 00000000..7a5deed7 --- /dev/null +++ b/modules/platform/projectcopy/copy_test.go @@ -0,0 +1,371 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package projectcopy + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" +) + +func TestCopyAppliesCDCoreAndSkipsIdenticalRerun(t *testing.T) { + api := newCopyAPI(false) + report, err := Copy(context.Background(), api.transport(), testScope, true) + if err != nil { + t.Fatalf("%v\n%s", err, strings.Join(api.seen, "\n")) + } + if !report.InventoryComplete || report.Readiness == "" { + t.Fatalf("readiness %q", report.Readiness) + } + raw, _ := json.Marshal(report) + for _, leaked := range []string{"SUPER_SECRET", "vault/path#key"} { + if strings.Contains(string(raw), leaked) { + t.Fatalf("report leaked %s", leaked) + } + } + if !containsResult(report, "pipeline", "gitpipe", ActionSkipped) { + t.Fatal("git-backed pipeline was not skipped") + } + if !containsResult(report, "reference", "account.shared_connector", ActionShared) { + t.Fatal("account connector was copied instead of reported") + } + if len(report.DelegateSelectors) != 1 || !strings.Contains(report.DelegateSelectors[0].Reason, "harness-delegate") { + t.Fatalf("delegate check %#v", report.DelegateSelectors) + } + var secretBody, triggerBody, projectBody string + for _, call := range api.mutating { + switch { + case strings.Contains(call.body, "db_password"): + secretBody = call.body + case strings.Contains(call.path, "/triggers"): + triggerBody = call.body + case call.path == "/ng/api/projects": + projectBody = call.body + } + } + if !strings.Contains(secretBody, InlineSecretPlaceholder) || strings.Contains(secretBody, "SUPER_SECRET") { + t.Fatalf("inline secret body = %s", secretBody) + } + if !strings.Contains(triggerBody, "enabled: false") { + t.Fatalf("trigger body = %s", triggerBody) + } + if !strings.Contains(projectBody, `"identifier":"destination"`) || !strings.Contains(projectBody, `"name":"destination"`) || strings.Contains(projectBody, `"name":"Source"`) || !strings.Contains(projectBody, "CD") { + t.Fatalf("project body = %s", projectBody) + } + for _, call := range api.mutating { + if strings.Contains(call.path, "delegate") { + t.Fatal("delegate was created") + } + } + before := len(api.mutating) + again, err := Copy(context.Background(), api.transport(), testScope, true) + if err != nil { + t.Fatalf("%v\n%s", err, strings.Join(api.seen, "\n")) + } + if len(api.mutating) != before { + t.Fatalf("rerun wrote %d extra resources", len(api.mutating)-before) + } + if !containsResult(again, "secret", "db_password", ActionSkip) || !containsResult(again, "pipeline", "deploy", ActionSkip) { + t.Fatal("identical rerun did not skip") + } +} + +func TestCopyPlanDoesNotWrite(t *testing.T) { + api := newCopyAPI(false) + report, err := Copy(context.Background(), api.transport(), testScope, false) + if err != nil { + t.Fatal(err) + } + if len(api.mutating) != 0 { + t.Fatalf("plan wrote %#v", api.mutating) + } + if !containsResult(report, "secret", "db_password", ActionCreate) || !strings.Contains(strings.Join(report.SecretsPendingValue, ","), "db_password") { + t.Fatal("plan did not include the inline secret") + } +} + +func TestCopyConflictWritesNothing(t *testing.T) { + api := newCopyAPI(true) + report, err := Copy(context.Background(), api.transport(), testScope, true) + if err == nil || !strings.Contains(err.Error(), "nothing written") && !strings.Contains(err.Error(), "differs") { + t.Fatalf("err=%v", err) + } + if len(api.mutating) != 0 { + t.Fatalf("conflict wrote %#v", api.mutating) + } + if !containsResult(report, "pipeline", "deploy", ActionConflict) { + t.Fatal("conflict missing from report") + } +} + +func TestCopyAcceptsLiveInlineSecretSchema(t *testing.T) { + s := &secret{Identifier: "github-pat", Name: "github-pat", Org: testScope.Org, Project: testScope.Source, Type: "SecretText", Spec: map[string]json.RawMessage{ + "secretManagerIdentifier": json.RawMessage(`"harnessSecretManager"`), + "valueType": json.RawMessage(`"Inline"`), + "value": json.RawMessage(`null`), + "additionalMetadata": json.RawMessage(`null`), + }} + if classify(s).Capability != MappingRequired { + t.Fatal(classify(s)) + } +} + +func TestRewriteDisablesTriggersAndRewritesProject(t *testing.T) { + doc, err := rewriteYAML("trigger:\n identifier: push\n enabled: true\n pipelineIdentifier: deploy\n projectIdentifier: source\n", testScope.Org, testScope.Destination, true) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(doc, "projectIdentifier: "+testScope.Destination) || !strings.Contains(doc, "enabled: false") || strings.Contains(doc, "projectIdentifier: source") { + t.Fatal(doc) + } +} + +func containsResult(report Report, kind, id string, action Action) bool { + for _, item := range report.Results { + if item.Kind == kind && item.Identifier == id && item.Action == action { + return true + } + } + return false +} + +type copyCall struct{ method, path, body, project string } + +type copyAPI struct { + conflict bool + mutating []copyCall + stored map[string]string + seen []string +} + +func newCopyAPI(conflict bool) *copyAPI { + return ©API{conflict: conflict, stored: map[string]string{}} +} + +func (a *copyAPI) transport() *Transport { + return fakeTransport(func(r *http.Request) (*http.Response, error) { + var body []byte + if r.Body != nil { + body, _ = io.ReadAll(r.Body) + } + path := strings.TrimPrefix(r.URL.Path, "/gateway") + project := r.URL.Query().Get("projectIdentifier") + a.seen = append(a.seen, r.Method+" "+path+" project="+project) + if r.Method == http.MethodPost || r.Method == http.MethodPut { + if !strings.Contains(path, "/list") { + call := copyCall{method: r.Method, path: path, body: string(body), project: project} + a.mutating = append(a.mutating, call) + a.stored[storeKey(call)] = string(body) + } + } + return response(a.serve(r.Method, path, project, string(body))), nil + }) +} + +func (a *copyAPI) serve(method, path, project, body string) (int, string) { + switch { + case path == "/ng/api/v2/secrets/list/secrets": + if project != testScope.Source { + return 200, emptySecretPage() + } + return 200, sourceSecrets() + case strings.HasPrefix(path, "/ng/api/v2/secrets/") && method == http.MethodGet: + return a.storedSecret(project, strings.TrimPrefix(path, "/ng/api/v2/secrets/")) + case path == "/ng/api/projects/"+testScope.Source: + return 200, `{"status":"SUCCESS","data":{"project":{"identifier":"source","name":"Source","orgIdentifier":"fixture_org","description":"demo","color":"#004fc4","modules":["CD"]}}}` + case path == "/ng/api/projects/"+testScope.Destination && method == http.MethodGet: + if _, ok := a.stored[http.MethodPost+" "+"/ng/api/projects"+" "+""]; ok || a.conflict { + return 200, `{"status":"SUCCESS","data":{"project":{"identifier":"destination","name":"Source","orgIdentifier":"fixture_org"}}}` + } + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + case path == "/ng/api/connectors/listV2": + if project != testScope.Source { + return 200, emptyPage() + } + return 200, `{"status":"SUCCESS","data":{"content":[{"connector":{"identifier":"github","name":"github","type":"Github","orgIdentifier":"fixture_org","projectIdentifier":"source","spec":{"delegateSelectors":["cd-delegate"],"connectorRef":"account.shared_connector"}}}],"totalPages":1,"totalItems":1}}` + case strings.HasPrefix(path, "/ng/api/connectors/") && method == http.MethodGet: + return a.storedJSON(http.MethodPost+" /ng/api/connectors "+project, "connector") + case path == "/ng/api/servicesV2" && method == http.MethodGet: + return a.yamlList(project, "service", "svc", "service:\n identifier: svc\n name: svc\n orgIdentifier: fixture_org\n projectIdentifier: source\n") + case strings.HasPrefix(path, "/ng/api/servicesV2/") && method == http.MethodGet: + return a.storedYAML(http.MethodPost+" /ng/api/servicesV2 "+project, "service") + case path == "/ng/api/environmentsV2" && method == http.MethodGet: + return a.yamlList(project, "environment", "prod", "environment:\n identifier: prod\n name: prod\n orgIdentifier: fixture_org\n projectIdentifier: source\n") + case strings.HasPrefix(path, "/ng/api/environmentsV2/") && path != "/ng/api/environmentsV2/serviceOverrides" && method == http.MethodGet: + return a.storedYAML(http.MethodPost+" /ng/api/environmentsV2 "+project, "environment") + case path == "/ng/api/infrastructures" || path == "/ng/api/environmentsV2/serviceOverrides": + return 200, emptyPage() + case path == "/template/api/templates/list": + if project != testScope.Source { + return 200, emptyPage() + } + return 200, `{"status":"SUCCESS","data":{"content":[{"identifier":"step","name":"step","versionLabel":"v1","stableTemplate":true,"storeType":"INLINE"}],"totalPages":1,"totalItems":1}}` + case strings.HasPrefix(path, "/template/api/templates/") && method == http.MethodGet: + return a.template(project) + case path == "/pipeline/api/pipelines/list": + if project != testScope.Source { + return 200, emptyPage() + } + return 200, `{"status":"SUCCESS","data":{"content":[{"identifier":"deploy","name":"deploy","storeType":"INLINE"},{"identifier":"gitpipe","name":"gitpipe","storeType":"REMOTE"}],"totalPages":1,"totalItems":2}}` + case path == "/pipeline/api/pipelines/deploy" && method == http.MethodGet: + if project == testScope.Destination && a.conflict { + return 200, `{"status":"SUCCESS","data":{"yamlPipeline":"pipeline:\n identifier: deploy\n name: other\n orgIdentifier: fixture_org\n projectIdentifier: destination\n"}}` + } + if project == testScope.Destination { + if doc, ok := a.stored[http.MethodPost+" /pipeline/api/pipelines/v2 "+project]; ok { + return 200, `{"status":"SUCCESS","data":{"yamlPipeline":` + jsonString(doc) + `}}` + } + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } + return 200, `{"status":"SUCCESS","data":{"yamlPipeline":"pipeline:\n identifier: deploy\n name: deploy\n orgIdentifier: fixture_org\n projectIdentifier: source\n"}}` + case path == "/pipeline/api/inputSets" && method == http.MethodGet: + return a.docList(project, "inputSet:\n identifier: inputs\n name: inputs\n orgIdentifier: fixture_org\n projectIdentifier: source\n pipeline:\n identifier: deploy\n", "inputs") + case path == "/pipeline/api/inputSets/inputs" && method == http.MethodGet: + return a.storedDoc(http.MethodPost+" /pipeline/api/inputSets "+project, "inputSetYaml") + case path == "/pipeline/api/triggers" && method == http.MethodGet: + return a.docList(project, "trigger:\n identifier: push\n name: push\n enabled: true\n pipelineIdentifier: deploy\n orgIdentifier: fixture_org\n projectIdentifier: source\n", "push") + case path == "/pipeline/api/triggers/push" && method == http.MethodGet: + return a.storedDoc(http.MethodPost+" /pipeline/api/triggers "+project, "yaml") + case path == "/pm/api/v1/policies" && method == http.MethodGet: + if project != testScope.Source { + return 200, emptyPage() + } + return 200, `{"status":"SUCCESS","data":{"content":[{"identifier":"deny_prod","name":"deny","rego":"package pipeline","projectIdentifier":"source"}],"totalPages":1,"totalItems":1}}` + case path == "/pm/api/v1/policies/deny_prod" && method == http.MethodGet: + return a.storedGovernance(http.MethodPost + " /pm/api/v1/policies " + project) + case path == "/pm/api/v1/policysets" && method == http.MethodGet: + if project != testScope.Source { + return 200, emptyPage() + } + return 200, `{"status":"SUCCESS","data":{"content":[{"identifier":"on_run","name":"on run","type":"pipeline","action":"onrun","enabled":true,"policies":[{"identifier":"deny_prod"}],"projectIdentifier":"source"}],"totalPages":1,"totalItems":1}}` + case path == "/pm/api/v1/policysets/on_run" && method == http.MethodGet: + return a.storedGovernance(http.MethodPost + " /pm/api/v1/policysets " + project) + case path == "/ng/api/delegate-setup/listDelegates": + return 200, `{"status":"SUCCESS","resource":[{"groupName":"harness-delegate","delegateGroupIdentifier":"del1","connectivityStatus":"connected","tags":["cd-delegate"]}],"totalPages":1}` + case method == http.MethodPost || method == http.MethodPut: + return 200, `{"status":"SUCCESS"}` + default: + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } +} + +func (a *copyAPI) storedSecret(project, id string) (int, string) { + if project == testScope.Source && id == "db_password" { + return 200, `{"status":"SUCCESS","data":{"secret":{"identifier":"db_password","name":"db","type":"SecretText","orgIdentifier":"fixture_org","projectIdentifier":"source","spec":{"type":"SecretText","valueType":"Inline","secretManagerIdentifier":"harnessSecretManager","value":"SUPER_SECRET"}},"updatedAt":17}}` + } + if project == testScope.Source && id == "ref_token" { + return 200, `{"status":"SUCCESS","data":{"secret":{"identifier":"ref_token","name":"ref","type":"SecretText","orgIdentifier":"fixture_org","projectIdentifier":"source","spec":{"type":"SecretText","valueType":"Reference","secretManagerIdentifier":"org.manager","value":"vault/path#key"}},"updatedAt":17}}` + } + raw, ok := a.stored[http.MethodPost+" /ng/api/v2/secrets "+project+" "+id] + if !ok { + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } + var body map[string]any + if json.Unmarshal([]byte(raw), &body) != nil { + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } + data, _ := json.Marshal(map[string]any{"status": "SUCCESS", "data": body}) + return 200, string(data) +} + +func sourceSecrets() string { + return `{"status":"SUCCESS","data":{"totalPages":1,"totalItems":2,"pageItemCount":2,"pageSize":100,"content":[` + + `{"secret":{"identifier":"db_password","name":"db","orgIdentifier":"fixture_org","projectIdentifier":"source","type":"SecretText","spec":{"type":"SecretText","valueType":"Inline","secretManagerIdentifier":"harnessSecretManager","value":"SUPER_SECRET"}},"updatedAt":17},` + + `{"secret":{"identifier":"ref_token","name":"ref","orgIdentifier":"fixture_org","projectIdentifier":"source","type":"SecretText","spec":{"type":"SecretText","valueType":"Reference","secretManagerIdentifier":"org.manager","value":"vault/path#key"}},"updatedAt":18}` + + `]}}` +} + +func (a *copyAPI) yamlList(project, root, id, doc string) (int, string) { + if project != testScope.Source { + return 200, emptyPage() + } + return 200, `{"status":"SUCCESS","data":{"content":[{"` + root + `":{"identifier":"` + id + `","name":"` + id + `","orgIdentifier":"fixture_org","projectIdentifier":"source","yaml":` + jsonString(doc) + `}}],"totalPages":1,"totalItems":1}}` +} + +func (a *copyAPI) storedYAML(key, root string) (int, string) { + doc, ok := a.stored[key] + if !ok { + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } + return 200, `{"status":"SUCCESS","data":{"` + root + `":{"yaml":` + jsonString(doc) + `}}}` +} + +func (a *copyAPI) storedJSON(key, root string) (int, string) { + raw, ok := a.stored[key] + if !ok { + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } + var body map[string]any + if json.Unmarshal([]byte(raw), &body) != nil { + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } + entity, _ := body[root] + data, _ := json.Marshal(map[string]any{"status": "SUCCESS", "data": map[string]any{root: entity}}) + return 200, string(data) +} + +func (a *copyAPI) template(project string) (int, string) { + if project == testScope.Source { + return 200, `{"status":"SUCCESS","data":{"yaml":` + jsonString("template:\n identifier: step\n name: step\n versionLabel: v1\n type: Step\n orgIdentifier: fixture_org\n projectIdentifier: source\n spec: {}\n") + `}}` + } + if doc, ok := a.stored[http.MethodPost+" /template/api/templates "+project]; ok { + return 200, `{"status":"SUCCESS","data":{"yaml":` + jsonString(doc) + `}}` + } + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` +} + +func (a *copyAPI) docList(project, doc, id string) (int, string) { + if project != testScope.Source { + return 200, emptyPage() + } + return 200, `{"status":"SUCCESS","data":{"content":[{"identifier":"` + id + `","name":"` + id + `","storeType":"INLINE","yaml":` + jsonString(doc) + `,"inputSetYaml":` + jsonString(doc) + `}],"totalPages":1,"totalItems":1}}` +} + +func (a *copyAPI) storedDoc(key, field string) (int, string) { + doc, ok := a.stored[key] + if !ok { + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } + data, _ := json.Marshal(map[string]any{"status": "SUCCESS", "data": map[string]any{field: doc, "yaml": doc}}) + return 200, string(data) +} + +func (a *copyAPI) storedGovernance(key string) (int, string) { + raw, ok := a.stored[key] + if !ok { + return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` + } + return 200, `{"status":"SUCCESS","data":` + raw + `}` +} + +func emptyPage() string { + return `{"status":"SUCCESS","data":{"content":[],"totalPages":0,"totalItems":0}}` +} + +func emptySecretPage() string { + return `{"status":"SUCCESS","data":{"totalPages":0,"totalItems":0,"pageItemCount":0,"pageSize":100,"content":[]}}` +} + +func storeKey(call copyCall) string { + key := call.method + " " + call.path + " " + call.project + if call.path == "/ng/api/v2/secrets" { + var body map[string]any + if json.Unmarshal([]byte(call.body), &body) == nil { + if secret, ok := body["secret"].(map[string]any); ok { + if id, ok := secret["identifier"].(string); ok { + return key + " " + id + } + } + } + } + return key +} + +func jsonString(s string) string { + data, _ := json.Marshal(s) + return string(data) +} diff --git a/modules/platform/projectcopy/inventory.go b/modules/platform/projectcopy/inventory.go index 20ad7d52..4d27c51d 100644 --- a/modules/platform/projectcopy/inventory.go +++ b/modules/platform/projectcopy/inventory.go @@ -36,6 +36,7 @@ func (s *secret) UnmarshalJSON(data []byte) error { for key := range fields { switch key { case "identifier", "name", "orgIdentifier", "projectIdentifier", "type", "spec", "description", "tags": + case "createdAt", "lastModifiedAt", "yaml", "live", "draft", "governanceMetadata", "entityValidityDetails": default: s.Unproven = true } @@ -223,16 +224,25 @@ func classify(s *secret) Item { default: return item } - var specType string - if s.Unproven || json.Unmarshal(s.Spec["type"], &specType) != nil || specType != s.Type { + if s.Unproven { return item } + if raw, ok := s.Spec["type"]; ok { + var specType string + if json.Unmarshal(raw, &specType) != nil || specType != s.Type { + return item + } + } if s.Type != "SecretText" { return item } for key, value := range s.Spec { switch key { case "type", "valueType", "secretManagerIdentifier", "value": + case "additionalMetadata": + if string(value) != "null" && string(value) != "{}" { + return item + } case "errorMessageForInvalidYaml": if string(value) != `""` { return item @@ -245,7 +255,7 @@ func classify(s *secret) Item { if json.Unmarshal(s.Spec["valueType"], &kind) != nil || json.Unmarshal(s.Spec["secretManagerIdentifier"], &manager) != nil || manager == "" { return item } - if raw, ok := s.Spec["value"]; ok && (string(raw) == "null" || json.Unmarshal(raw, &value) != nil) { + if raw, ok := s.Spec["value"]; ok && string(raw) != "null" && json.Unmarshal(raw, &value) != nil { return item } managerID := manager diff --git a/modules/platform/projectcopy/inventory_test.go b/modules/platform/projectcopy/inventory_test.go index 3631366a..02067ca0 100644 --- a/modules/platform/projectcopy/inventory_test.go +++ b/modules/platform/projectcopy/inventory_test.go @@ -195,6 +195,9 @@ func TestSecretCapabilities(t *testing.T) { want Capability }{ {"reference", func(*secret) {}, ReferenceOnly}, + {"live inline", func(s *secret) { + s.Spec = map[string]json.RawMessage{"secretManagerIdentifier": json.RawMessage(`"harnessSecretManager"`), "valueType": json.RawMessage(`"Inline"`), "value": json.RawMessage(`null`), "additionalMetadata": json.RawMessage(`null`)} + }, MappingRequired}, {"inline", func(s *secret) { s.Spec["valueType"] = json.RawMessage(`"Inline"`); delete(s.Spec, "value") }, MappingRequired}, {"unknown value type", func(s *secret) { s.Spec["valueType"] = json.RawMessage(`"Unknown"`) }, Blocked}, {"unknown field", func(s *secret) { s.Spec["credentials"] = json.RawMessage(`"` + marker + `"`) }, Blocked}, diff --git a/modules/platform/projectcopy/rewrite.go b/modules/platform/projectcopy/rewrite.go new file mode 100644 index 00000000..f492e7fb --- /dev/null +++ b/modules/platform/projectcopy/rewrite.go @@ -0,0 +1,181 @@ +// Copyright © 2026 Harness Inc. +// SPDX-License-Identifier: Apache-2.0 + +package projectcopy + +import ( + "encoding/json" + "reflect" + "regexp" + "strings" + + "go.yaml.in/yaml/v3" +) + +var scopedRef = regexp.MustCompile(`^(account|org)\.[A-Za-z_][A-Za-z0-9_]{0,127}$`) + +var rootDrop = map[string]bool{ + "createdAt": true, "lastModifiedAt": true, "createdBy": true, "lastModifiedBy": true, + "status": true, "harnessManaged": true, "entityValidityDetails": true, "connectorStats": true, + "gitDetails": true, "isFavorite": true, "isDraft": true, "cacheResponse": true, + "errorMessage": true, "connectorMetaData": true, "governanceMetadata": true, + "yamlVersion": true, "entityValidity": true, +} + +func rewriteYAML(doc, org, project string, disableTriggers bool) (string, error) { + var node any + if err := yaml.Unmarshal([]byte(doc), &node); err != nil { + return "", err + } + node = yamlToPlain(node) + rewriteTree(node, org, project, disableTriggers) + out, err := yaml.Marshal(node) + if err != nil { + return "", err + } + return string(out), nil +} + +func sameDocument(a, b string) bool { + var left, right any + if yaml.Unmarshal([]byte(a), &left) != nil || yaml.Unmarshal([]byte(b), &right) != nil { + return false + } + return reflect.DeepEqual(yamlToPlain(left), yamlToPlain(right)) +} + +func yamlToPlain(v any) any { + switch n := v.(type) { + case map[string]any: + out := make(map[string]any, len(n)) + for k, child := range n { + out[k] = yamlToPlain(child) + } + return out + case map[any]any: + out := make(map[string]any, len(n)) + for k, child := range n { + out[toString(k)] = yamlToPlain(child) + } + return out + case []any: + out := make([]any, len(n)) + for i := range n { + out[i] = yamlToPlain(n[i]) + } + return out + default: + return n + } +} + +func toString(v any) string { + s, _ := v.(string) + return s +} + +func rewriteTree(v any, org, project string, disableTriggers bool) { + switch n := v.(type) { + case map[string]any: + if _, ok := n["projectIdentifier"]; ok { + n["projectIdentifier"] = project + } + if _, ok := n["orgIdentifier"]; ok { + n["orgIdentifier"] = org + } + if disableTriggers { + if _, ok := n["pipelineIdentifier"]; ok { + if _, ok := n["enabled"]; ok { + n["enabled"] = false + } + } + } + for k, child := range n { + if s, ok := child.(string); ok && (k == "yaml" || k == "yamlPipeline" || k == "inputSetYaml") && strings.Contains(s, "projectIdentifier") { + if rewritten, err := rewriteYAML(s, org, project, disableTriggers); err == nil { + n[k] = rewritten + continue + } + } + rewriteTree(child, org, project, disableTriggers) + } + case []any: + for i := range n { + rewriteTree(n[i], org, project, disableTriggers) + } + } +} + +func cleanRoot(obj map[string]any) map[string]any { + cloned := cloneMap(obj) + for key := range rootDrop { + delete(cloned, key) + } + delete(cloned, "yaml") + delete(cloned, "yamlPipeline") + delete(cloned, "inputSetYaml") + return cloned +} + +func cloneMap(obj map[string]any) map[string]any { + data, err := json.Marshal(obj) + if err != nil { + return map[string]any{} + } + var out map[string]any + if json.Unmarshal(data, &out) != nil || out == nil { + return map[string]any{} + } + return out +} + +func canonicalJSON(v any) string { + data, err := json.Marshal(v) + if err != nil { + return "" + } + return string(data) +} + +func walk(v any, fn func(key string, value any)) { + switch n := v.(type) { + case map[string]any: + for k, child := range n { + fn(k, child) + walk(child, fn) + } + case []any: + for _, child := range n { + walk(child, fn) + } + } +} + +func stringField(m map[string]any, keys ...string) string { + for _, key := range keys { + if s, ok := m[key].(string); ok && s != "" { + return s + } + } + return "" +} + +func isRemote(m map[string]any) bool { + if strings.EqualFold(stringField(m, "storeType", "store_type"), "REMOTE") { + return true + } + if git, ok := m["gitDetails"].(map[string]any); ok { + return strings.EqualFold(stringField(git, "storeType"), "REMOTE") + } + return false +} + +func asMap(v any) (map[string]any, bool) { + m, ok := v.(map[string]any) + return m, ok && m != nil +} + +func asSlice(v any) ([]any, bool) { + s, ok := v.([]any) + return s, ok +} diff --git a/modules/platform/projectcopy/transport.go b/modules/platform/projectcopy/transport.go index ec89a81f..938cb215 100644 --- a/modules/platform/projectcopy/transport.go +++ b/modules/platform/projectcopy/transport.go @@ -41,6 +41,79 @@ func wait(ctx context.Context, d time.Duration) error { } } +// exchange performs one scoped API call. Response bodies are returned to the caller and never logged. +// HTTP statuses are returned as-is so callers can tell a missing resource from a transport failure. +func (t *Transport) exchange(ctx context.Context, method, path string, query url.Values, body, contentType string) (int, []byte, error) { + base, err := url.Parse(t.auth.APIUrl) + if err != nil || base.Scheme != "https" || base.Host == "" || base.User != nil || base.RawQuery != "" || base.Fragment != "" { + return 0, nil, errors.New("project copy requires a valid HTTPS API base URL without credentials, query or fragment") + } + base.Path = strings.TrimRight(base.Path, "/") + path + if query != nil { + base.RawQuery = query.Encode() + } + for attempt := 0; attempt < 3; attempt++ { + var reader io.Reader + if body != "" { + reader = strings.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, base.String(), reader) + if err != nil { + return 0, nil, errors.New("cannot prepare project copy request") + } + t.auth.SetAuthHeader(req) + req.Header.Set("Accept", "application/json") + if body != "" { + if contentType == "" { + contentType = "application/json" + } + req.Header.Set("Content-Type", contentType) + } + resp, err := t.http.Do(req) + if err != nil { + if attempt == 2 || ctx.Err() != nil { + return 0, nil, errors.New("project copy request failed") + } + if t.wait(ctx, time.Duration(attempt+1)*time.Second) != nil { + return 0, nil, errors.New("project copy cancelled") + } + continue + } + retry := resp.StatusCode == 429 || resp.StatusCode == 502 || resp.StatusCode == 503 || resp.StatusCode == 504 + if retry && attempt < 2 { + delay := time.Duration(attempt+1) * time.Second + if raw := resp.Header.Get("Retry-After"); raw != "" { + if seconds, e := strconv.Atoi(raw); e == nil && seconds >= 0 { + delay = time.Duration(min(seconds, 11)) * time.Second + } else if date, e := http.ParseTime(raw); e == nil { + delay = max(time.Until(date), 0) + } else { + resp.Body.Close() + return 0, nil, errors.New("project copy retry policy unavailable") + } + } + resp.Body.Close() + if delay > 10*time.Second { + return 0, nil, errors.New("project copy rate limited; retry later") + } + if t.wait(ctx, delay) != nil { + return 0, nil, errors.New("project copy cancelled") + } + continue + } + data, err := io.ReadAll(io.LimitReader(resp.Body, responseLimit+1)) + resp.Body.Close() + if err != nil || len(data) > responseLimit { + return 0, nil, errors.New("project copy response incomplete or too large") + } + if len(data) > 0 && (!json.Valid(data) || !unambiguousJSON(data)) { + return 0, nil, errors.New("malformed project copy response") + } + return resp.StatusCode, data, nil + } + return 0, nil, errors.New("project copy retries exhausted") +} + // The POST below is a documented list operation, never a resource creation. func (t *Transport) read(ctx context.Context, scope Scope, id string, page int, target any) error { base, err := url.Parse(t.auth.APIUrl) diff --git a/modules/platform/projectcopy/types.go b/modules/platform/projectcopy/types.go index 649c5975..6df23b25 100644 --- a/modules/platform/projectcopy/types.go +++ b/modules/platform/projectcopy/types.go @@ -43,17 +43,54 @@ type Item struct { Reason string `json:"reason"` } +type Action string + +const ( + ActionCreate Action = "create" + ActionSkip Action = "skip" + ActionConflict Action = "conflict" + ActionBlocked Action = "blocked" + ActionShared Action = "shared" + ActionSkipped Action = "skipped" +) + +// InlineSecretPlaceholder is the shell value stored for copied inline SecretText. +// The source value is never read or written. Replace it in the destination before running anything. +const InlineSecretPlaceholder = "123456" + +type Result struct { + Kind string `json:"kind"` + Identifier string `json:"identifier"` + Action Action `json:"action"` + Reason string `json:"reason,omitempty"` +} + type Report struct { - Scope Scope `json:"scope"` - Coverage string `json:"coverage"` - Mode string `json:"mode"` - InventoryComplete bool `json:"inventory_complete"` - ApplyAvailable bool `json:"apply_available"` - Readiness string `json:"readiness"` - NotInventoried []string `json:"not_inventoried"` - Secrets []Item `json:"secrets"` + Scope Scope `json:"scope"` + Coverage string `json:"coverage"` + Mode string `json:"mode"` + InventoryComplete bool `json:"inventory_complete"` + ApplyAvailable bool `json:"apply_available"` + Readiness string `json:"readiness"` + NotInventoried []string `json:"not_inventoried"` + Secrets []Item `json:"secrets"` + Results []Result `json:"results,omitempty"` + DelegateSelectors []Result `json:"delegate_selectors,omitempty"` + SecretsPendingValue []string `json:"secrets_pending_value,omitempty"` } func NewReport(s Scope) Report { return Report{Scope: s, Coverage: "PARTIAL", Mode: "read-only planning", Readiness: "NOT ASSESSED; destination not checked or created", NotInventoried: []string{"connectors", "pipelines", "all other project resources"}, Secrets: []Item{}} } + +func NewCopyReport(s Scope, apply bool) Report { + mode, readiness := "plan", "plan only; pass --apply to copy" + if apply { + mode, readiness = "apply", "copying" + } + return Report{ + Scope: s, Coverage: "cd-core", Mode: mode, ApplyAvailable: true, Readiness: readiness, + NotInventoried: []string{"code repositories", "gitops", "feature flags", "executions", "delegate installations"}, + Secrets: []Item{}, + } +} diff --git a/pkg/spec/platform.spec.yaml b/pkg/spec/platform.spec.yaml index 49960728..cdc05fc5 100644 --- a/pkg/spec/platform.spec.yaml +++ b/pkg/spec/platform.spec.yaml @@ -494,13 +494,25 @@ commands: verb: migrate noun: project noun_to: project - short: "PARTIAL read-only secret inventory and capability planning (no apply)" + short: "Copy a project's CD core into another project in the same org" long: | - Inventory only the source project's selected secrets. Requires explicit - source/destination projects and --resources secret. The destination is not - checked or created; connectors, pipelines and other resources are NOT INVENTORIED. - Values, locators and raw definitions are never reported. Apply is unavailable. - Reports support text/JSON and --out to a NEW file only; existing files are never overwritten. + Copy project-scoped CD configuration from --from to --to in one org. + The destination project is created when it does not already exist. + Identical destination resources are skipped. Differing destination + content aborts the copy before any write. + + --resources cd-core copies secrets, connectors, services, environments, + infrastructures, service overrides, templates, pipelines, input sets, + triggers, policies, and policy sets. Triggers are created disabled. + Git-backed entities are skipped. Org and account references are reported + and left in place. Delegate selectors are checked against connected + account delegates; delegates are not copied. + + Inline SecretText values are not read. New inline secrets are stored + with the placeholder value 123456 and must be updated before use. + Reference secrets copy their manager and path. Other secret types are + blocked. The default is a plan; pass --apply to write. + Reports support text/JSON and --out to a NEW file only. handler_type: workflow workflow_id: project_copy migrate_from: @@ -508,18 +520,17 @@ commands: label: Source project identifier migrate_to: presence: required - label: Destination project identifier (not created) + label: Destination project identifier flags: - name: resources required: true - description: "Explicit resource selection: secret only" + description: "Resource set to copy: cd-core" - name: dry-run is_bool: true - description: "Read-only planning (also the default; no apply implementation)" + description: "Plan only. This is the default." - name: apply is_bool: true - hidden: true - description: "Unavailable; rejected before inventory" + description: "Create the destination project if needed and copy resources" - command: list organization verb: list From 3868a05af87c153d32279824d3f8dc9b6ebc879f Mon Sep 17 00:00:00 2001 From: Dewan Ahmed Date: Fri, 23 Oct 2026 21:52:09 -0300 Subject: [PATCH 5/7] fix(platform): post CD resources as NG YAML envelopes Service, environment, and infrastructure creates must send JSON with identity fields and a yaml string. Raw YAML posts return 400 from NG. Co-authored-by: Cursor --- modules/platform/projectcopy/copy.go | 61 +++++++++++++++++++++-- modules/platform/projectcopy/copy_test.go | 20 ++++++++ 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/modules/platform/projectcopy/copy.go b/modules/platform/projectcopy/copy.go index 597ebf0f..f5e4ef88 100644 --- a/modules/platform/projectcopy/copy.go +++ b/modules/platform/projectcopy/copy.go @@ -381,7 +381,7 @@ func (c *copier) planYAMLList(kind, path, root, parent string, extra url.Values) doc := rewritten createPath, createQuery := yamlCreate(kind, id, parent) c.queue(Result{Kind: kind, Identifier: reportID, Action: ActionCreate}, func() error { - return c.postYAML(createPath, createQuery, doc) + return c.postCDYAML(kind, createPath, createQuery, doc) }) continue } @@ -1039,17 +1039,72 @@ func (c *copier) postYAML(path string, query url.Values, body string) error { return c.write(http.MethodPost, path, query, body, "application/yaml") } +// postCDYAML posts service/environment/infrastructure YAML in the NG JSON envelope +// {identifier, name, orgIdentifier, projectIdentifier, yaml: ""}. +func (c *copier) postCDYAML(kind, path string, extra url.Values, doc string) error { + env, err := cdEnvelope(kind, doc) + if err != nil { + return err + } + raw, err := json.Marshal(env) + if err != nil { + return err + } + query := c.query(c.scope.Destination) + if extra != nil { + query = mergeQuery(query, extra) + } + return c.postJSON(path, query, string(raw)) +} + +func cdEnvelope(wrapper, rawBody string) (map[string]any, error) { + var parsed map[string]any + if err := yaml.Unmarshal([]byte(rawBody), &parsed); err != nil || parsed == nil { + return nil, errors.New("definition could not be wrapped for create") + } + plain, _ := yamlToPlain(parsed).(map[string]any) + if plain == nil { + return nil, errors.New("definition could not be wrapped for create") + } + inner := plain + if wrapped, ok := plain[wrapper].(map[string]any); ok { + inner = wrapped + } + env := map[string]any{"yaml": rawBody} + for _, key := range []string{"identifier", "name", "orgIdentifier", "projectIdentifier", "description", "tags", "type", "environmentRef"} { + if value, ok := inner[key]; ok { + env[key] = value + } + } + return env, nil +} + func (c *copier) write(method, path string, query url.Values, body, contentType string) error { - status, _, err := c.transport.exchange(c.ctx, method, path, query, body, contentType) + status, resp, err := c.transport.exchange(c.ctx, method, path, query, body, contentType) if err != nil { return err } if status < 200 || status >= 300 { - return fmt.Errorf("project copy write failed: status %d", status) + return writeFailure(status, resp) } return nil } +func writeFailure(status int, body []byte) error { + msg := fmt.Sprintf("project copy write failed: status %d", status) + var obj map[string]any + if json.Unmarshal(body, &obj) != nil { + return errors.New(msg) + } + if code := stringField(obj, "code"); code != "" && len(code) < 80 { + msg += " " + code + } + if message := stringField(obj, "message"); message != "" && len(message) < 240 { + msg += ": " + message + } + return errors.New(msg) +} + func (c *copier) list(method, path string, query url.Values, body, pageParam, sizeParam, wrap string) ([]map[string]any, error) { var all []map[string]any seen := map[string]bool{} diff --git a/modules/platform/projectcopy/copy_test.go b/modules/platform/projectcopy/copy_test.go index 7a5deed7..c013b0f1 100644 --- a/modules/platform/projectcopy/copy_test.go +++ b/modules/platform/projectcopy/copy_test.go @@ -114,6 +114,20 @@ func TestCopyAcceptsLiveInlineSecretSchema(t *testing.T) { } } +func TestCDEnvelopeWrapsServiceYAML(t *testing.T) { + env, err := cdEnvelope("service", "service:\n identifier: demo_app\n name: demo-app\n orgIdentifier: fixture_org\n projectIdentifier: destination\n") + if err != nil { + t.Fatal(err) + } + if env["identifier"] != "demo_app" || env["projectIdentifier"] != "destination" { + t.Fatalf("%v", env) + } + yamlField, _ := env["yaml"].(string) + if !strings.Contains(yamlField, "identifier: demo_app") { + t.Fatal(yamlField) + } +} + func TestRewriteDisablesTriggersAndRewritesProject(t *testing.T) { doc, err := rewriteYAML("trigger:\n identifier: push\n enabled: true\n pipelineIdentifier: deploy\n projectIdentifier: source\n", testScope.Org, testScope.Destination, true) if err != nil { @@ -291,6 +305,12 @@ func (a *copyAPI) storedYAML(key, root string) (int, string) { if !ok { return 404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}` } + var env map[string]any + if json.Unmarshal([]byte(doc), &env) == nil { + if inner, ok := env["yaml"].(string); ok { + doc = inner + } + } return 200, `{"status":"SUCCESS","data":{"` + root + `":{"yaml":` + jsonString(doc) + `}}}` } From fe3f72f614afd277ff01479f4228852600a028d7 Mon Sep 17 00:00:00 2001 From: Dewan Ahmed Date: Fri, 23 Oct 2026 22:00:05 -0300 Subject: [PATCH 6/7] fix(platform): close high-severity project copy review gaps Keep --dry-run from applying, reject --out before any writes, rewrite only matching source scope identifiers, and fail closed on truncated or unrecognized list pages. Co-authored-by: Cursor --- modules/platform/project_copy.go | 69 +++++++----- modules/platform/project_copy_test.go | 20 ++++ modules/platform/projectcopy/copy.go | 123 +++++++++++++++------- modules/platform/projectcopy/copy_test.go | 40 ++++++- modules/platform/projectcopy/rewrite.go | 27 +++-- 5 files changed, 207 insertions(+), 72 deletions(-) diff --git a/modules/platform/project_copy.go b/modules/platform/project_copy.go index 4ed12098..86b3a6a6 100644 --- a/modules/platform/project_copy.go +++ b/modules/platform/project_copy.go @@ -19,15 +19,50 @@ func projectCopy(ctx *cmdctx.Ctx) error { if err != nil { return err } - report, copyErr := projectcopy.Copy(ctx.Context, projectcopy.NewTransport(ctx.Auth), scope, cmdctx.GetBool(ctx.FlagValues, "apply")) - if err := writeProjectCopyReport(ctx, report); err != nil { + out, closeOut, err := openProjectCopyOut(ctx) + if err != nil { return err } + if closeOut != nil { + defer closeOut() + } + report, copyErr := projectcopy.Copy(ctx.Context, projectcopy.NewTransport(ctx.Auth), scope, projectCopyShouldApply(ctx)) + if err := renderProjectCopyReport(out, reportFormat(ctx), report); err != nil { + if copyErr != nil { + return copyErr + } + return errors.New("cannot write project planning report") + } return copyErr } +func projectCopyShouldApply(ctx *cmdctx.Ctx) bool { + if cmdctx.GetBool(ctx.FlagValues, "dry-run") { + return false + } + return cmdctx.GetBool(ctx.FlagValues, "apply") +} + +func reportFormat(ctx *cmdctx.Ctx) string { + if ctx.FormatFlags.Format == "" { + return "text" + } + return ctx.FormatFlags.Format +} + +func openProjectCopyOut(ctx *cmdctx.Ctx) (io.Writer, func(), error) { + if ctx.FormatFlags.OutFile == "" { + return os.Stdout, nil, nil + } + f, err := os.OpenFile(ctx.FormatFlags.OutFile, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + return nil, nil, errors.New("cannot create report: --out must name a new file") + } + return f, func() { _ = f.Close() }, nil +} + func projectCopyScope(ctx *cmdctx.Ctx) (projectcopy.Scope, error) { - if ctx.ProvidedFlags["dry-run"] && !cmdctx.GetBool(ctx.FlagValues, "dry-run") && !cmdctx.GetBool(ctx.FlagValues, "apply") { + if ctx.ProvidedFlags["dry-run"] && !cmdctx.GetBool(ctx.FlagValues, "dry-run") && !projectCopyShouldApply(ctx) { return projectcopy.Scope{}, errors.New("pass --apply to copy; --dry-run=false does not write") } if cmdctx.GetString(ctx.FlagValues, "resources") != "cd-core" { @@ -50,28 +85,14 @@ func projectCopyScope(ctx *cmdctx.Ctx) (projectcopy.Scope, error) { } func writeProjectCopyReport(ctx *cmdctx.Ctx, report projectcopy.Report) error { - format := ctx.FormatFlags.Format - if format == "" { - format = "text" - } - if format != "text" && format != "json" { - return errors.New("project planning supports --format text or json") - } - var w io.Writer = os.Stdout - if ctx.FormatFlags.OutFile != "" { - // Exclusive creation also rejects symlinks/hardlinks to profiles or other inputs. - f, err := os.OpenFile(ctx.FormatFlags.OutFile, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) - if err != nil { - return errors.New("cannot create report: --out must name a new file") - } - writeErr := renderProjectCopyReport(f, format, report) - closeErr := f.Close() - if writeErr != nil || closeErr != nil { - return errors.New("cannot write project planning report") - } - return nil + out, closeOut, err := openProjectCopyOut(ctx) + if err != nil { + return err + } + if closeOut != nil { + defer closeOut() } - if err := renderProjectCopyReport(w, format, report); err != nil { + if err := renderProjectCopyReport(out, reportFormat(ctx), report); err != nil { return errors.New("cannot write project planning report") } return nil diff --git a/modules/platform/project_copy_test.go b/modules/platform/project_copy_test.go index 37421d91..66cc5397 100644 --- a/modules/platform/project_copy_test.go +++ b/modules/platform/project_copy_test.go @@ -52,6 +52,26 @@ func TestProjectCopyRejectsUnavailableWorkBeforeTransport(t *testing.T) { t.Fatal(err) } c = copyContext() + c.SetFlag("dry-run", true) + c.SetFlag("apply", true) + if projectCopyShouldApply(c) { + t.Fatal("dry-run must not apply") + } + if _, err := projectCopyScope(c); err != nil { + t.Fatal(err) + } + existing := filepath.Join(t.TempDir(), "report") + os.WriteFile(existing, []byte("kept"), 0600) + c = copyContext() + c.SetFlag("apply", true) + c.FormatFlags.OutFile = existing + if err := projectCopy(c); err == nil || !strings.Contains(err.Error(), "cannot create report") { + t.Fatalf("existing --out must fail before copy: %v", err) + } + if data, _ := os.ReadFile(existing); string(data) != "kept" { + t.Fatal("existing --out changed") + } + c = copyContext() s, err := projectCopyScope(c) if err != nil || s.Source != "source" || s.Destination != "destination" { t.Fatal("profile project replaced explicit locations") diff --git a/modules/platform/projectcopy/copy.go b/modules/platform/projectcopy/copy.go index f5e4ef88..fe645b6e 100644 --- a/modules/platform/projectcopy/copy.go +++ b/modules/platform/projectcopy/copy.go @@ -26,6 +26,18 @@ func Copy(ctx context.Context, t *Transport, scope Scope, apply bool) (Report, e return c.report, err } +func (c *copier) rewriteOpts(disableTriggers bool) rewriteOpts { + return rewriteOpts{Org: c.scope.Org, Project: c.scope.Destination, SourceOrg: c.scope.Org, SourceProject: c.scope.Source, DisableTriggers: disableTriggers} +} + +func (c *copier) rewriteDoc(doc string, disableTriggers bool) (string, error) { + return rewriteYAML(doc, c.rewriteOpts(disableTriggers)) +} + +func (c *copier) rewriteObj(v any) { + rewriteTree(v, c.rewriteOpts(false)) +} + type copier struct { ctx context.Context transport *Transport @@ -309,7 +321,7 @@ func (c *copier) planConnectors() error { } source := cleanRoot(item) c.observe(source) - rewriteTree(source, c.scope.Org, c.scope.Destination, false) + c.rewriteObj(source) destRaw, found, err := c.getObject("/ng/api/connectors/"+url.PathEscape(id), c.query(c.scope.Destination)) if err != nil { return err @@ -317,7 +329,7 @@ func (c *copier) planConnectors() error { if found { dest, _ := digMap(destRaw, "data", "connector") cleaned := cleanRoot(dest) - rewriteTree(cleaned, c.scope.Org, c.scope.Destination, false) + c.rewriteObj(cleaned) if canonicalJSON(cleaned) == canonicalJSON(source) { c.keep(Result{Kind: "connector", Identifier: id, Action: ActionSkip, Reason: "destination matches"}) continue @@ -363,7 +375,7 @@ func (c *copier) planYAMLList(kind, path, root, parent string, extra url.Values) c.block(kind, id, "definition missing") continue } - rewritten, err := rewriteYAML(sourceDoc, c.scope.Org, c.scope.Destination, false) + rewritten, err := c.rewriteDoc(sourceDoc, false) if err != nil { c.block(kind, id, "definition could not be rewritten") continue @@ -385,7 +397,7 @@ func (c *copier) planYAMLList(kind, path, root, parent string, extra url.Values) }) continue } - destRewritten, err := rewriteYAML(destDoc, c.scope.Org, c.scope.Destination, false) + destRewritten, err := c.rewriteDoc(destDoc, false) if err != nil || !sameDocument(rewritten, destRewritten) { c.conflictResult(kind, reportID) continue @@ -513,7 +525,7 @@ func (c *copier) planOverrides(env string) error { } source := cleanRoot(item) c.observe(source) - rewriteTree(source, c.scope.Org, c.scope.Destination, false) + c.rewriteObj(source) destRaw, found, err := c.getObject("/ng/api/serviceOverrides/"+url.PathEscape(stringField(item, "identifier")), c.query(c.scope.Destination)) if err != nil { return err @@ -521,7 +533,7 @@ func (c *copier) planOverrides(env string) error { if found { dest, _ := digMap(destRaw, "data") cleaned := cleanRoot(dest) - rewriteTree(cleaned, c.scope.Org, c.scope.Destination, false) + c.rewriteObj(cleaned) if canonicalJSON(cleaned) == canonicalJSON(source) { c.keep(Result{Kind: "service_override", Identifier: id, Action: ActionSkip, Reason: "destination matches"}) continue @@ -571,7 +583,7 @@ func (c *copier) planTemplates() error { if doc == "" { doc = stringField(obj, "yaml") } - rewritten, err := rewriteYAML(doc, c.scope.Org, c.scope.Destination, false) + rewritten, err := c.rewriteDoc(doc, false) if err != nil || rewritten == "" { c.block("template", reportID, "template definition missing") continue @@ -584,7 +596,7 @@ func (c *copier) planTemplates() error { if destFound { destData, _ := digMap(destObj, "data") destDoc := stringField(destData, "yaml") - destRewritten, rerr := rewriteYAML(destDoc, c.scope.Org, c.scope.Destination, false) + destRewritten, rerr := c.rewriteDoc(destDoc, false) if rerr != nil || !sameDocument(rewritten, destRewritten) { c.conflictResult("template", reportID) continue @@ -629,7 +641,7 @@ func (c *copier) planPipelines() error { c.block("pipeline", id, "pipeline definition missing") continue } - rewritten, err := rewriteYAML(doc, c.scope.Org, c.scope.Destination, false) + rewritten, err := c.rewriteDoc(doc, false) if err != nil { c.block("pipeline", id, "pipeline definition could not be rewritten") continue @@ -646,7 +658,7 @@ func (c *copier) planPipelines() error { }) continue } - destRewritten, rerr := rewriteYAML(destDoc, c.scope.Org, c.scope.Destination, false) + destRewritten, rerr := c.rewriteDoc(destDoc, false) if rerr != nil || !sameDocument(rewritten, destRewritten) { c.conflictResult("pipeline", id) continue @@ -710,7 +722,7 @@ func (c *copier) planPipelineDocs(kind, pipeline, path, yamlKey string, disable data, _ := digMap(obj, "data") doc = stringField(data, yamlKey, "yaml", "inputSetYaml") } - rewritten, err := rewriteYAML(doc, c.scope.Org, c.scope.Destination, disable) + rewritten, err := c.rewriteDoc(doc, disable) if err != nil || rewritten == "" { c.block(kind, reportID, "definition could not be rewritten") continue @@ -723,7 +735,7 @@ func (c *copier) planPipelineDocs(kind, pipeline, path, yamlKey string, disable if destFound { destData, _ := digMap(destObj, "data") destDoc := stringField(destData, yamlKey, "yaml", "inputSetYaml") - destRewritten, rerr := rewriteYAML(destDoc, c.scope.Org, c.scope.Destination, disable) + destRewritten, rerr := c.rewriteDoc(destDoc, disable) if rerr != nil || !sameDocument(rewritten, destRewritten) { c.conflictResult(kind, reportID) continue @@ -1115,15 +1127,13 @@ func (c *copier) list(method, path string, query url.Values, body, pageParam, si return nil, err } if status != http.StatusOK { - if page > 0 && (status == http.StatusBadRequest || status == http.StatusNotFound) { - return all, nil - } return nil, fmt.Errorf("project copy list failed: status %d", status) } - items, totalPages, err := extractItems(data) + pageData, err := extractItems(data) if err != nil { return nil, err } + items := pageData.Items if wrap != "" { unwrapped := make([]map[string]any, 0, len(items)) for _, item := range items { @@ -1150,51 +1160,92 @@ func (c *copier) list(method, path string, query url.Values, body, pageParam, si fresh++ all = append(all, item) } - if len(items) == 0 || len(items) < 100 || (totalPages > 0 && page+1 >= totalPages) || fresh == 0 { - return all, nil - } if len(all) > 100000 { return nil, errors.New("project copy list exceeded 100000 items") } + more := false + switch { + case pageData.HasTotalPages: + more = page+1 < pageData.TotalPages + if !more && pageData.HasTotalItems && len(all) != pageData.TotalItems { + return nil, errors.New("project copy list incomplete") + } + case pageData.HasTotalItems: + more = len(all) < pageData.TotalItems + default: + more = len(items) == 100 + } + if !more { + return all, nil + } + if len(items) == 0 || fresh == 0 { + return nil, errors.New("project copy list incomplete") + } } return nil, errors.New("project copy list exceeded page limit") } -func extractItems(body []byte) ([]map[string]any, int, error) { +type listPage struct { + Items []map[string]any + TotalPages int + TotalItems int + HasTotalPages bool + HasTotalItems bool +} + +func extractItems(body []byte) (listPage, error) { if len(body) == 0 { - return nil, 0, errors.New("project copy list returned an empty body") + return listPage{}, errors.New("project copy list returned an empty body") } var top any if err := json.Unmarshal(body, &top); err != nil { - return nil, 0, errors.New("malformed project copy list") + return listPage{}, errors.New("malformed project copy list") } switch node := top.(type) { case []any: - return mapsOf(node), 1, nil + items := mapsOf(node) + return listPage{Items: items, TotalPages: 1, HasTotalPages: true, TotalItems: len(items), HasTotalItems: true}, nil case map[string]any: - if !strings.EqualFold(stringField(node, "status"), "") && !strings.EqualFold(stringField(node, "status"), "SUCCESS") && stringField(node, "status") != "" { - if !strings.EqualFold(stringField(node, "status"), "SUCCESS") { - return nil, 0, errors.New("project copy list failed") - } + if status := stringField(node, "status"); status != "" && !strings.EqualFold(status, "SUCCESS") { + return listPage{}, errors.New("project copy list failed") } data := node - if inner, ok := asMap(node["data"]); ok { + if raw, exists := node["data"]; exists { + inner, ok := asMap(raw) + if !ok { + return listPage{}, errors.New("unrecognized project copy list") + } data = inner } + var items []any + found := false for _, key := range []string{"content", "policies", "policy_sets", "policysets", "resource"} { - if items, ok := asSlice(data[key]); ok { - return mapsOf(items), intFrom(data["totalPages"]), nil + if arr, ok := asSlice(data[key]); ok { + items, found = arr, true + break } - if items, ok := asSlice(node[key]); ok { - return mapsOf(items), intFrom(node["totalPages"]), nil + if arr, ok := asSlice(node[key]); ok { + items, found = arr, true + break } } - if intFrom(data["totalItems"]) == 0 && intFrom(data["totalElements"]) == 0 && data["content"] == nil && node["resource"] == nil { - return nil, intFrom(data["totalPages"]), nil + if !found { + return listPage{}, errors.New("unrecognized project copy list") + } + page := listPage{Items: mapsOf(items)} + if _, ok := data["totalPages"]; ok { + page.HasTotalPages, page.TotalPages = true, intFrom(data["totalPages"]) + } else if _, ok := node["totalPages"]; ok { + page.HasTotalPages, page.TotalPages = true, intFrom(node["totalPages"]) + } + if v, ok := data["totalItems"]; ok { + page.HasTotalItems, page.TotalItems = true, intFrom(v) + } else if v, ok := data["totalElements"]; ok { + page.HasTotalItems, page.TotalItems = true, intFrom(v) } - return nil, 0, errors.New("unrecognized project copy list") + return page, nil default: - return nil, 0, errors.New("unrecognized project copy list") + return listPage{}, errors.New("unrecognized project copy list") } } diff --git a/modules/platform/projectcopy/copy_test.go b/modules/platform/projectcopy/copy_test.go index c013b0f1..0e637b2e 100644 --- a/modules/platform/projectcopy/copy_test.go +++ b/modules/platform/projectcopy/copy_test.go @@ -8,6 +8,7 @@ import ( "encoding/json" "io" "net/http" + "net/url" "strings" "testing" ) @@ -129,7 +130,7 @@ func TestCDEnvelopeWrapsServiceYAML(t *testing.T) { } func TestRewriteDisablesTriggersAndRewritesProject(t *testing.T) { - doc, err := rewriteYAML("trigger:\n identifier: push\n enabled: true\n pipelineIdentifier: deploy\n projectIdentifier: source\n", testScope.Org, testScope.Destination, true) + doc, err := rewriteYAML("trigger:\n identifier: push\n enabled: true\n pipelineIdentifier: deploy\n projectIdentifier: source\n", rewriteOpts{Org: testScope.Org, Project: testScope.Destination, SourceOrg: testScope.Org, SourceProject: testScope.Source, DisableTriggers: true}) if err != nil { t.Fatal(err) } @@ -138,6 +139,43 @@ func TestRewriteDisablesTriggersAndRewritesProject(t *testing.T) { } } +func TestRewritePreservesCrossProjectRefs(t *testing.T) { + doc, err := rewriteYAML("pipeline:\n projectIdentifier: source\n stages:\n - stage:\n spec:\n pipeline:\n projectIdentifier: other_project\n orgIdentifier: other_org\n", rewriteOpts{Org: testScope.Org, Project: testScope.Destination, SourceOrg: testScope.Org, SourceProject: testScope.Source}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(doc, "projectIdentifier: "+testScope.Destination) || !strings.Contains(doc, "projectIdentifier: other_project") || !strings.Contains(doc, "orgIdentifier: other_org") { + t.Fatal(doc) + } +} + +func TestListFailsClosedOnLaterPageError(t *testing.T) { + calls := 0 + tr := fakeTransport(func(r *http.Request) (*http.Response, error) { + calls++ + if calls == 1 { + return response(200, `{"status":"SUCCESS","data":{"content":[{"identifier":"a"}],"totalItems":2,"totalPages":2}}`), nil + } + return response(404, `{"status":"ERROR","code":"RESOURCE_NOT_FOUND"}`), nil + }) + c := &copier{ctx: context.Background(), transport: tr, scope: testScope} + if _, err := c.list(http.MethodGet, "/items", url.Values{}, "", "page", "size", ""); err == nil { + t.Fatal("later page 404 accepted as complete") + } +} + +func TestExtractItemsRejectsUnprovenLists(t *testing.T) { + for _, body := range []string{`{}`, `{"status":"SUCCESS"}`, `{"status":"SUCCESS","data":null}`, `{"status":"ERROR","data":{"content":[]}}`} { + if _, err := extractItems([]byte(body)); err == nil { + t.Fatalf("accepted %s", body) + } + } + page, err := extractItems([]byte(`{"status":"SUCCESS","data":{"content":[],"totalItems":0,"totalPages":0}}`)) + if err != nil || len(page.Items) != 0 || !page.HasTotalItems { + t.Fatalf("%v %#v", err, page) + } +} + func containsResult(report Report, kind, id string, action Action) bool { for _, item := range report.Results { if item.Kind == kind && item.Identifier == id && item.Action == action { diff --git a/modules/platform/projectcopy/rewrite.go b/modules/platform/projectcopy/rewrite.go index f492e7fb..5357d863 100644 --- a/modules/platform/projectcopy/rewrite.go +++ b/modules/platform/projectcopy/rewrite.go @@ -22,13 +22,18 @@ var rootDrop = map[string]bool{ "yamlVersion": true, "entityValidity": true, } -func rewriteYAML(doc, org, project string, disableTriggers bool) (string, error) { +type rewriteOpts struct { + Org, Project, SourceOrg, SourceProject string + DisableTriggers bool +} + +func rewriteYAML(doc string, opts rewriteOpts) (string, error) { var node any if err := yaml.Unmarshal([]byte(doc), &node); err != nil { return "", err } node = yamlToPlain(node) - rewriteTree(node, org, project, disableTriggers) + rewriteTree(node, opts) out, err := yaml.Marshal(node) if err != nil { return "", err @@ -74,16 +79,16 @@ func toString(v any) string { return s } -func rewriteTree(v any, org, project string, disableTriggers bool) { +func rewriteTree(v any, opts rewriteOpts) { switch n := v.(type) { case map[string]any: - if _, ok := n["projectIdentifier"]; ok { - n["projectIdentifier"] = project + if cur, ok := n["projectIdentifier"].(string); ok && cur == opts.SourceProject { + n["projectIdentifier"] = opts.Project } - if _, ok := n["orgIdentifier"]; ok { - n["orgIdentifier"] = org + if cur, ok := n["orgIdentifier"].(string); ok && cur == opts.SourceOrg { + n["orgIdentifier"] = opts.Org } - if disableTriggers { + if opts.DisableTriggers { if _, ok := n["pipelineIdentifier"]; ok { if _, ok := n["enabled"]; ok { n["enabled"] = false @@ -92,16 +97,16 @@ func rewriteTree(v any, org, project string, disableTriggers bool) { } for k, child := range n { if s, ok := child.(string); ok && (k == "yaml" || k == "yamlPipeline" || k == "inputSetYaml") && strings.Contains(s, "projectIdentifier") { - if rewritten, err := rewriteYAML(s, org, project, disableTriggers); err == nil { + if rewritten, err := rewriteYAML(s, opts); err == nil { n[k] = rewritten continue } } - rewriteTree(child, org, project, disableTriggers) + rewriteTree(child, opts) } case []any: for i := range n { - rewriteTree(n[i], org, project, disableTriggers) + rewriteTree(n[i], opts) } } } From a30e485f9b4e76db91fa8f4a346ea5451e37ff51 Mon Sep 17 00:00:00 2001 From: Dewan Ahmed Date: Tue, 27 Oct 2026 12:38:55 -0300 Subject: [PATCH 7/7] fix(platform): treat skipped copy work as incomplete Git-backed skips now fail the command, reference secrets conflict on path, templates copy in dependency order, and stable-template errors stop the write. Transport retries only read calls, detects not-found from API codes, and refreshes SSO tokens before requests. Co-authored-by: Cursor --- modules/platform/project-copy.md | 8 +- modules/platform/projectcopy/copy.go | 196 +++++++++++++++++++--- modules/platform/projectcopy/copy_test.go | 155 +++++++++++++++-- modules/platform/projectcopy/transport.go | 40 ++++- 4 files changed, 355 insertions(+), 44 deletions(-) diff --git a/modules/platform/project-copy.md b/modules/platform/project-copy.md index 4b21a88e..51fd58ea 100644 --- a/modules/platform/project-copy.md +++ b/modules/platform/project-copy.md @@ -24,13 +24,15 @@ The first command is a plan. Nothing is written. `--apply` creates the destinati Order: project, secrets, connectors, services, environments, infrastructures, service overrides, templates, pipelines, input sets, triggers, policies, policy sets. - Inline `SecretText` is created with the placeholder value `123456`. The source value is not read. Update each listed secret before running the destination project. -- Reference secrets copy the secret manager and reference path. +- Reference secrets copy the secret manager and reference path. A destination secret with a different path is a conflict. - Other secret types are reported as blocked and skipped. +- Templates are copied in dependency order using project-scoped `templateRef` values. - Triggers are created disabled. -- Git-backed entities are skipped. +- Git-backed entities are skipped and the command exits nonzero so the skip is not treated as a complete copy. - Org and account references, including `account.` and `org.` identifiers, are reported and left in place. -- Delegate selectors are checked against connected delegates. Delegates themselves are not installed. +- Delegate selectors are checked against connected delegates (`CONNECTED`). Delegates themselves are not installed. - Identical destination resources are skipped. A same identifier with different content aborts the copy before any write. +- A create failure stops the copy. Re-run `--apply` to continue; matching resources already written are skipped. ## Test against a source project diff --git a/modules/platform/projectcopy/copy.go b/modules/platform/projectcopy/copy.go index fe645b6e..be398128 100644 --- a/modules/platform/projectcopy/copy.go +++ b/modules/platform/projectcopy/copy.go @@ -49,6 +49,7 @@ type copier struct { plans []work conflict bool blocked bool + skipped bool envIDs []string pipelineIDs []string } @@ -120,6 +121,10 @@ func (c *copier) run() error { c.report.Readiness = "plan incomplete: blocked resources will be skipped on apply" return errors.New("project copy plan incomplete: blocked resources were not included") } + if c.skipped { + c.report.Readiness = "plan incomplete: requested git-backed resources will be skipped on apply" + return errors.New("project copy plan incomplete: requested git-backed resources were not included") + } c.report.Readiness = "plan only; pass --apply to copy" return nil } @@ -141,6 +146,13 @@ func (c *copier) run() error { c.report.Readiness = "copied with blocked resources skipped" return errors.New("project copy incomplete: blocked resources were not copied") } + if c.skipped { + c.report.Readiness = "copied with requested resources skipped" + if len(c.report.SecretsPendingValue) > 0 { + c.report.Readiness = "copied with requested resources skipped; update inline secrets before running the destination project" + } + return errors.New("project copy incomplete: requested git-backed resources were not copied") + } c.report.Readiness = "copied" if len(c.report.SecretsPendingValue) > 0 { c.report.Readiness = "copied; update inline secrets before running the destination project" @@ -275,7 +287,13 @@ func secretMetaMatches(want, got map[string]any) bool { if gotSpec == nil || stringField(gotSpec, "valueType") != stringField(wantSpec, "valueType") { return false } - return stringField(gotSpec, "secretManagerIdentifier") == stringField(wantSpec, "secretManagerIdentifier") + if stringField(gotSpec, "secretManagerIdentifier") != stringField(wantSpec, "secretManagerIdentifier") { + return false + } + if strings.EqualFold(stringField(wantSpec, "valueType"), "Reference") { + return stringField(gotSpec, "value") == stringField(wantSpec, "value") + } + return true } func specObject(spec map[string]json.RawMessage, inline bool) (map[string]any, error) { @@ -308,7 +326,7 @@ func (c *copier) planConnectors() error { continue } if isRemote(item) { - c.keep(Result{Kind: "connector", Identifier: id, Action: ActionSkipped, Reason: "git-backed connector skipped"}) + c.skipGit("connector", id, "git-backed connector skipped") continue } if id == "harnessSecretManager" || truthy(item["harnessManaged"]) { @@ -364,7 +382,7 @@ func (c *copier) planYAMLList(kind, path, root, parent string, extra url.Values) continue } if isRemote(item) { - c.keep(Result{Kind: kind, Identifier: id, Action: ActionSkipped, Reason: "git-backed resource skipped"}) + c.skipGit(kind, id, "git-backed resource skipped") continue } sourceDoc, err := c.yamlFor(kind, id, item, root, extra, c.scope.Source) @@ -520,7 +538,7 @@ func (c *copier) planOverrides(env string) error { id = env + "/" + stringField(item, "serviceRef", "serviceIdentifier") } if isRemote(item) { - c.keep(Result{Kind: "service_override", Identifier: id, Action: ActionSkipped, Reason: "git-backed resource skipped"}) + c.skipGit("service_override", id, "git-backed resource skipped") continue } source := cleanRoot(item) @@ -550,23 +568,23 @@ func (c *copier) planOverrides(env string) error { return nil } +type templateUnit struct { + id, version, reportID, doc string + stable bool +} + func (c *copier) planTemplates() error { items, err := c.list(http.MethodPost, "/template/api/templates/list", mergeQuery(c.query(c.scope.Source), url.Values{"templateListType": {"ALL"}}), `{"filterType":"Template"}`, "page", "size", "") if err != nil { return err } - sort.Slice(items, func(i, j int) bool { - if stringField(items[i], "identifier") != stringField(items[j], "identifier") { - return stringField(items[i], "identifier") < stringField(items[j], "identifier") - } - return versionLess(stringField(items[i], "versionLabel", "version"), stringField(items[j], "versionLabel", "version")) - }) + var units []templateUnit for _, item := range items { id := stringField(item, "identifier") version := stringField(item, "versionLabel", "version") reportID := id + "/" + version if isRemote(item) { - c.keep(Result{Kind: "template", Identifier: reportID, Action: ActionSkipped, Reason: "git-backed template skipped"}) + c.skipGit("template", reportID, "git-backed template skipped") continue } query := mergeQuery(c.query(c.scope.Source), url.Values{"versionLabel": {version}}) @@ -588,8 +606,14 @@ func (c *copier) planTemplates() error { c.block("template", reportID, "template definition missing") continue } - c.observeDoc(rewritten) - destObj, destFound, err := c.getObject("/template/api/templates/"+url.PathEscape(id), mergeQuery(c.query(c.scope.Destination), url.Values{"versionLabel": {version}})) + units = append(units, templateUnit{ + id: id, version: version, reportID: reportID, doc: rewritten, + stable: truthy(item["stableTemplate"]) || truthy(item["stable"]), + }) + } + for _, unit := range orderTemplateUnits(units) { + c.observeDoc(unit.doc) + destObj, destFound, err := c.getObject("/template/api/templates/"+url.PathEscape(unit.id), mergeQuery(c.query(c.scope.Destination), url.Values{"versionLabel": {unit.version}})) if err != nil { return err } @@ -597,16 +621,16 @@ func (c *copier) planTemplates() error { destData, _ := digMap(destObj, "data") destDoc := stringField(destData, "yaml") destRewritten, rerr := c.rewriteDoc(destDoc, false) - if rerr != nil || !sameDocument(rewritten, destRewritten) { - c.conflictResult("template", reportID) + if rerr != nil || !sameDocument(unit.doc, destRewritten) { + c.conflictResult("template", unit.reportID) continue } - c.keep(Result{Kind: "template", Identifier: reportID, Action: ActionSkip, Reason: "destination matches"}) + c.keep(Result{Kind: "template", Identifier: unit.reportID, Action: ActionSkip, Reason: "destination matches"}) continue } - stable := truthy(item["stableTemplate"]) || truthy(item["stable"]) - docCopy := rewritten - c.queue(Result{Kind: "template", Identifier: reportID, Action: ActionCreate}, func() error { + docCopy := unit.doc + id, version, stable := unit.id, unit.version, unit.stable + c.queue(Result{Kind: "template", Identifier: unit.reportID, Action: ActionCreate}, func() error { if err := c.postYAML("/template/api/templates", c.query(c.scope.Destination), docCopy); err != nil { return err } @@ -614,14 +638,107 @@ func (c *copier) planTemplates() error { return nil } stablePath := "/template/api/templates/updateStableTemplate/" + url.PathEscape(id) + "/" + url.PathEscape(version) - // The version is already stored. A rejected stable-label call does not roll that back. - _ = c.postJSON(stablePath, c.query(c.scope.Destination), "") - return nil + return c.postJSON(stablePath, c.query(c.scope.Destination), "") }) } return nil } +func orderTemplateUnits(units []templateUnit) []templateUnit { + if len(units) < 2 { + return units + } + ids := map[string]struct{}{} + byID := map[string][]templateUnit{} + for _, unit := range units { + ids[unit.id] = struct{}{} + byID[unit.id] = append(byID[unit.id], unit) + } + for id := range byID { + sort.Slice(byID[id], func(i, j int) bool { + return versionLess(byID[id][i].version, byID[id][j].version) + }) + } + prereq := map[string]map[string]struct{}{} + for _, unit := range units { + for _, ref := range templateRefs(unit.doc) { + dep, ok := projectTemplateID(ref) + if !ok || dep == unit.id { + continue + } + if _, known := ids[dep]; !known { + continue + } + if prereq[unit.id] == nil { + prereq[unit.id] = map[string]struct{}{} + } + prereq[unit.id][dep] = struct{}{} + } + } + remaining := map[string]struct{}{} + for id := range ids { + remaining[id] = struct{}{} + } + var orderedIDs []string + for len(remaining) > 0 { + var ready []string + for id := range remaining { + blocked := false + for dep := range prereq[id] { + if _, still := remaining[dep]; still { + blocked = true + break + } + } + if !blocked { + ready = append(ready, id) + } + } + if len(ready) == 0 { + for id := range remaining { + ready = append(ready, id) + } + sort.Strings(ready) + orderedIDs = append(orderedIDs, ready...) + break + } + sort.Strings(ready) + for _, id := range ready { + orderedIDs = append(orderedIDs, id) + delete(remaining, id) + } + } + out := make([]templateUnit, 0, len(units)) + for _, id := range orderedIDs { + out = append(out, byID[id]...) + } + return out +} + +func templateRefs(doc string) []string { + var node any + if yaml.Unmarshal([]byte(doc), &node) != nil { + return nil + } + var refs []string + walk(yamlToPlain(node), func(key string, value any) { + s, ok := value.(string) + if key != "templateRef" || !ok || s == "" { + return + } + refs = append(refs, s) + }) + return refs +} + +func projectTemplateID(ref string) (string, bool) { + ref = strings.TrimSpace(ref) + if ref == "" || strings.Contains(ref, ".") { + return "", false + } + return ref, true +} + func (c *copier) planPipelines() error { items, err := c.list(http.MethodPost, "/pipeline/api/pipelines/list", c.query(c.scope.Source), `{"filterType":"PipelineSetup"}`, "page", "size", "") if err != nil { @@ -630,7 +747,7 @@ func (c *copier) planPipelines() error { for _, item := range items { id := stringField(item, "identifier") if isRemote(item) { - c.keep(Result{Kind: "pipeline", Identifier: id, Action: ActionSkipped, Reason: "git-backed pipeline skipped"}) + c.skipGit("pipeline", id, "git-backed pipeline skipped") continue } doc, found, err := c.pipelineYAML(id, c.scope.Source) @@ -706,7 +823,7 @@ func (c *copier) planPipelineDocs(kind, pipeline, path, yamlKey string, disable id := stringField(item, "identifier") reportID := pipeline + "/" + id if isRemote(item) { - c.keep(Result{Kind: kind, Identifier: reportID, Action: ActionSkipped, Reason: "git-backed resource skipped"}) + c.skipGit(kind, reportID, "git-backed resource skipped") continue } doc := stringField(item, yamlKey, "yaml", "inputSetYaml") @@ -867,7 +984,17 @@ func (c *copier) planDelegates() error { } func delegateConnected(item map[string]any) bool { - return strings.Contains(strings.ToLower(stringField(item, "connectivityStatus", "status")), "connected") + status := strings.ToUpper(strings.TrimSpace(stringField(item, "connectivityStatus", "status"))) + switch status { + case "DISCONNECTED", "DOWN", "EXPIRED", "DEAD": + return false + case "CONNECTED", "ACTIVE", "SUCCESS": + return true + } + if b, ok := item["activelyConnected"].(bool); ok { + return b + } + return strings.EqualFold(strings.TrimSpace(stringField(item, "activelyConnected")), "true") } func delegateMatches(item map[string]any, selector string) bool { @@ -932,6 +1059,11 @@ func (c *copier) keep(result Result) { c.report.Results = append(c.report.Results, result) } +func (c *copier) skipGit(kind, id, reason string) { + c.skipped = true + c.keep(Result{Kind: kind, Identifier: id, Action: ActionSkipped, Reason: reason}) +} + func (c *copier) block(kind, id, reason string) { c.blocked = true c.keep(Result{Kind: kind, Identifier: id, Action: ActionBlocked, Reason: reason}) @@ -1275,8 +1407,18 @@ func isNotFound(status int, body []byte) bool { if status == http.StatusNotFound { return true } - text := strings.ToUpper(string(body)) - return strings.Contains(text, "NOT_FOUND") || strings.Contains(text, "DOES NOT EXIST") || strings.Contains(text, "NOT FOUND") + var envelope struct { + Status string `json:"status"` + Code string `json:"code"` + } + if json.Unmarshal(body, &envelope) != nil { + return false + } + if strings.EqualFold(envelope.Status, "SUCCESS") { + return false + } + code := strings.ToUpper(strings.TrimSpace(envelope.Code)) + return code == "ENTITY_NOT_FOUND" || code == "RESOURCE_NOT_FOUND_EXCEPTION" || strings.HasSuffix(code, "_NOT_FOUND") } func intFrom(v any) int { diff --git a/modules/platform/projectcopy/copy_test.go b/modules/platform/projectcopy/copy_test.go index 0e637b2e..0f176cd2 100644 --- a/modules/platform/projectcopy/copy_test.go +++ b/modules/platform/projectcopy/copy_test.go @@ -16,10 +16,10 @@ import ( func TestCopyAppliesCDCoreAndSkipsIdenticalRerun(t *testing.T) { api := newCopyAPI(false) report, err := Copy(context.Background(), api.transport(), testScope, true) - if err != nil { - t.Fatalf("%v\n%s", err, strings.Join(api.seen, "\n")) + if err == nil || !strings.Contains(err.Error(), "git-backed") { + t.Fatalf("expected incomplete copy for skipped git-backed resources: %v\n%s", err, strings.Join(api.seen, "\n")) } - if !report.InventoryComplete || report.Readiness == "" { + if !report.InventoryComplete || !strings.Contains(report.Readiness, "skipped") { t.Fatalf("readiness %q", report.Readiness) } raw, _ := json.Marshal(report) @@ -64,8 +64,8 @@ func TestCopyAppliesCDCoreAndSkipsIdenticalRerun(t *testing.T) { } before := len(api.mutating) again, err := Copy(context.Background(), api.transport(), testScope, true) - if err != nil { - t.Fatalf("%v\n%s", err, strings.Join(api.seen, "\n")) + if err == nil || !strings.Contains(err.Error(), "git-backed") { + t.Fatalf("expected incomplete rerun for skipped git-backed resources: %v\n%s", err, strings.Join(api.seen, "\n")) } if len(api.mutating) != before { t.Fatalf("rerun wrote %d extra resources", len(api.mutating)-before) @@ -78,8 +78,8 @@ func TestCopyAppliesCDCoreAndSkipsIdenticalRerun(t *testing.T) { func TestCopyPlanDoesNotWrite(t *testing.T) { api := newCopyAPI(false) report, err := Copy(context.Background(), api.transport(), testScope, false) - if err != nil { - t.Fatal(err) + if err == nil || !strings.Contains(err.Error(), "git-backed") { + t.Fatalf("expected incomplete plan for skipped git-backed resources: %v", err) } if len(api.mutating) != 0 { t.Fatalf("plan wrote %#v", api.mutating) @@ -164,6 +164,129 @@ func TestListFailsClosedOnLaterPageError(t *testing.T) { } } +func TestSecretMetaMatchesReferencePath(t *testing.T) { + want := map[string]any{"name": "ref", "type": "SecretText", "spec": map[string]any{"valueType": "Reference", "secretManagerIdentifier": "org.manager", "value": "vault/path#key"}} + got := map[string]any{"name": "ref", "type": "SecretText", "spec": map[string]any{"valueType": "Reference", "secretManagerIdentifier": "org.manager", "value": "vault/other#key"}} + if secretMetaMatches(want, got) { + t.Fatal("different reference paths treated as identical") + } + got["spec"].(map[string]any)["value"] = "vault/path#key" + if !secretMetaMatches(want, got) { + t.Fatal("matching reference path rejected") + } +} + +func TestOrderTemplateUnitsCopiesDependenciesFirst(t *testing.T) { + ordered := orderTemplateUnits([]templateUnit{ + {id: "child", version: "v1", doc: "template:\n spec:\n templateRef: parent\n"}, + {id: "parent", version: "v2", doc: "template:\n spec:\n templateRef: account.echo\n"}, + {id: "parent", version: "v1", doc: "template:\n spec: {}\n"}, + }) + if len(ordered) != 3 || ordered[0].id != "parent" || ordered[0].version != "v1" || ordered[1].id != "parent" || ordered[1].version != "v2" || ordered[2].id != "child" { + t.Fatalf("%v", ordered) + } +} + +func TestDelegateConnectedRejectsDisconnected(t *testing.T) { + if delegateConnected(map[string]any{"connectivityStatus": "DISCONNECTED"}) { + t.Fatal("DISCONNECTED accepted") + } + if !delegateConnected(map[string]any{"connectivityStatus": "connected"}) { + t.Fatal("connected rejected") + } +} + +func TestIsNotFoundUsesAPICode(t *testing.T) { + if !isNotFound(http.StatusNotFound, nil) { + t.Fatal("404") + } + if !isNotFound(http.StatusOK, []byte(`{"status":"ERROR","code":"RESOURCE_NOT_FOUND_EXCEPTION"}`)) { + t.Fatal("API not-found code") + } + if isNotFound(http.StatusBadRequest, []byte("resource NOT_FOUND in yaml")) { + t.Fatal("substring match") + } + if isNotFound(http.StatusOK, []byte(`{"status":"SUCCESS","code":"RESOURCE_NOT_FOUND"}`)) { + t.Fatal("success envelope") + } +} + +func TestMutatingPostIsNotRetried(t *testing.T) { + calls := 0 + tr := fakeTransport(func(r *http.Request) (*http.Response, error) { + calls++ + return response(503, `{"status":"ERROR"}`), nil + }) + c := &copier{ctx: context.Background(), transport: tr, scope: testScope} + if err := c.postJSON("/ng/api/connectors", c.query(testScope.Destination), `{"connector":{}}`); err == nil { + t.Fatal("mutating 503 accepted") + } + if calls != 1 { + t.Fatalf("mutating POST retried %d times", calls) + } + calls = 0 + status, _, err := tr.exchange(context.Background(), http.MethodGet, "/ng/api/projects/destination", c.query(testScope.Destination), "", "") + if err != nil || status != 503 { + t.Fatalf("status=%d err=%v", status, err) + } + if calls != 3 { + t.Fatalf("GET 503 retried %d times", calls) + } +} + +func TestCopyResumesAfterCreateFailure(t *testing.T) { + api := newCopyAPI(false) + api.failPath = "/ng/api/servicesV2" + api.failOnce = true + report, err := Copy(context.Background(), api.transport(), testScope, true) + if err == nil || report.Readiness != "copy stopped after a create failure; re-run to continue" { + t.Fatalf("err=%v readiness=%q", err, report.Readiness) + } + if containsResult(report, "service", "svc", ActionCreate) { + t.Fatal("failed create recorded as success") + } + projectWrites := 0 + for _, call := range api.mutating { + if call.path == "/ng/api/projects" { + projectWrites++ + } + if call.path == "/ng/api/servicesV2" { + t.Fatal("failed service create was stored") + } + } + if projectWrites != 1 { + t.Fatalf("project writes = %d", projectWrites) + } + again, err := Copy(context.Background(), api.transport(), testScope, true) + if err == nil || !strings.Contains(err.Error(), "git-backed") { + t.Fatalf("expected resume to finish remaining writes: %v", err) + } + if !containsResult(again, "project", testScope.Destination, ActionSkip) || !containsResult(again, "service", "svc", ActionCreate) { + t.Fatalf("resume results %#v", again.Results) + } + projectWrites = 0 + for _, call := range api.mutating { + if call.path == "/ng/api/projects" { + projectWrites++ + } + } + if projectWrites != 1 { + t.Fatalf("resume recreated the project: %d writes", projectWrites) + } +} + +func TestCopyStableTemplateFailureStopsCopy(t *testing.T) { + api := newCopyAPI(false) + api.rejectStable = true + report, err := Copy(context.Background(), api.transport(), testScope, true) + if err == nil || report.Readiness != "copy stopped after a create failure; re-run to continue" { + t.Fatalf("err=%v readiness=%q", err, report.Readiness) + } + if !containsResult(report, "template", "step/v1", ActionBlocked) { + t.Fatalf("stable-template failure %#v", report.Results) + } +} + func TestExtractItemsRejectsUnprovenLists(t *testing.T) { for _, body := range []string{`{}`, `{"status":"SUCCESS"}`, `{"status":"SUCCESS","data":null}`, `{"status":"ERROR","data":{"content":[]}}`} { if _, err := extractItems([]byte(body)); err == nil { @@ -188,10 +311,13 @@ func containsResult(report Report, kind, id string, action Action) bool { type copyCall struct{ method, path, body, project string } type copyAPI struct { - conflict bool - mutating []copyCall - stored map[string]string - seen []string + conflict bool + failOnce bool + failPath string + rejectStable bool + mutating []copyCall + stored map[string]string + seen []string } func newCopyAPI(conflict bool) *copyAPI { @@ -209,6 +335,13 @@ func (a *copyAPI) transport() *Transport { a.seen = append(a.seen, r.Method+" "+path+" project="+project) if r.Method == http.MethodPost || r.Method == http.MethodPut { if !strings.Contains(path, "/list") { + if a.failOnce && r.Method == http.MethodPost && path == a.failPath { + a.failOnce = false + return response(500, `{"status":"ERROR","code":"UNKNOWN"}`), nil + } + if a.rejectStable && r.Method == http.MethodPut && strings.Contains(path, "updateStableTemplate") { + return response(400, `{"status":"ERROR","code":"INVALID_REQUEST"}`), nil + } call := copyCall{method: r.Method, path: path, body: string(body), project: project} a.mutating = append(a.mutating, call) a.stored[storeKey(call)] = string(body) diff --git a/modules/platform/projectcopy/transport.go b/modules/platform/projectcopy/transport.go index 938cb215..ff454ae5 100644 --- a/modules/platform/projectcopy/transport.go +++ b/modules/platform/projectcopy/transport.go @@ -52,7 +52,11 @@ func (t *Transport) exchange(ctx context.Context, method, path string, query url if query != nil { base.RawQuery = query.Encode() } - for attempt := 0; attempt < 3; attempt++ { + attempts := retryLimit(method, path, body) + for attempt := 0; attempt < attempts; attempt++ { + if err := refreshAuth(t.auth); err != nil { + return 0, nil, err + } var reader io.Reader if body != "" { reader = strings.NewReader(body) @@ -71,7 +75,7 @@ func (t *Transport) exchange(ctx context.Context, method, path string, query url } resp, err := t.http.Do(req) if err != nil { - if attempt == 2 || ctx.Err() != nil { + if attempt == attempts-1 || ctx.Err() != nil { return 0, nil, errors.New("project copy request failed") } if t.wait(ctx, time.Duration(attempt+1)*time.Second) != nil { @@ -80,7 +84,7 @@ func (t *Transport) exchange(ctx context.Context, method, path string, query url continue } retry := resp.StatusCode == 429 || resp.StatusCode == 502 || resp.StatusCode == 503 || resp.StatusCode == 504 - if retry && attempt < 2 { + if retry && attempt < attempts-1 { delay := time.Duration(attempt+1) * time.Second if raw := resp.Header.Get("Retry-After"); raw != "" { if seconds, e := strconv.Atoi(raw); e == nil && seconds >= 0 { @@ -135,6 +139,9 @@ func (t *Transport) read(ctx context.Context, scope Scope, id string, page int, } base.RawQuery = q.Encode() for attempt := 0; attempt < 3; attempt++ { + if err := refreshAuth(t.auth); err != nil { + return err + } req, err := http.NewRequestWithContext(ctx, method, base.String(), strings.NewReader(body)) if err != nil { return errors.New("cannot prepare secret inventory request") @@ -192,6 +199,33 @@ func (t *Transport) read(ctx context.Context, scope Scope, id string, page int, return errors.New("secret inventory retries exhausted") } +func refreshAuth(a *auth.ResolvedAuth) error { + if a == nil { + return errors.New("project copy authentication required") + } + if err := auth.CheckAndUpdateAccessToken(a, time.Now()); err != nil { + return errors.New("project copy authentication expired") + } + return nil +} + +func retryLimit(method, path, body string) int { + if method == http.MethodGet || method == http.MethodHead { + return 3 + } + if method == http.MethodPost && isReadPost(path, body) { + return 3 + } + return 1 +} + +func isReadPost(path, body string) bool { + if strings.Contains(path, "/list") || strings.HasSuffix(path, "/listDelegates") { + return true + } + return strings.Contains(body, `"filterType"`) +} + func canonicalObject(data []byte, controls ...string) (map[string]json.RawMessage, error) { var fields map[string]json.RawMessage if !unambiguousJSON(data) || json.Unmarshal(data, &fields) != nil || fields == nil {