From c83c17efa7aa63c835892805df4a6f9a273f8f1f Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Thu, 22 Oct 2026 07:16:34 -0500 Subject: [PATCH] feat(package): add import-selection command for project packages --- docs/README.md | 1 + docs/n8n_package.md | 6 +- docs/n8n_package_import-selection.md | 68 +++++++++ internal/cli/help_test.go | 1 + internal/cli/n8n_package.go | 175 ++++++++++++++++++++++- internal/cli/n8n_package_test.go | 187 +++++++++++++++++++++++++ internal/coverage/coverage_test.go | 2 +- internal/coverage/manifest.json | 4 +- internal/n8n/n8n_package.go | 178 +++++++++++++++++++++--- internal/n8n/n8n_package_test.go | 201 +++++++++++++++++++++++++++ test/integration/n8n_package_test.go | 144 +++++++++++++++++++ 11 files changed, 944 insertions(+), 23 deletions(-) create mode 100644 docs/n8n_package_import-selection.md diff --git a/docs/README.md b/docs/README.md index ab7bc7c..1c3a32c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -112,6 +112,7 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n otel test-trace`](n8n_otel_test-trace.md) | Send one test span to an OTLP collector | | [`n8n otel`](n8n_otel.md) | Manage OpenTelemetry tracing settings | | [`n8n package export`](n8n_package_export.md) | Export agents, workflows, folders, or projects as an n8n package (beta) | +| [`n8n package import-selection`](n8n_package_import-selection.md) | Import chosen workflows from one project of an n8n package (beta) | | [`n8n package import`](n8n_package_import.md) | Import an n8n package into a project (beta) | | [`n8n package`](n8n_package.md) | Export and import n8n packages (beta) | | [`n8n project create`](n8n_project_create.md) | Create a project | diff --git a/docs/n8n_package.md b/docs/n8n_package.md index d9fd1fc..aa1e94c 100644 --- a/docs/n8n_package.md +++ b/docs/n8n_package.md @@ -6,7 +6,9 @@ Export and import n8n packages (beta) Move agents, workflows, folders, and projects between instances as gzipped tar packages (.n8np). Start with 'export' to write a package file from this -instance, then 'import' to read one back into a project. +instance, then 'import' to read one back into a project, or +'import-selection' to cherry-pick chosen workflows from one project of a +project package. The whole group is beta: breaking changes may still occur without a major version bump. Export needs the licensed Packages feature. Import can need @@ -25,6 +27,7 @@ n8n package [flags] n8n package export --workflow-id abc123 --out workflows.n8np n8n package export --project-id Ox8O54VQrmBrb4qL --out project.n8np --output json n8n package import --file workflows.n8np --workflow-conflict-policy new-version --yes + n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --workflow-id 2tUt1wbLX592XDdX --yes ``` ### Options @@ -38,4 +41,5 @@ n8n package [flags] * [n8n](n8n.md) - Command-line client for the n8n API * [n8n package export](n8n_package_export.md) - Export agents, workflows, folders, or projects as an n8n package (beta) * [n8n package import](n8n_package_import.md) - Import an n8n package into a project (beta) +* [n8n package import-selection](n8n_package_import-selection.md) - Import chosen workflows from one project of an n8n package (beta) diff --git a/docs/n8n_package_import-selection.md b/docs/n8n_package_import-selection.md new file mode 100644 index 0000000..9cc656f --- /dev/null +++ b/docs/n8n_package_import-selection.md @@ -0,0 +1,68 @@ +## n8n package import-selection + +Import chosen workflows from one project of an n8n package (beta) + +### Synopsis + +Cherry-pick workflows from one source project of a project package +(.n8np) instead of importing the whole package. Send the archive with +--file FILE or --file - for stdin, name the source project with +--project-id as it appears in the package, and list the source workflows +to import with --workflow-id. The workflows are written into the +instance project with that same ID, which is created if it does not +exist yet; there is no target-project or folder flag. + +Use this instead of 'n8n package import' to promote a few workflows +without touching the rest of the project. The import is additive: it +never removes a workflow the selection omits, and it deletes only the +destination workflows listed with --delete-workflow-id (archived by +default; --overwrite-deletion-policy hard-delete also drops their +executions permanently, so prefer archive). --workflow-id may be omitted +for a delete-only run. Selected IDs from another project are dropped, +absent delete IDs are a no-op, and an ID cannot be both imported and +deleted. Folder, tag, and project policies are fixed by the server; only +the workflow conflict, workflow ID, and deletion policies are settable. +A workflow package is rejected with a 400: export a project package with +'n8n package export --project-id'. + +Beta: breaking changes may still occur without a major version bump. +This mutates the instance, so interactive runs ask for confirmation and +non-interactive runs require --yes; --file - also requires --yes because +stdin cannot answer. Needs workflow:import, plus workflow:delete when +deleting or when an update changes a workflow's archive state, and the +licensed Packages feature. Output is the same import result as +'n8n package import'. + +``` +n8n package import-selection [flags] +``` + +### Examples + +``` + n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --workflow-id 2tUt1wbLX592XDdX --workflow-id 7pQr3sTuVwXyZaBc --yes + n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --workflow-id 2tUt1wbLX592XDdX --delete-workflow-id 9xKp2mNqRzAbCdEf --workflow-conflict-policy fail --output json --yes + n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --delete-workflow-id 9xKp2mNqRzAbCdEf --overwrite-deletion-policy hard-delete +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --delete-workflow-id stringArray destination workflow ID to remove from the target project, repeatable; needs workflow:delete and must not match a --workflow-id (default: none) + --file string project package archive (.n8np) to import from: a file path, or - for stdin (required; stdin requires --yes) + -h, --help help for import-selection + --output string output format: text or json (JSON is the full import result) (default "text") + --overwrite-deletion-policy string how --delete-workflow-id removes workflows: archive (recoverable) or hard-delete (also drops executions permanently; prefer archive); needs --delete-workflow-id (default: server default archive) + --project-id string source project ID as it appears in the package; also the target project ID, created if missing (required) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --workflow-conflict-policy string selected workflow that already exists in the target project: new-version updates it, fail rejects the import, skip leaves it unchanged (default: server default new-version) + --workflow-id stringArray source workflow ID to import from --project-id, repeatable (default: none, for a delete-only run with --delete-workflow-id) + --workflow-id-policy string ID for newly created workflows, always sent: source reuses the package ID, new mints a fresh ID (default: source) (default "source") + --yes confirm importing and deleting the listed workflows without prompting (required when stdin is not interactive) +``` + +### SEE ALSO + +* [n8n package](n8n_package.md) - Export and import n8n packages (beta) + diff --git a/internal/cli/help_test.go b/internal/cli/help_test.go index 3fcfdf9..1f10553 100644 --- a/internal/cli/help_test.go +++ b/internal/cli/help_test.go @@ -218,6 +218,7 @@ func TestHelpSucceedsAtEveryLevel(t *testing.T) { {"package"}, {"package", "export"}, {"package", "import"}, + {"package", "import-selection"}, {"git-connection"}, {"git-connection", "list"}, {"git-connection", "create"}, diff --git a/internal/cli/n8n_package.go b/internal/cli/n8n_package.go index 5ba2a7b..2189cde 100644 --- a/internal/cli/n8n_package.go +++ b/internal/cli/n8n_package.go @@ -31,7 +31,9 @@ func newPackageCommand(opts Options) *cobra.Command { Short: "Export and import n8n packages (beta)", Long: "Move agents, workflows, folders, and projects between instances as gzipped tar\n" + "packages (.n8np). Start with 'export' to write a package file from this\n" + - "instance, then 'import' to read one back into a project.\n\n" + + "instance, then 'import' to read one back into a project, or\n" + + "'import-selection' to cherry-pick chosen workflows from one project of a\n" + + "project package.\n\n" + "The whole group is beta: breaking changes may still occur without a major\n" + "version bump. Export needs the licensed Packages feature. Import can need\n" + "the Variables and Folders features as well, and it may publish, archive,\n" + @@ -40,13 +42,15 @@ func newPackageCommand(opts Options) *cobra.Command { "confirmation first.", Example: " n8n package export --workflow-id abc123 --out workflows.n8np\n" + " n8n package export --project-id Ox8O54VQrmBrb4qL --out project.n8np --output json\n" + - " n8n package import --file workflows.n8np --workflow-conflict-policy new-version --yes", + " n8n package import --file workflows.n8np --workflow-conflict-policy new-version --yes\n" + + " n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --workflow-id 2tUt1wbLX592XDdX --yes", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, } cmd.AddCommand( newPackageExportCommand(opts), newPackageImportCommand(opts), + newPackageImportSelectionCommand(opts), ) return cmd } @@ -643,9 +647,169 @@ func importedCredentialIDs(result *n8n.ImportPackageResult) []string { return ids } +type packageImportSelectionFlags struct { + instance instanceFlags + file string + projectID string + workflowIDs []string + deletedIDs []string + workflowConflict string + workflowIDPolicy string + deletionPolicy string + yes bool + output string +} + +func newPackageImportSelectionCommand(opts Options) *cobra.Command { + var f packageImportSelectionFlags + cmd := &cobra.Command{ + Use: "import-selection", + Short: "Import chosen workflows from one project of an n8n package (beta)", + Long: "Cherry-pick workflows from one source project of a project package\n" + + "(.n8np) instead of importing the whole package. Send the archive with\n" + + "--file FILE or --file - for stdin, name the source project with\n" + + "--project-id as it appears in the package, and list the source workflows\n" + + "to import with --workflow-id. The workflows are written into the\n" + + "instance project with that same ID, which is created if it does not\n" + + "exist yet; there is no target-project or folder flag.\n\n" + + "Use this instead of 'n8n package import' to promote a few workflows\n" + + "without touching the rest of the project. The import is additive: it\n" + + "never removes a workflow the selection omits, and it deletes only the\n" + + "destination workflows listed with --delete-workflow-id (archived by\n" + + "default; --overwrite-deletion-policy hard-delete also drops their\n" + + "executions permanently, so prefer archive). --workflow-id may be omitted\n" + + "for a delete-only run. Selected IDs from another project are dropped,\n" + + "absent delete IDs are a no-op, and an ID cannot be both imported and\n" + + "deleted. Folder, tag, and project policies are fixed by the server; only\n" + + "the workflow conflict, workflow ID, and deletion policies are settable.\n" + + "A workflow package is rejected with a 400: export a project package with\n" + + "'n8n package export --project-id'.\n\n" + + "Beta: breaking changes may still occur without a major version bump.\n" + + "This mutates the instance, so interactive runs ask for confirmation and\n" + + "non-interactive runs require --yes; --file - also requires --yes because\n" + + "stdin cannot answer. Needs workflow:import, plus workflow:delete when\n" + + "deleting or when an update changes a workflow's archive state, and the\n" + + "licensed Packages feature. Output is the same import result as\n" + + "'n8n package import'.", + Example: " n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --workflow-id 2tUt1wbLX592XDdX --workflow-id 7pQr3sTuVwXyZaBc --yes\n" + + " n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --workflow-id 2tUt1wbLX592XDdX --delete-workflow-id 9xKp2mNqRzAbCdEf --workflow-conflict-policy fail --output json --yes\n" + + " n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --delete-workflow-id 9xKp2mNqRzAbCdEf --overwrite-deletion-policy hard-delete", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return runPackageImportSelection(cmd.Context(), opts, f) + }, + } + f.instance.register(cmd) + cmd.Flags().StringVar(&f.file, "file", "", "project package archive (.n8np) to import from: a file path, or - for stdin (required; stdin requires --yes)") + cmd.Flags().StringVar(&f.projectID, "project-id", "", "source project ID as it appears in the package; also the target project ID, created if missing (required)") + cmd.Flags().StringArrayVar(&f.workflowIDs, "workflow-id", nil, "source workflow ID to import from --project-id, repeatable (default: none, for a delete-only run with --delete-workflow-id)") + cmd.Flags().StringArrayVar(&f.deletedIDs, "delete-workflow-id", nil, "destination workflow ID to remove from the target project, repeatable; needs workflow:delete and must not match a --workflow-id (default: none)") + cmd.Flags().StringVar(&f.workflowConflict, "workflow-conflict-policy", "", "selected workflow that already exists in the target project: new-version updates it, fail rejects the import, skip leaves it unchanged (default: server default new-version)") + cmd.Flags().StringVar(&f.workflowIDPolicy, "workflow-id-policy", n8n.ImportWorkflowIDSource, "ID for newly created workflows, always sent: source reuses the package ID, new mints a fresh ID (default: source)") + cmd.Flags().StringVar(&f.deletionPolicy, "overwrite-deletion-policy", "", "how --delete-workflow-id removes workflows: archive (recoverable) or hard-delete (also drops executions permanently; prefer archive); needs --delete-workflow-id (default: server default archive)") + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm importing and deleting the listed workflows without prompting (required when stdin is not interactive)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the full import result)") + return cmd +} + +func runPackageImportSelection(ctx context.Context, opts Options, f packageImportSelectionFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if strings.TrimSpace(f.file) == "" { + return fmt.Errorf("--file is required: pass the .n8np project package archive, or - for stdin") + } + if strings.TrimSpace(f.projectID) == "" { + return fmt.Errorf("--project-id is required: pass the source project ID as it appears in the package") + } + if len(f.workflowIDs) == 0 && len(f.deletedIDs) == 0 { + return fmt.Errorf("nothing to import or delete: pass --workflow-id, --delete-workflow-id, or both") + } + if f.file == "-" && !f.yes { + return fmt.Errorf("--file - consumes stdin and cannot answer the import confirmation: pass --yes after reviewing the selection and policies") + } + request := n8n.ImportPackageSelectionRequest{ + ProjectID: strings.TrimSpace(f.projectID), + WorkflowIDs: trimmedIDs(f.workflowIDs), + DeletedWorkflowIDs: trimmedIDs(f.deletedIDs), + WorkflowConflictPolicy: strings.TrimSpace(f.workflowConflict), + WorkflowIDPolicy: strings.TrimSpace(f.workflowIDPolicy), + OverwriteDeletionPolicy: strings.TrimSpace(f.deletionPolicy), + } + if err := request.Validate(); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + if err := opts.confirmer(f.yes).Confirm(packageImportSelectionQuestion(f.file, request, resolution)); err != nil { + return err + } + archive, filename, cleanup, err := openPackageArchive(opts, f.file) + if err != nil { + return err + } + defer cleanup() + result, err := client.ImportPackageSelection(ctx, request, archive, filename) + if err != nil { + need := allOf("workflow:import") + if len(request.DeletedWorkflowIDs) > 0 { + need = allOf("workflow:import", "workflow:delete") + } + return packageAPIError(err, resolution, "import-selection", need) + } + if f.output == outputJSON { + return writeJSON(opts.Streams.Out, result) + } + return writePackageImportText(opts, resolution, result) +} + +// trimmedIDs trims each repeatable ID flag value; empty values stay so +// validation can name them. +func trimmedIDs(ids []string) []string { + if len(ids) == 0 { + return nil + } + trimmed := make([]string, len(ids)) + for i, id := range ids { + trimmed[i] = strings.TrimSpace(id) + } + return trimmed +} + +func packageImportSelectionQuestion(file string, request n8n.ImportPackageSelectionRequest, resolution config.Resolution) string { + question := fmt.Sprintf("Import %d workflow(s) from source project %q of package %q into project %q on %s (the instance project with the same ID, created if missing)?", + len(request.WorkflowIDs), request.ProjectID, displayPackageName(file), request.ProjectID, resolution.URL) + if len(request.WorkflowIDs) > 0 { + conflict := request.WorkflowConflictPolicy + if conflict == "" { + conflict = n8n.ImportWorkflowConflictNewVersion + " (server default)" + } + question += fmt.Sprintf(" Existing workflows use %q and new workflows take %q IDs.", conflict, request.WorkflowIDPolicy) + } + switch { + case len(request.DeletedWorkflowIDs) == 0: + question += " No workflow is deleted." + case request.OverwriteDeletionPolicy == n8n.ImportDeletionHardDelete: + question += fmt.Sprintf(" Hard-delete PERMANENTLY deletes %d workflow(s) (%s) with their executions; this cannot be undone, prefer archive.", + len(request.DeletedWorkflowIDs), strings.Join(request.DeletedWorkflowIDs, ", ")) + default: + question += fmt.Sprintf(" %d workflow(s) (%s) are archived (recoverable).", + len(request.DeletedWorkflowIDs), strings.Join(request.DeletedWorkflowIDs, ", ")) + } + return question +} + // packageAPIError restates the fix for a failed export or import. need is the // scope requirement reported on a 403. func packageAPIError(err error, resolution config.Resolution, action string, need scopeNeed) error { + if blocked, ok := n8n.AsImportBlocked(err); ok && action == "import-selection" { + if blocked.StatusCode == http.StatusConflict { + return fmt.Errorf("%s rejected the selection import (409): %d conflict issue(s) and nothing was written; a workflow-removal-conflict means a --delete-workflow-id matches a selected workflow's destination, so drop it from one list, and a workflow conflict under fail needs --workflow-conflict-policy new-version or skip: %w", resolution.URL, len(blocked.Issues), err) + } + return fmt.Errorf("%s rejected the selection import (422): %d blocking issue(s); workflow-removal-forbidden needs the workflow:delete scope, and unresolved credentials or unknown node types must exist on this instance first, then retry: %w", resolution.URL, len(blocked.Issues), err) + } if blocked, ok := n8n.AsImportBlocked(err); ok && action == "import" { if blocked.StatusCode == http.StatusConflict { return fmt.Errorf("%s rejected the package import (409): %d conflict issue(s); nothing matched with fail stays unchanged, so adjust a conflict policy such as --workflow-conflict-policy, --project-conflict-policy, --folder-conflict-policy, --tag-conflict-policy, or --variable-conflict-policy and retry: %w", resolution.URL, len(blocked.Issues), err) @@ -657,12 +821,19 @@ func packageAPIError(err error, resolution config.Resolution, action string, nee if action == "export" { return fmt.Errorf("%s rejected the package export (400): check the selected IDs (unknown, mixed project and loose groups, agents without the agents module, or missing dependencies under --dependency-policy fail) and --version-policy: %w", resolution.URL, err) } + if action == "import-selection" { + return fmt.Errorf("%s rejected the selection import (400): it needs a project package (export one with 'n8n package export --project-id'; workflow packages are rejected), a well-formed archive, and a --project-id that exists in the package: %w", resolution.URL, err) + } return fmt.Errorf("%s rejected the package import (400): the archive is malformed, the manifest is missing, or a routing or policy field is invalid (bindings JSON, --variable-parent-policy on a project package): %w", resolution.URL, err) case n8n.IsForbidden(err): if action == "export" { return forbiddenScopeError(err, resolution, "package export", need, "variable:list is also needed when exported entities reference variables and values are included, agent exports need the agents module, and the instance needs the licensed Packages feature.", packageResource) } + if action == "import-selection" { + return forbiddenScopeError(err, resolution, "package import-selection", need, + "workflow:delete is also needed when an update changes a workflow's archive state, and the instance needs the licensed Packages feature.", packageResource) + } return forbiddenScopeError(err, resolution, "package import", need, "the import also needs the credential (create-with-values), variable, tag, data-table (dataTable:update for schema overwrite), folder and delete scopes the package and policies require, and the instance needs the licensed Packages feature.", packageResource) case n8n.IsNotFound(err): diff --git a/internal/cli/n8n_package_test.go b/internal/cli/n8n_package_test.go index 5fc7527..74beddd 100644 --- a/internal/cli/n8n_package_test.go +++ b/internal/cli/n8n_package_test.go @@ -612,3 +612,190 @@ func TestPackageExportBetaIsVisible(t *testing.T) { } } } + +func TestPackageImportSelectionConfirmationAndBody(t *testing.T) { + f := packageFixture(t, cliPackageImportResult) + archive := writePackageArchive(t, cliPackageArchive) + before := f.requestCount() + f.stdin = "no\n" + + args := []string{"package", "import-selection", "--file", archive, "--project-id", "src-p", + "--workflow-id", "wf-1", "--workflow-id", "wf-2", "--delete-workflow-id", "wf-9"} + got := f.run(args...) + if got.code != ExitError || !strings.Contains(got.stderr, "aborted") || f.requestCount() != before { + t.Errorf("declined result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + for _, want := range []string{"2 workflow(s)", `project "src-p"`, "created if missing", "new-version", `"source"`, "wf-9", "archived"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("prompt = %q, want %q", got.stderr, want) + } + } + + f.interactive = false + got = f.run(args...) + if got.code != ExitError || !strings.Contains(got.stderr, "pass --yes") || f.requestCount() != before { + t.Errorf("non-interactive result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + got = f.run(append(args, "--workflow-conflict-policy", "skip", "--yes", "--output", "json")...) + if got.code != ExitSuccess { + t.Fatalf("confirmed exit = %d, stderr: %s", got.code, got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodPost || req.URL.Path != n8n.BasePath+n8n.N8nPackageImportSelectionPath { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + fields, fileBytes, filename := parseCLIImportMultipart(t, f) + want := map[string]string{ + "selectedProjectId": "src-p", + "selectedWorkflowIds": `["wf-1","wf-2"]`, + "deletedWorkflowIds": `["wf-9"]`, + "workflowConflictPolicy": "skip", + "workflowIdPolicy": "source", + } + for name, value := range want { + if fields[name] != value { + t.Errorf("field %s = %q, want %q (all: %v)", name, fields[name], value, fields) + } + } + if len(fields) != len(want) { + t.Errorf("fields = %v, want exactly %v", fields, want) + } + if fileBytes != cliPackageArchive || filename != "test-package.n8np" { + t.Errorf("package = %q (%q), want the archive bytes and base name", fileBytes, filename) + } + var result n8n.ImportPackageResult + if err := json.Unmarshal([]byte(got.stdout), &result); err != nil || len(result.Workflows) != 2 { + t.Errorf("stdout = %q, want the import result (error: %v)", got.stdout, err) + } +} + +func TestPackageImportSelectionText(t *testing.T) { + f := packageFixture(t, cliPackageImportResult) + archive := writePackageArchive(t, cliPackageArchive) + + got := f.run("package", "import-selection", "--file", archive, "--project-id", "p1", "--workflow-id", "wf-src", "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"Imported:", "2 workflows", "1 created", "wf-local"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } +} + +func TestPackageImportSelectionHardDeleteWarnsStronger(t *testing.T) { + f := packageFixture(t, cliPackageImportResult) + archive := writePackageArchive(t, cliPackageArchive) + f.stdin = "no\n" + + got := f.run("package", "import-selection", "--file", archive, "--project-id", "p1", + "--delete-workflow-id", "wf-old", "--overwrite-deletion-policy", "hard-delete") + if got.code != ExitError { + t.Fatalf("exit = %d, want a decline (stderr: %s)", got.code, got.stderr) + } + for _, want := range []string{"0 workflow(s)", "PERMANENTLY", "executions", "cannot be undone", "prefer archive", "wf-old"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("prompt = %q, want %q", got.stderr, want) + } + } +} + +func TestPackageImportSelectionStdinRequiresYes(t *testing.T) { + f := packageFixture(t, cliPackageImportResult) + f.stdin = cliPackageArchive + before := f.requestCount() + + got := f.run("package", "import-selection", "--file", "-", "--project-id", "p1", "--workflow-id", "a") + if got.code != ExitError || !strings.Contains(got.stderr, "--yes") || f.requestCount() != before { + t.Errorf("stdin without --yes result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + f.stdin = cliPackageArchive + got = f.run("package", "import-selection", "--file", "-", "--project-id", "p1", "--workflow-id", "a", "--yes", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("stdin exit = %d, stderr: %s", got.code, got.stderr) + } + _, fileBytes, filename := parseCLIImportMultipart(t, f) + if fileBytes != cliPackageArchive || filename != n8n.DefaultImportPackageFilename { + t.Errorf("package = %q (%q), want stdin bytes under the default name", fileBytes, filename) + } +} + +func TestPackageImportSelectionRejectsBadInputBeforeTransport(t *testing.T) { + f := packageFixture(t, cliPackageImportResult) + archive := writePackageArchive(t, cliPackageArchive) + before := f.requestCount() + + cmd := func(extra ...string) []string { + return append([]string{"package", "import-selection"}, append(extra, "--yes")...) + } + cases := []struct { + args []string + want string + }{ + {cmd("--project-id", "p", "--workflow-id", "a"), "--file is required"}, + {cmd("--file", archive, "--workflow-id", "a"), "--project-id is required"}, + {cmd("--file", archive, "--project-id", "p"), "nothing to import or delete"}, + {cmd("--file", archive, "--project-id", "p", "--workflow-id", "a", "--workflow-id", "a"), "more than once"}, + {cmd("--file", archive, "--project-id", "p", "--delete-workflow-id", "b", "--delete-workflow-id", "b"), "more than once"}, + {cmd("--file", archive, "--project-id", "p", "--workflow-id", "a", "--delete-workflow-id", "a"), "both selected for import and listed for deletion"}, + {cmd("--file", archive, "--project-id", "p", "--workflow-id", ""), "must not be empty"}, + {cmd("--file", archive, "--project-id", "p", "--workflow-id", "a", "--workflow-conflict-policy", "sometimes"), "workflow-conflict policy"}, + {cmd("--file", archive, "--project-id", "p", "--workflow-id", "a", "--workflow-id-policy", "sometimes"), "workflow-id policy"}, + {cmd("--file", archive, "--project-id", "p", "--delete-workflow-id", "b", "--overwrite-deletion-policy", "purge"), "overwrite-deletion policy"}, + {cmd("--file", archive, "--project-id", "p", "--workflow-id", "a", "--overwrite-deletion-policy", "archive"), "only applies to deleted workflow IDs"}, + {cmd("--file", archive, "--project-id", "p", "--workflow-id", "a", "--output", "yaml"), "yaml"}, + {cmd("--file", filepath.Join(t.TempDir(), "missing.n8np"), "--project-id", "p", "--workflow-id", "a"), "open package archive"}, + } + for _, tc := range cases { + got := f.run(tc.args...) + if got.code != ExitError || !strings.Contains(got.stderr, tc.want) { + t.Errorf("%v = exit %d, stderr %q; want exit %d naming %q", tc.args, got.code, got.stderr, ExitError, tc.want) + } + } + if f.requestCount() != before { + t.Errorf("requests = %d, want %d before transport", f.requestCount(), before) + } +} + +func TestPackageImportSelectionErrorsPointAtFix(t *testing.T) { + f := packageFixture(t, "") + archive := writePackageArchive(t, cliPackageArchive) + args := []string{"package", "import-selection", "--file", archive, "--project-id", "p", "--workflow-id", "a", "--delete-workflow-id", "b", "--yes"} + + f.status = http.StatusConflict + f.body = `{"message":"overlap","issues":[{"type":"workflow-removal-conflict","workflowId":"b"}]}` + got := f.run(args...) + if got.code != ExitError || !strings.Contains(got.stderr, "409") || !strings.Contains(got.stderr, "workflow-removal-conflict") || !strings.Contains(got.stderr, "--delete-workflow-id") { + t.Errorf("409 result = %+v, want the removal-conflict remediation", got) + } + + f.status = http.StatusUnprocessableEntity + f.body = `{"message":"denied","issues":[{"type":"workflow-removal-forbidden","workflowId":"b"}]}` + got = f.run(args...) + if got.code != ExitError || !strings.Contains(got.stderr, "422") || !strings.Contains(got.stderr, "workflow:delete") { + t.Errorf("422 result = %+v, want the delete-scope remediation", got) + } + + f.status = http.StatusBadRequest + f.body = `{"message":"not a project package"}` + got = f.run(args...) + if got.code != ExitError || !strings.Contains(got.stderr, "400") || !strings.Contains(got.stderr, "project package") || !strings.Contains(got.stderr, "n8n package export --project-id") { + t.Errorf("400 result = %+v, want the project-package hint", got) + } + + f.status = http.StatusForbidden + f.body = `{"message":"denied"}` + got = f.run(args...) + if got.code != ExitError || !strings.Contains(got.stderr, "workflow:import") || !strings.Contains(got.stderr, "workflow:delete") || !strings.Contains(got.stderr, "n8n discover --resource n8npackage") { + t.Errorf("403 result = %+v, want both scopes and the discover hint", got) + } + + f.status = http.StatusNotFound + got = f.run(args...) + if got.code != ExitError || !strings.Contains(got.stderr, "Packages") || !strings.Contains(got.stderr, "n8n discover --resource n8npackage") { + t.Errorf("404 result = %+v, want the availability hint", got) + } +} diff --git a/internal/coverage/coverage_test.go b/internal/coverage/coverage_test.go index 9aa90a3..936a528 100644 --- a/internal/coverage/coverage_test.go +++ b/internal/coverage/coverage_test.go @@ -327,7 +327,7 @@ func TestAvailabilityMatchesSpecs(t *testing.T) { // // A phase is never excused because one server does not serve its resource: // every phase owns operations from the union of the documents. -const deliveredThrough = 29 +const deliveredThrough = 30 // TestPhaseCounts is how a phase exit gate reads the manifest: every operation // a delivered phase owns must be implemented, and no later phase may have diff --git a/internal/coverage/manifest.json b/internal/coverage/manifest.json index 7abad2e..bc69c9c 100644 --- a/internal/coverage/manifest.json +++ b/internal/coverage/manifest.json @@ -1749,8 +1749,8 @@ "scope": "workflow:import", "availability": "both", "phase": 30, - "command": "", - "status": "planned" + "command": "n8n package import-selection", + "status": "implemented" }, { "operationId": "getPromotionChanges", diff --git a/internal/n8n/n8n_package.go b/internal/n8n/n8n_package.go index ecd4c5d..fce7afd 100644 --- a/internal/n8n/n8n_package.go +++ b/internal/n8n/n8n_package.go @@ -14,6 +14,7 @@ import ( "errors" "fmt" "io" + "maps" "mime" "mime/multipart" "net/http" @@ -24,8 +25,9 @@ import ( // n8n package endpoints. const ( - N8nPackageExportPath = "/n8n-packages/export" - N8nPackageImportPath = "/n8n-packages/import" + N8nPackageExportPath = "/n8n-packages/export" + N8nPackageImportPath = "/n8n-packages/import" + N8nPackageImportSelectionPath = "/n8n-packages/import-selection" ) // ExportCountsHeader carries the JSON-serialized per-entity counts of what @@ -487,6 +489,125 @@ func (r ImportPackageRequest) fields() map[string]string { return fields } +// ImportPackageSelectionRequest cherry-picks workflows from one source project +// of a project package. The workflows land in the instance project whose ID +// equals ProjectID, created if missing; there is no target-project field. +// Folder, tag, and project policies are fixed by the server. +// +// WorkflowIDs are source IDs within ProjectID and may be empty for a +// delete-only request. DeletedWorkflowIDs are destination IDs in the same +// project, removed per OverwriteDeletionPolicy (server default archive). +// Empty optional policies are omitted so the server default applies, except +// WorkflowIDPolicy, which is always sent like [ImportPackageRequest]. +type ImportPackageSelectionRequest struct { + ProjectID string + WorkflowIDs []string + DeletedWorkflowIDs []string + WorkflowConflictPolicy string + WorkflowIDPolicy string + OverwriteDeletionPolicy string +} + +// Validate rejects a selection the API would reject before transport. A +// workflow ID named both for import and for deletion is refused: the server +// answers 409 workflow-removal-conflict when a delete matches a selected +// workflow's destination, which under the source ID policy is the same ID. +func (r ImportPackageSelectionRequest) Validate() error { + if strings.TrimSpace(r.ProjectID) == "" { + return fmt.Errorf("source project ID is required: pass the project ID as it appears in the package") + } + if strings.TrimSpace(r.ProjectID) != r.ProjectID { + return fmt.Errorf("project ID must not start or end with whitespace") + } + if len(r.WorkflowIDs) == 0 && len(r.DeletedWorkflowIDs) == 0 { + return fmt.Errorf("nothing to import or delete: pass at least one workflow ID to import or to delete") + } + selected := map[string]bool{} + for _, id := range r.WorkflowIDs { + if err := validateSelectionID("workflow ID", id); err != nil { + return err + } + if selected[id] { + return fmt.Errorf("workflow ID %q is selected more than once: list each workflow once", id) + } + selected[id] = true + } + deleted := map[string]bool{} + for _, id := range r.DeletedWorkflowIDs { + if err := validateSelectionID("deleted workflow ID", id); err != nil { + return err + } + if deleted[id] { + return fmt.Errorf("deleted workflow ID %q is listed more than once: list each workflow once", id) + } + if selected[id] { + return fmt.Errorf("workflow ID %q is both selected for import and listed for deletion: a delete must not match a selected workflow, so drop it from one list", id) + } + deleted[id] = true + } + if r.WorkflowConflictPolicy != "" && !slices.Contains(importWorkflowConflicts, r.WorkflowConflictPolicy) { + return fmt.Errorf("unknown workflow-conflict policy %q: use %s", r.WorkflowConflictPolicy, strings.Join(importWorkflowConflicts, ", ")) + } + if !slices.Contains(importWorkflowIDPolicies, r.WorkflowIDPolicy) { + return fmt.Errorf("unknown workflow-id policy %q: use %s", r.WorkflowIDPolicy, strings.Join(importWorkflowIDPolicies, ", ")) + } + if r.OverwriteDeletionPolicy != "" { + if !slices.Contains(importDeletionPolicies, r.OverwriteDeletionPolicy) { + return fmt.Errorf("unknown overwrite-deletion policy %q: use %s", r.OverwriteDeletionPolicy, strings.Join(importDeletionPolicies, ", ")) + } + if len(r.DeletedWorkflowIDs) == 0 { + return fmt.Errorf("overwrite-deletion policy %q only applies to deleted workflow IDs: list the workflows to delete or drop the policy", r.OverwriteDeletionPolicy) + } + } + return nil +} + +func validateSelectionID(name, id string) error { + if strings.TrimSpace(id) == "" { + return fmt.Errorf("%s must not be empty", name) + } + if strings.TrimSpace(id) != id { + return fmt.Errorf("%s %q must not start or end with whitespace", name, id) + } + return nil +} + +// fields renders the selection as multipart form fields. The ID lists travel +// as JSON-encoded string arrays; selectedWorkflowIds is always present, as [] +// when empty, and deletedWorkflowIds only when it names a workflow. +func (r ImportPackageSelectionRequest) fields() (map[string]string, error) { + selected, err := json.Marshal(nonNilStrings(r.WorkflowIDs)) + if err != nil { + return nil, fmt.Errorf("encode selected workflow IDs: %w", err) + } + fields := map[string]string{ + "selectedProjectId": r.ProjectID, + "selectedWorkflowIds": string(selected), + "workflowIdPolicy": r.WorkflowIDPolicy, + } + if len(r.DeletedWorkflowIDs) > 0 { + deleted, err := json.Marshal(r.DeletedWorkflowIDs) + if err != nil { + return nil, fmt.Errorf("encode deleted workflow IDs: %w", err) + } + fields["deletedWorkflowIds"] = string(deleted) + } + if r.WorkflowConflictPolicy != "" { + fields["workflowConflictPolicy"] = r.WorkflowConflictPolicy + } + if r.OverwriteDeletionPolicy != "" { + fields["overwriteDeletionPolicy"] = r.OverwriteDeletionPolicy + } + return fields, nil +} + +func nonNilStrings(values []string) []string { + if values == nil { + return []string{} + } + return values +} + // ImportPackageResult is the import outcome: what was written, removed, and // how every referenced entity resolved. Names only travel for variables and // tags; values never travel in the response. @@ -560,7 +681,7 @@ type ImportPublishing struct { } // RemovedWorkflow is a target workflow removed by folderConflictPolicy -// overwrite. Deletion reports what actually happened: a hard-delete that +// overwrite, or listed for deletion in an import selection. Deletion reports what actually happened: a hard-delete that // could not drop its row yet stays archived. type RemovedWorkflow struct { WorkflowID string `json:"workflowId"` @@ -756,6 +877,29 @@ func (c *Client) ImportPackage(ctx context.Context, request ImportPackageRequest if err := request.Validate(); err != nil { return nil, err } + return c.postPackageImport(ctx, N8nPackageImportPath, request.fields(), packageData, filename) +} + +// ImportPackageSelection cherry-picks workflows from one source project of a +// project package into the instance project with the same ID, created if +// missing. It never removes a workflow the selection omits; it deletes only +// request.DeletedWorkflowIDs. The archive streams like [Client.ImportPackage] +// and the result has the same shape. The caller confirms first. +func (c *Client) ImportPackageSelection(ctx context.Context, request ImportPackageSelectionRequest, packageData io.Reader, filename string) (*ImportPackageResult, error) { + if err := request.Validate(); err != nil { + return nil, err + } + fields, err := request.fields() + if err != nil { + return nil, err + } + return c.postPackageImport(ctx, N8nPackageImportSelectionPath, fields, packageData, filename) +} + +// postPackageImport streams fields and the archive to an import endpoint and +// decodes the shared import result. A 409 or 422 becomes an +// [*ImportBlockedError] naming path. +func (c *Client) postPackageImport(ctx context.Context, path string, fields map[string]string, packageData io.Reader, filename string) (*ImportPackageResult, error) { if packageData == nil { return nil, fmt.Errorf("package archive is required: pass the .n8np bytes") } @@ -771,12 +915,12 @@ func (c *Client) ImportPackage(ctx context.Context, request ImportPackageRequest defer cancel() } - importEndpoint, err := c.resolve(N8nPackageImportPath, nil) + importEndpoint, err := c.resolve(path, nil) if err != nil { return nil, err } - body, contentType := multipartImportBody(request, packageData, filename) + body, contentType := multipartImportBody(fields, packageData, filename) req, err := http.NewRequestWithContext(ctx, http.MethodPost, importEndpoint.String(), body) if err != nil { return nil, fmt.Errorf("n8n: build request: %w", err) @@ -803,9 +947,9 @@ func (c *Client) ImportPackage(ctx context.Context, request ImportPackageRequest "error", err, ) if ctxErr := ctx.Err(); ctxErr != nil { - return nil, fmt.Errorf("n8n: POST %s: %w", N8nPackageImportPath, ctxErr) + return nil, fmt.Errorf("n8n: POST %s: %w", path, ctxErr) } - return nil, fmt.Errorf("n8n: POST %s: %w", N8nPackageImportPath, err) + return nil, fmt.Errorf("n8n: POST %s: %w", path, err) } defer drainAndClose(resp.Body) @@ -820,21 +964,21 @@ func (c *Client) ImportPackage(ctx context.Context, request ImportPackageRequest if resp.StatusCode == http.StatusConflict || resp.StatusCode == http.StatusUnprocessableEntity { raw, _, err := readLimited(resp.Body, maxErrorBody) if err != nil { - return nil, fmt.Errorf("n8n: POST %s: read error response: %w", N8nPackageImportPath, err) + return nil, fmt.Errorf("n8n: POST %s: read error response: %w", path, err) } - return nil, newImportBlockedError(resp, N8nPackageImportPath, raw) + return nil, newImportBlockedError(resp, path, raw) } if resp.StatusCode < 200 || resp.StatusCode > 299 { raw, truncated, err := readLimited(resp.Body, maxErrorBody) if err != nil { - return nil, fmt.Errorf("n8n: POST %s: read error response: %w", N8nPackageImportPath, err) + return nil, fmt.Errorf("n8n: POST %s: read error response: %w", path, err) } - return nil, newAPIError(resp, http.MethodPost, N8nPackageImportPath, raw, truncated) + return nil, newAPIError(resp, http.MethodPost, path, raw, truncated) } var result ImportPackageResult if err := decodeBody(resp, &result); err != nil { - return nil, fmt.Errorf("n8n: POST %s: %w", N8nPackageImportPath, err) + return nil, fmt.Errorf("n8n: POST %s: %w", path, err) } return &result, nil } @@ -842,20 +986,20 @@ func (c *Client) ImportPackage(ctx context.Context, request ImportPackageRequest // multipartImportBody streams the policy fields and the archive through a // pipe: the writer side runs in a goroutine, so the HTTP transport reads // while the archive streams without an intermediate buffer. -func multipartImportBody(request ImportPackageRequest, packageData io.Reader, filename string) (io.Reader, string) { +func multipartImportBody(fields map[string]string, packageData io.Reader, filename string) (io.Reader, string) { reader, writer := io.Pipe() multipartWriter := multipart.NewWriter(writer) contentType := multipartWriter.FormDataContentType() go func() { - err := writeMultipartImport(multipartWriter, request, packageData, filename) + err := writeMultipartImport(multipartWriter, fields, packageData, filename) _ = writer.CloseWithError(err) }() return reader, contentType } -func writeMultipartImport(multipartWriter *multipart.Writer, request ImportPackageRequest, packageData io.Reader, filename string) error { - for name, value := range request.fields() { - if err := multipartWriter.WriteField(name, value); err != nil { +func writeMultipartImport(multipartWriter *multipart.Writer, fields map[string]string, packageData io.Reader, filename string) error { + for _, name := range slices.Sorted(maps.Keys(fields)) { + if err := multipartWriter.WriteField(name, fields[name]); err != nil { _ = multipartWriter.Close() return fmt.Errorf("write import field %s: %w", name, err) } diff --git a/internal/n8n/n8n_package_test.go b/internal/n8n/n8n_package_test.go index 299ca63..de3a969 100644 --- a/internal/n8n/n8n_package_test.go +++ b/internal/n8n/n8n_package_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "io" "mime" "mime/multipart" @@ -571,3 +572,203 @@ func TestImportPackageOtherErrors(t *testing.T) { }) } } + +func TestImportPackageSelectionStreamsMultipart(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, packageImportResultJSON)) + + result, err := server.client(t).ImportPackageSelection(context.Background(), ImportPackageSelectionRequest{ + ProjectID: "src-project", + WorkflowIDs: []string{"wf-1", "wf-2"}, + DeletedWorkflowIDs: []string{"wf-3"}, + WorkflowConflictPolicy: ImportWorkflowConflictSkip, + WorkflowIDPolicy: ImportWorkflowIDNew, + OverwriteDeletionPolicy: ImportDeletionHardDelete, + }, strings.NewReader(packageArchiveBytes), "project.n8np") + if err != nil { + t.Fatalf("ImportPackageSelection: %v", err) + } + req, raw := server.last(t) + if req.Method != http.MethodPost || req.URL.Path != BasePath+N8nPackageImportSelectionPath { + t.Errorf("request = %s %s, want POST %s", req.Method, req.URL.Path, BasePath+N8nPackageImportSelectionPath) + } + if got := req.Header.Get(HeaderAPIKey); got != "community-secret" { + t.Errorf("%s = %q, want API key", HeaderAPIKey, got) + } + fields, fileBytes, filename := parseMultipartImport(t, req, []byte(raw)) + want := map[string]string{ + "selectedProjectId": "src-project", + "selectedWorkflowIds": `["wf-1","wf-2"]`, + "deletedWorkflowIds": `["wf-3"]`, + "workflowConflictPolicy": ImportWorkflowConflictSkip, + "workflowIdPolicy": ImportWorkflowIDNew, + "overwriteDeletionPolicy": ImportDeletionHardDelete, + } + if diff := cmp.Diff(want, fields); diff != "" { + t.Errorf("fields mismatch (-want +got):\n%s", diff) + } + if fileBytes != packageArchiveBytes || filename != "project.n8np" { + t.Errorf("package = %q (%q), want the streamed archive and its name", fileBytes, filename) + } + if len(result.Workflows) != 1 || result.Workflows[0].LocalID != "wf-local" { + t.Errorf("result = %+v, want the shared import result", result) + } +} + +func TestImportPackageSelectionOmitsUnsetFields(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, packageImportResultJSON)) + + _, err := server.client(t).ImportPackageSelection(context.Background(), ImportPackageSelectionRequest{ + ProjectID: "src-project", + DeletedWorkflowIDs: []string{"wf-3"}, + WorkflowIDPolicy: ImportWorkflowIDSource, + }, strings.NewReader(packageArchiveBytes), "") + if err != nil { + t.Fatalf("ImportPackageSelection: %v", err) + } + req, raw := server.last(t) + fields, _, filename := parseMultipartImport(t, req, []byte(raw)) + want := map[string]string{ + "selectedProjectId": "src-project", + "selectedWorkflowIds": `[]`, + "deletedWorkflowIds": `["wf-3"]`, + "workflowIdPolicy": ImportWorkflowIDSource, + } + if diff := cmp.Diff(want, fields); diff != "" { + t.Errorf("delete-only fields mismatch (-want +got):\n%s", diff) + } + if filename != DefaultImportPackageFilename { + t.Errorf("filename = %q, want %q", filename, DefaultImportPackageFilename) + } + + _, err = server.client(t).ImportPackageSelection(context.Background(), ImportPackageSelectionRequest{ + ProjectID: "src-project", + WorkflowIDs: []string{"wf-1"}, + WorkflowIDPolicy: ImportWorkflowIDSource, + }, strings.NewReader(packageArchiveBytes), "p.n8np") + if err != nil { + t.Fatalf("ImportPackageSelection: %v", err) + } + req, raw = server.last(t) + fields, _, _ = parseMultipartImport(t, req, []byte(raw)) + for _, name := range []string{"deletedWorkflowIds", "workflowConflictPolicy", "overwriteDeletionPolicy"} { + if _, present := fields[name]; present { + t.Errorf("%s = present, want omitted when unset", name) + } + } +} + +func TestImportPackageSelectionValidation(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, packageImportResultJSON)) + client := server.client(t) + + base := func(mutate func(*ImportPackageSelectionRequest)) ImportPackageSelectionRequest { + request := ImportPackageSelectionRequest{ + ProjectID: "p", + WorkflowIDs: []string{"a"}, + WorkflowIDPolicy: ImportWorkflowIDSource, + } + mutate(&request) + return request + } + cases := map[string]ImportPackageSelectionRequest{ + "no project": base(func(r *ImportPackageSelectionRequest) { r.ProjectID = "" }), + "padded project": base(func(r *ImportPackageSelectionRequest) { r.ProjectID = " p " }), + "nothing selected": base(func(r *ImportPackageSelectionRequest) { r.WorkflowIDs = nil }), + "empty workflow id": base(func(r *ImportPackageSelectionRequest) { r.WorkflowIDs = []string{""} }), + "padded workflow id": base(func(r *ImportPackageSelectionRequest) { r.WorkflowIDs = []string{"a "} }), + "duplicate selected": base(func(r *ImportPackageSelectionRequest) { r.WorkflowIDs = []string{"a", "a"} }), + "duplicate deleted": base(func(r *ImportPackageSelectionRequest) { r.DeletedWorkflowIDs = []string{"b", "b"} }), + "selected and deleted": base(func(r *ImportPackageSelectionRequest) { r.DeletedWorkflowIDs = []string{"a"} }), + "empty deleted id": base(func(r *ImportPackageSelectionRequest) { r.DeletedWorkflowIDs = []string{" "} }), + "bad conflict policy": base(func(r *ImportPackageSelectionRequest) { r.WorkflowConflictPolicy = "sometimes" }), + "missing id policy": base(func(r *ImportPackageSelectionRequest) { r.WorkflowIDPolicy = "" }), + "bad id policy": base(func(r *ImportPackageSelectionRequest) { r.WorkflowIDPolicy = "sometimes" }), + "bad deletion policy": base(func(r *ImportPackageSelectionRequest) { + r.DeletedWorkflowIDs = []string{"b"} + r.OverwriteDeletionPolicy = "sometimes" + }), + "deletion without delete": base(func(r *ImportPackageSelectionRequest) { r.OverwriteDeletionPolicy = ImportDeletionArchive }), + } + for name, request := range cases { + if _, err := client.ImportPackageSelection(context.Background(), request, strings.NewReader(packageArchiveBytes), "p.n8np"); err == nil { + t.Errorf("%s: want a validation error", name) + } + } + if _, err := client.ImportPackageSelection(context.Background(), base(func(*ImportPackageSelectionRequest) {}), nil, "p.n8np"); err == nil { + t.Error("nil archive: want an error") + } + if len(server.requests) != 0 { + t.Errorf("requests = %d, want 0 before transport", len(server.requests)) + } +} + +func TestImportPackageSelectionBlocked(t *testing.T) { + for _, tc := range []struct { + status int + body string + check func(error) bool + }{ + {http.StatusConflict, `{"message":"overlap","issues":[{"type":"workflow-removal-conflict","workflowId":"a"}]}`, IsImportConflict}, + {http.StatusUnprocessableEntity, `{"message":"denied","issues":[{"type":"workflow-removal-forbidden","workflowId":"b"}]}`, IsImportUnprocessable}, + } { + server := newCommunityPackageServer(t, packageJSONHandler(tc.status, tc.body)) + _, err := server.client(t).ImportPackageSelection(context.Background(), ImportPackageSelectionRequest{ + ProjectID: "p", + WorkflowIDs: []string{"a"}, + DeletedWorkflowIDs: []string{"b"}, + WorkflowIDPolicy: ImportWorkflowIDNew, + }, strings.NewReader(packageArchiveBytes), "p.n8np") + if err == nil || !tc.check(err) { + t.Fatalf("%d: error = %v, want a blocked error", tc.status, err) + } + blocked, _ := AsImportBlocked(err) + if blocked.Path != N8nPackageImportSelectionPath || len(blocked.Issues) != 1 || !strings.Contains(string(blocked.Issues[0].Raw), "workflowId") { + t.Errorf("%d: blocked = %+v, want the selection path and the verbatim issue", tc.status, blocked) + } + if !strings.Contains(err.Error(), "POST "+N8nPackageImportSelectionPath) { + t.Errorf("%d: error = %q, want the selection path", tc.status, err.Error()) + } + } +} + +func TestImportPackageSelectionOtherErrors(t *testing.T) { + for _, tc := range []struct { + name string + status int + body string + check func(error) bool + }{ + {"workflow package", http.StatusBadRequest, `{"message":"import-selection needs a project package"}`, func(err error) bool { return IsStatus(err, http.StatusBadRequest) }}, + {"forbidden", http.StatusForbidden, `{"message":"denied"}`, IsForbidden}, + {"not found", http.StatusNotFound, `{"message":"not found"}`, IsNotFound}, + } { + t.Run(tc.name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(tc.status, tc.body)) + _, err := server.client(t).ImportPackageSelection(context.Background(), ImportPackageSelectionRequest{ + ProjectID: "p", + WorkflowIDs: []string{"a"}, + WorkflowIDPolicy: ImportWorkflowIDSource, + }, strings.NewReader(packageArchiveBytes), "p.n8np") + if err == nil || !tc.check(err) { + t.Fatalf("error = %v, want the %d behavior", err, tc.status) + } + if !strings.Contains(err.Error(), N8nPackageImportSelectionPath) { + t.Errorf("error = %q, want the selection path", err.Error()) + } + }) + } +} + +func TestImportPackageSelectionCancellation(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, packageImportResultJSON)) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := server.client(t).ImportPackageSelection(ctx, ImportPackageSelectionRequest{ + ProjectID: "p", + WorkflowIDs: []string{"a"}, + WorkflowIDPolicy: ImportWorkflowIDSource, + }, strings.NewReader(packageArchiveBytes), "p.n8np") + if !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } +} diff --git a/test/integration/n8n_package_test.go b/test/integration/n8n_package_test.go index 1e744cd..35c3d1c 100644 --- a/test/integration/n8n_package_test.go +++ b/test/integration/n8n_package_test.go @@ -4,11 +4,13 @@ import ( "bytes" "context" "encoding/json" + "fmt" "net/http" "os" "path/filepath" "strings" "testing" + "time" "github.com/SomeoneWithOptions/n8n-cli/internal/cli" "github.com/SomeoneWithOptions/n8n-cli/internal/config" @@ -121,3 +123,145 @@ func TestN8nPackageImportValidation(t *testing.T) { } t.Logf("invalid archive rejected as expected: %v", err) } + +// TestN8nPackageImportSelectionValidation posts a malformed archive to the +// selection endpoint, which must reject it before writing anything. +func TestN8nPackageImportSelectionValidation(t *testing.T) { + instance := integration.Require(t) + client := instance.Client(t) + + _, err := client.ImportPackageSelection(context.Background(), n8n.ImportPackageSelectionRequest{ + ProjectID: integration.ResourcePrefix + "missing-project", + WorkflowIDs: []string{integration.ResourcePrefix + "missing-workflow"}, + WorkflowIDPolicy: n8n.ImportWorkflowIDSource, + }, strings.NewReader("not-a-gzip-package"), "invalid.n8np") + if n8n.IsForbidden(err) || n8n.IsNotFound(err) || n8n.IsStatus(err, http.StatusServiceUnavailable) { + t.Skip("integration instance does not serve package import-selection") + } + if err == nil { + t.Fatal("ImportPackageSelection(invalid archive): want a rejection, got success") + } + if !n8n.IsStatus(err, http.StatusBadRequest) && !n8n.IsImportUnprocessable(err) { + t.Errorf("error = %v, want a 400 or 422 validation rejection", err) + } + t.Logf("invalid archive rejected as expected: %v", err) +} + +// TestN8nPackageImportSelectionRoundTrip creates a prefixed project with two +// workflows, exports it as a project package, and imports one workflow back +// while archiving the other. It only touches what it created, and cleanup is +// registered before the first assertion. +func TestN8nPackageImportSelectionRoundTrip(t *testing.T) { + instance := integration.RequireDestructive(t) + client := instance.Client(t) + ctx := context.Background() + stamp := time.Now().UnixNano() + name := fmt.Sprintf("%spackage-selection-%d", integration.ResourcePrefix, stamp) + + project, err := client.CreateProject(ctx, n8n.CreateProjectRequest{Name: name}) + if n8n.IsForbidden(err) || n8n.IsNotFound(err) { + t.Skipf("integration instance denies project creation: %v", err) + } + if err != nil { + t.Fatalf("CreateProject(%q): %v", name, err) + } + projectID := project.ID + if projectID == "" { + projects, err := n8n.Collect(ctx, client.ListProjects, n8n.ListOptions{Limit: 100}, 0) + if err != nil { + t.Fatalf("ListProjects after create: %v", err) + } + for _, candidate := range projects { + if candidate.Name == name { + projectID = candidate.ID + } + } + } + if projectID == "" { + t.Fatalf("created project %q was not found in the project list", name) + } + t.Cleanup(func() { + if err := client.DeleteProject(context.Background(), projectID); err != nil && !n8n.IsNotFound(err) { + t.Errorf("cleanup DeleteProject(%q): %v", projectID, err) + } + }) + + createInProject := func(suffix string) string { + t.Helper() + workflowName := fmt.Sprintf("%s-%s", name, suffix) + created, err := client.CreateWorkflow(ctx, workflowDefinition(workflowName, fmt.Sprintf("%s%d-%s", integration.ResourcePrefix, stamp, suffix))) + if err != nil { + t.Fatalf("CreateWorkflow(%q): %v", workflowName, err) + } + t.Cleanup(func() { + if _, err := client.DeleteWorkflow(context.Background(), created.ID); err != nil && !n8n.IsNotFound(err) { + t.Errorf("cleanup DeleteWorkflow(%q): %v", created.ID, err) + } + }) + if err := client.TransferWorkflow(ctx, created.ID, projectID); err != nil { + t.Fatalf("TransferWorkflow(%q, %q): %v", created.ID, projectID, err) + } + return created.ID + } + kept := createInProject("kept") + removed := createInProject("removed") + + var archive bytes.Buffer + if _, err := client.ExportPackage(ctx, n8n.ExportPackageRequest{ProjectIDs: []string{projectID}}, &archive); err != nil { + if n8n.IsForbidden(err) || n8n.IsNotFound(err) { + t.Skip("integration instance has no licensed Packages feature") + } + t.Fatalf("ExportPackage(project %q): %v", projectID, err) + } + + result, err := client.ImportPackageSelection(ctx, n8n.ImportPackageSelectionRequest{ + ProjectID: projectID, + WorkflowIDs: []string{kept}, + DeletedWorkflowIDs: []string{removed}, + WorkflowConflictPolicy: n8n.ImportWorkflowConflictNewVersion, + WorkflowIDPolicy: n8n.ImportWorkflowIDSource, + OverwriteDeletionPolicy: n8n.ImportDeletionArchive, + }, bytes.NewReader(archive.Bytes()), "project.n8np") + if n8n.IsForbidden(err) || n8n.IsNotFound(err) || n8n.IsStatus(err, http.StatusServiceUnavailable) { + t.Skipf("integration instance does not serve package import-selection: %v", err) + } + if err != nil { + t.Fatalf("ImportPackageSelection: %v", err) + } + if len(result.Workflows) != 1 || result.Workflows[0].LocalID != kept || result.Workflows[0].ProjectID != projectID { + t.Errorf("workflows = %+v, want only %q updated in place in project %q", result.Workflows, kept, projectID) + } + if len(result.RemovedWorkflows) != 1 || result.RemovedWorkflows[0].WorkflowID != removed || result.RemovedWorkflows[0].Deletion != "archived" { + t.Errorf("removedWorkflows = %+v, want %q archived", result.RemovedWorkflows, removed) + } + + path := filepath.Join(t.TempDir(), "project.n8np") + if err := os.WriteFile(path, archive.Bytes(), 0o600); err != nil { + t.Fatalf("write archive: %v", err) + } + env := map[string]string{config.EnvURL: instance.URL, config.EnvAPIKey: instance.APIKey.Reveal()} + interactive := false + var stdout, stderr strings.Builder + code := cli.Run(ctx, []string{"package", "import-selection", "--file", path, "--project-id", projectID, + "--workflow-id", kept, "--workflow-conflict-policy", "skip", "--yes", "--output", "json"}, cli.Options{ + Streams: cli.Streams{In: strings.NewReader(""), Out: &stdout, Err: &stderr}, + Version: version.Get(), + ConfigDir: t.TempDir(), + Env: func(name string) string { return env[name] }, + Keyring: config.NewMemoryStore(config.StorageKeyring), + Interactive: &interactive, + }) + if code != cli.ExitSuccess { + t.Fatalf("package import-selection exit code = %d (stderr: %s)", code, stderr.String()) + } + var skipped n8n.ImportPackageResult + if err := json.Unmarshal([]byte(stdout.String()), &skipped); err != nil { + t.Fatalf("stdout is not an import result: %v\n%s", err, stdout.String()) + } + if len(skipped.Workflows) != 1 || skipped.Workflows[0].Status != "skipped" { + t.Errorf("workflows = %+v, want %q skipped under the skip policy", skipped.Workflows, kept) + } + if strings.Contains(stdout.String(), instance.APIKey.Reveal()) { + t.Error("API credential leaked into stdout") + } +}