From f2e59bc6b528e054f231a8191684d027a4eb984e Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 23:42:20 -0500 Subject: [PATCH 1/7] fix(evaluation): decode numeric test-case executionId The public API types test-case executionId as a nullable integer, but the client decoded it into *string, so any numeric id failed with an UnmarshalTypeError. Decode into json.Number, which also accepts the numeric strings older instances sent. Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/cli/evaluation.go | 10 ++++++++- internal/cli/evaluation_test.go | 18 ++++++++++++++- internal/n8n/evaluation.go | 6 +++-- internal/n8n/evaluation_test.go | 39 +++++++++++++++++++++++++++++++-- 4 files changed, 67 insertions(+), 6 deletions(-) diff --git a/internal/cli/evaluation.go b/internal/cli/evaluation.go index baf823f..6eef728 100644 --- a/internal/cli/evaluation.go +++ b/internal/cli/evaluation.go @@ -2,6 +2,7 @@ package cli import ( "context" + "encoding/json" "fmt" "net/http" "strings" @@ -432,7 +433,7 @@ func writeEvaluationCaseList(opts Options, resolution config.Resolution, workflo fmt.Fprintln(tw, "\nID\tSTATUS\tEXECUTION\tSTARTED\tCOMPLETED\tERROR") for _, testCase := range page.Data { fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\n", emptyDash(testCase.ID), emptyDash(testCase.Status), - optionalText(testCase.ExecutionID), optionalText(testCase.RunAt), optionalText(testCase.CompletedAt), optionalText(testCase.ErrorCode)) + optionalNumber(testCase.ExecutionID), optionalText(testCase.RunAt), optionalText(testCase.CompletedAt), optionalText(testCase.ErrorCode)) } } if page.HasMore() { @@ -441,6 +442,13 @@ func writeEvaluationCaseList(opts Options, resolution config.Resolution, workflo return tw.Flush() } +func optionalNumber(value *json.Number) string { + if value == nil { + return "-" + } + return emptyDash(value.String()) +} + func validateEvaluationArguments(workflowID, runID string) error { if err := validateEvaluationArgument("workflow ID", workflowID); err != nil { return err diff --git a/internal/cli/evaluation_test.go b/internal/cli/evaluation_test.go index ef0fa58..1653c00 100644 --- a/internal/cli/evaluation_test.go +++ b/internal/cli/evaluation_test.go @@ -20,7 +20,7 @@ const cliEvaluationCase = `{ "id":"case-1","status":"success","runAt":"2026-09-18T10:00:00Z", "completedAt":"2026-09-18T10:00:10Z","metrics":{"quality":1}, "errorCode":null,"errorDetails":null,"inputs":{"question":"hello"}, - "outputs":{"answer":"world"},"executionId":"1000" + "outputs":{"answer":"world"},"executionId":1000 }` func evaluationFixture(t *testing.T, body string) *fixture { @@ -166,6 +166,9 @@ func TestEvaluationCaseListPaginationAndJSON(t *testing.T) { if err := json.Unmarshal([]byte(got.stdout), &page); err != nil || len(page.Data) != 2 || page.Data[0].ID != "case-1" || !strings.Contains(string(page.Data[0].Inputs), `"question"`) { t.Errorf("stdout = %q (error: %v)", got.stdout, err) } + if !strings.Contains(got.stdout, `"executionId": 1000`) && !strings.Contains(got.stdout, `"executionId":1000`) { + t.Errorf("stdout lost numeric executionId:\n%s", got.stdout) + } first := f.requests[len(f.requests)-2] if first.URL.EscapedPath() != n8n.BasePath+"/workflows/wf%2Fone%3Fx=1/test-runs/run%2Ftwo%3Fx=2/test-cases" || first.URL.Query().Get("limit") != "1" { t.Errorf("first request = %s?%s", first.URL.EscapedPath(), first.URL.RawQuery) @@ -176,6 +179,19 @@ func TestEvaluationCaseListPaginationAndJSON(t *testing.T) { } } +func TestEvaluationCaseListTextShowsNumericExecution(t *testing.T) { + f := evaluationFixture(t, `{"data":[`+cliEvaluationCase+`],"nextCursor":null}`) + got := f.run("evaluation", "case", "list", "wf-1", "run-1") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"EXECUTION", "case-1", "1000"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } +} + func TestEvaluationValidationBeforeTransport(t *testing.T) { for name, args := range map[string][]string{ "status": {"evaluation", "list", "wf-1", "--status", "success"}, diff --git a/internal/n8n/evaluation.go b/internal/n8n/evaluation.go index f6cad0b..b7a3467 100644 --- a/internal/n8n/evaluation.go +++ b/internal/n8n/evaluation.go @@ -61,7 +61,9 @@ type EvaluationCancelResult struct { } // EvaluationTestCase is one case within an evaluation run. Inputs, outputs, -// metrics and errors remain raw workflow-defined JSON. +// metrics and errors remain raw workflow-defined JSON. ExecutionID is a JSON +// number in the contract; json.Number also accepts the numeric strings older +// instances sent. type EvaluationTestCase struct { ID string `json:"id"` Status string `json:"status"` @@ -72,7 +74,7 @@ type EvaluationTestCase struct { ErrorDetails json.RawMessage `json:"errorDetails,omitempty"` Inputs json.RawMessage `json:"inputs,omitempty"` Outputs json.RawMessage `json:"outputs,omitempty"` - ExecutionID *string `json:"executionId"` + ExecutionID *json.Number `json:"executionId"` } // ListEvaluationRunsOptions controls run status filtering and cursor diff --git a/internal/n8n/evaluation_test.go b/internal/n8n/evaluation_test.go index c2656c0..054e84d 100644 --- a/internal/n8n/evaluation_test.go +++ b/internal/n8n/evaluation_test.go @@ -2,6 +2,7 @@ package n8n import ( "context" + "encoding/json" "net/http" "strings" "testing" @@ -31,7 +32,7 @@ const evaluationCaseResponse = `{ "errorDetails":null, "inputs":{"question":"hello"}, "outputs":{"answer":"world"}, - "executionId":"1000" + "executionId":1000 }` func TestListEvaluationRunsQueryAndDecoding(t *testing.T) { @@ -100,7 +101,7 @@ func TestEvaluationRequests(t *testing.T) { }, method: http.MethodPost, path: "/workflows/wf%2Fone%3Fx=1/test-runs/run%2Ftwo%3Fx=2/cancel", result: `{"id":"run-1","status":"cancelled"}`, status: http.StatusAccepted}, {name: "cases", call: func(c *Client) error { page, err := c.ListEvaluationCases(context.Background(), workflowID, runID, ListEvaluationCasesOptions{ListOptions: ListOptions{Limit: 25, Cursor: "case/cursor?x=1"}}) - if err == nil && (len(page.Data) != 1 || page.Data[0].ID != "case-1" || page.Data[0].ExecutionID == nil || *page.Data[0].ExecutionID != "1000") { + if err == nil && (len(page.Data) != 1 || page.Data[0].ID != "case-1" || page.Data[0].ExecutionID == nil || page.Data[0].ExecutionID.String() != "1000") { t.Errorf("page = %+v", page) } return err @@ -127,6 +128,40 @@ func TestEvaluationRequests(t *testing.T) { } } +func TestEvaluationCaseExecutionIDShapes(t *testing.T) { + for name, tt := range map[string]struct { + raw string + want string + }{ + "number": {raw: `1000`, want: "1000"}, + "numeric string": {raw: `"1000"`, want: "1000"}, + "null": {raw: `null`}, + } { + t.Run(name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, + `{"data":[{"id":"case-1","status":"success","executionId":`+tt.raw+`}],"nextCursor":null}`)) + page, err := server.client(t).ListEvaluationCases(context.Background(), "wf-1", "run-1", ListEvaluationCasesOptions{}) + if err != nil { + t.Fatalf("ListEvaluationCases: %v", err) + } + got := page.Data[0].ExecutionID + if tt.want == "" { + if got != nil { + t.Errorf("executionId = %v, want nil", *got) + } + return + } + if got == nil || got.String() != tt.want { + t.Errorf("executionId = %v, want %s", got, tt.want) + } + encoded, err := json.Marshal(page.Data[0]) + if err != nil || !strings.Contains(string(encoded), `"executionId":1000`) { + t.Errorf("encoded = %s (error: %v), want numeric executionId", encoded, err) + } + }) + } +} + func TestEvaluationValidationBeforeTransport(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"data":[],"nextCursor":null}`)) client := server.client(t) From 224a55319e378e65a9a05c60b840081ec0660251 Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 23:45:52 -0500 Subject: [PATCH 2/7] fix(workflow): send description, null folder and read-shaped settings - create accepts description; it was filtered out and reported as dropped, also losing it on 'workflow copy' - parentFolderId may be null on write (null = move to the project root) - settings set to "DEFAULT" (read-only marker) are dropped and reported as settings.NAME; a null settings is sent as {} instead of failing validation - read-only node createdAt/updatedAt are stripped and reported - workflow list --include-parent-folder adds a FOLDER column and keeps parentFolder in JSON Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/n8n_workflow_create.md | 9 ++- docs/n8n_workflow_list.md | 36 +++++---- docs/n8n_workflow_update.md | 8 +- internal/cli/workflow.go | 63 ++++++++++----- internal/cli/workflow_copy_test.go | 5 +- internal/cli/workflow_test.go | 93 ++++++++++++++++++++++ internal/n8n/workflow.go | 118 ++++++++++++++++++++++++++-- internal/n8n/workflow_test.go | 119 +++++++++++++++++++++++++---- 8 files changed, 388 insertions(+), 63 deletions(-) diff --git a/docs/n8n_workflow_create.md b/docs/n8n_workflow_create.md index 2eb48ce..60d3460 100644 --- a/docs/n8n_workflow_create.md +++ b/docs/n8n_workflow_create.md @@ -9,10 +9,11 @@ from stdin ('--input -'); without it, --name creates an empty workflow with no nodes, ready to be edited in the UI or filled in by a later update. The input may be a document produced by 'n8n workflow get --output json': the -read-only fields (id, versionId, active, timestamps, tags, sharing) are dropped -before sending, because the API answers a read-only field with 400, and the -dropped names are reported on stderr. --name, --project-id and ---parent-folder-id override what the document says. +read-only fields (id, versionId, active, timestamps, tags, sharing, node +timestamps) and settings set to "DEFAULT" are dropped before sending, because +the API answers them with 400, and the dropped names are reported on stderr. A +null settings is sent as {}. --name, --project-id and --parent-folder-id +override what the document says. A created workflow is never published: publish it with 'n8n workflow publish'. Requires workflow:create. diff --git a/docs/n8n_workflow_list.md b/docs/n8n_workflow_list.md index 9e443f3..f50dd34 100644 --- a/docs/n8n_workflow_list.md +++ b/docs/n8n_workflow_list.md @@ -11,7 +11,9 @@ every cursor, capped at 10,000 workflows. Use this to find the workflow ID every other command takes. Narrow the result set with --active, --name, --tag and --project-id. Each row carries the full definition, so on a large instance prefer --exclude-pinned-data, which drops -the pinned sample data that dominates the response. Requires workflow:list. +the pinned sample data that dominates the response. --include-parent-folder +adds the containing folder: a FOLDER column in text, parentFolder in JSON +({"id": ...}, or null at the project root). Requires workflow:list. Script views print rows only, with no header, count or blank lines, so stdout pipes cleanly; the next cursor and any empty-result hint go to stderr, and an @@ -42,27 +44,29 @@ n8n workflow list [flags] n8n workflow list --active true --limit 50 n8n workflow list --tag production --tag finance n8n workflow list --project-id PROJECT_ID --exclude-pinned-data + n8n workflow list --project-id PROJECT_ID --include-parent-folder n8n workflow list --all --output json ``` ### Options ``` - --active string only published (true) or unpublished (false) workflows (default: both) - --all follow every page instead of one (maximum 10,000 workflows; hitting it warns and sets JSON collection.truncated) - --brief print only ID and name, tab-separated and escaped, with no header (default: full table) - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - --cursor string pagination cursor returned by a previous list (default: the first page) - --exclude-pinned-data leave pinned sample data out of the response (default: include it) - -h, --help help for list - --limit int workflows per API page, 1 to 250 (default: server default of 100) - --name string only workflows with exactly this name (default: any name) - --offset int number of workflows to skip before the page (default: start at the first workflow) - --output string output format: text or json (JSON is a page object with data and nextCursor, plus collection with --all) (default "text") - --project-id string only workflows in this project, from 'n8n project list' (default: every project) - --quiet print only workflow IDs, one per line, with no header (default: full table) - --tag stringArray only workflows carrying this tag name, repeatable and combined with AND (default: any tag) - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --active string only published (true) or unpublished (false) workflows (default: both) + --all follow every page instead of one (maximum 10,000 workflows; hitting it warns and sets JSON collection.truncated) + --brief print only ID and name, tab-separated and escaped, with no header (default: full table) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --cursor string pagination cursor returned by a previous list (default: the first page) + --exclude-pinned-data leave pinned sample data out of the response (default: include it) + -h, --help help for list + --include-parent-folder add each workflow's containing folder, null at the project root (default: omit it) + --limit int workflows per API page, 1 to 250 (default: server default of 100) + --name string only workflows with exactly this name (default: any name) + --offset int number of workflows to skip before the page (default: start at the first workflow) + --output string output format: text or json (JSON is a page object with data and nextCursor, plus collection with --all) (default "text") + --project-id string only workflows in this project, from 'n8n project list' (default: every project) + --quiet print only workflow IDs, one per line, with no header (default: full table) + --tag stringArray only workflows carrying this tag name, repeatable and combined with AND (default: any tag) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) ``` ### SEE ALSO diff --git a/docs/n8n_workflow_update.md b/docs/n8n_workflow_update.md index 5528eb3..5828dd8 100644 --- a/docs/n8n_workflow_update.md +++ b/docs/n8n_workflow_update.md @@ -13,8 +13,12 @@ start from a fresh read: n8n workflow get ID --output json > workflow.json n8n workflow update ID --input workflow.json Read-only fields in the document (id, versionId, active, timestamps, tags, -sharing) are dropped before sending and reported on stderr, because the API -answers a read-only field with 400. +sharing, node timestamps) and settings set to "DEFAULT" are dropped before +sending and reported on stderr, because the API answers them with 400; an +omitted setting keeps the instance default, which is what "DEFAULT" means. +A null settings is sent as {}. Add "parentFolderId": "FOLDER_ID" to move +the workflow into a folder, or "parentFolderId": null to move it to the +project root; without the field the folder is unchanged. A published workflow is republished with the new version unless --no-publish is given. Republishing additionally needs the workflow:activate scope and the diff --git a/internal/cli/workflow.go b/internal/cli/workflow.go index fc7053f..89c9f5a 100644 --- a/internal/cli/workflow.go +++ b/internal/cli/workflow.go @@ -85,6 +85,7 @@ type workflowListFlags struct { name string projectID string excludePins bool + withFolder bool view listViewFlags output string } @@ -100,7 +101,9 @@ func newWorkflowListCommand(opts Options) *cobra.Command { "Use this to find the workflow ID every other command takes. Narrow the result\n" + "set with --active, --name, --tag and --project-id. Each row carries the full\n" + "definition, so on a large instance prefer --exclude-pinned-data, which drops\n" + - "the pinned sample data that dominates the response. Requires workflow:list.\n\n" + + "the pinned sample data that dominates the response. --include-parent-folder\n" + + "adds the containing folder: a FOLDER column in text, parentFolder in JSON\n" + + "({\"id\": ...}, or null at the project root). Requires workflow:list.\n\n" + scriptViewHelp("workflow", "ID and name") + "\n\n" + cursorCollectionHelp, Example: " n8n workflow list\n" + @@ -109,6 +112,7 @@ func newWorkflowListCommand(opts Options) *cobra.Command { " n8n workflow list --active true --limit 50\n" + " n8n workflow list --tag production --tag finance\n" + " n8n workflow list --project-id PROJECT_ID --exclude-pinned-data\n" + + " n8n workflow list --project-id PROJECT_ID --include-parent-folder\n" + " n8n workflow list --all --output json", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { @@ -125,6 +129,7 @@ func newWorkflowListCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.name, "name", "", "only workflows with exactly this name (default: any name)") cmd.Flags().StringVar(&f.projectID, "project-id", "", "only workflows in this project, from 'n8n project list' (default: every project)") cmd.Flags().BoolVar(&f.excludePins, "exclude-pinned-data", false, "leave pinned sample data out of the response (default: include it)") + cmd.Flags().BoolVar(&f.withFolder, "include-parent-folder", false, "add each workflow's containing folder, null at the project root (default: omit it)") f.view.register(cmd, "workflow", "ID and name") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is a page object with data and nextCursor, plus collection with --all)") return cmd @@ -139,13 +144,14 @@ func runWorkflowList(ctx context.Context, opts Options, f workflowListFlags) err return err } listOpts := n8n.ListWorkflowsOptions{ - ListOptions: n8n.ListOptions{Limit: f.limit, Cursor: f.cursor}, - Offset: f.offset, - Active: active, - Tags: f.tags, - Name: f.name, - ProjectID: f.projectID, - ExcludePinnedData: f.excludePins, + ListOptions: n8n.ListOptions{Limit: f.limit, Cursor: f.cursor}, + Offset: f.offset, + Active: active, + Tags: f.tags, + Name: f.name, + ProjectID: f.projectID, + ExcludePinnedData: f.excludePins, + IncludeParentFolder: f.withFolder, } if err := listOpts.Validate(); err != nil { return err @@ -176,7 +182,7 @@ func runWorkflowList(ctx context.Context, opts Options, f workflowListFlags) err return scriptListRow{ID: workflow.ID, Fields: []string{workflow.Name}} }) } else { - err = writeWorkflowList(opts, resolution, page) + err = writeWorkflowList(opts, resolution, page, f.withFolder) } return finishCollection(opts.Streams.Err, collection, err) } @@ -200,17 +206,30 @@ func workflowActiveFilter(value string) (*bool, error) { const workflowListEmptyHint = "No workflows were returned. Widen the filters, or create one with 'n8n workflow create --name NAME'." -func writeWorkflowList(opts Options, resolution config.Resolution, page n8n.Page[n8n.Workflow]) error { +func writeWorkflowList(opts Options, resolution config.Resolution, page n8n.Page[n8n.Workflow], withFolder bool) error { tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + folderMissing := false fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) fmt.Fprintf(tw, "Workflows:\t%d\n", len(page.Data)) if len(page.Data) > 0 { - fmt.Fprintln(tw, "\nID\tNAME\tPUBLISHED\tARCHIVED\tNODES\tTRIGGERS\tTAGS\tUPDATED") + header := "\nID\tNAME\tPUBLISHED\tARCHIVED\tNODES\tTRIGGERS\tTAGS\tUPDATED" + if withFolder { + header += "\tFOLDER" + } + fmt.Fprintln(tw, header) for _, workflow := range page.Data { - fmt.Fprintf(tw, "%s\t%s\t%t\t%t\t%d\t%d\t%s\t%s\n", + fmt.Fprintf(tw, "%s\t%s\t%t\t%t\t%d\t%d\t%s\t%s", emptyDash(workflow.ID), emptyDash(workflow.Name), workflow.Active, workflow.IsArchived, workflow.NodeCount(), workflow.TriggerCount, emptyDash(workflowTagNames(workflow.Tags)), emptyDash(workflow.UpdatedAt)) + if withFolder { + folder, ok := workflow.ParentFolderID() + if !ok { + folderMissing = true + } + fmt.Fprintf(tw, "\t%s", emptyDash(folder)) + } + fmt.Fprintln(tw) } } if page.HasMore() { @@ -222,6 +241,9 @@ func writeWorkflowList(opts Options, resolution config.Resolution, page n8n.Page if len(page.Data) == 0 { fmt.Fprintln(opts.Streams.Err, workflowListEmptyHint) } + if folderMissing { + fmt.Fprintln(opts.Streams.Err, "The instance sent no parentFolder field, so FOLDER '-' means unknown, not the project root; it may predate --include-parent-folder.") + } return nil } @@ -328,10 +350,11 @@ func newWorkflowCreateCommand(opts Options) *cobra.Command { "from stdin ('--input -'); without it, --name creates an empty workflow with no\n" + "nodes, ready to be edited in the UI or filled in by a later update.\n\n" + "The input may be a document produced by 'n8n workflow get --output json': the\n" + - "read-only fields (id, versionId, active, timestamps, tags, sharing) are dropped\n" + - "before sending, because the API answers a read-only field with 400, and the\n" + - "dropped names are reported on stderr. --name, --project-id and\n" + - "--parent-folder-id override what the document says.\n\n" + + "read-only fields (id, versionId, active, timestamps, tags, sharing, node\n" + + "timestamps) and settings set to \"DEFAULT\" are dropped before sending, because\n" + + "the API answers them with 400, and the dropped names are reported on stderr. A\n" + + "null settings is sent as {}. --name, --project-id and --parent-folder-id\n" + + "override what the document says.\n\n" + "A created workflow is never published: publish it with 'n8n workflow publish'.\n" + "Requires workflow:create.", Example: " n8n workflow create --name \"Invoice sync\"\n" + @@ -435,8 +458,12 @@ func newWorkflowUpdateCommand(opts Options) *cobra.Command { " n8n workflow get ID --output json > workflow.json\n" + " n8n workflow update ID --input workflow.json\n" + "Read-only fields in the document (id, versionId, active, timestamps, tags,\n" + - "sharing) are dropped before sending and reported on stderr, because the API\n" + - "answers a read-only field with 400.\n\n" + + "sharing, node timestamps) and settings set to \"DEFAULT\" are dropped before\n" + + "sending and reported on stderr, because the API answers them with 400; an\n" + + "omitted setting keeps the instance default, which is what \"DEFAULT\" means.\n" + + "A null settings is sent as {}. Add \"parentFolderId\": \"FOLDER_ID\" to move\n" + + "the workflow into a folder, or \"parentFolderId\": null to move it to the\n" + + "project root; without the field the folder is unchanged.\n\n" + "A published workflow is republished with the new version unless --no-publish is\n" + "given. Republishing additionally needs the workflow:activate scope and the\n" + "project's workflow:publish permission; without them the new version is still\n" + diff --git a/internal/cli/workflow_copy_test.go b/internal/cli/workflow_copy_test.go index d0ed0b5..5cd34df 100644 --- a/internal/cli/workflow_copy_test.go +++ b/internal/cli/workflow_copy_test.go @@ -164,7 +164,8 @@ func TestWorkflowCopyRefusesOneInstance(t *testing.T) { func TestWorkflowCopyCreatesMissingTarget(t *testing.T) { from, to := copyFixtures(t) - stageSource(from, `{"data":[{"id":"AAA","name":"Invoice sync"}]}`, from.body) + source := strings.Replace(from.body, `"description":null`, `"description":"Syncs invoices"`, 1) + stageSource(from, `{"data":[{"id":"AAA","name":"Invoice sync"}]}`, source) stageTarget(to, `{"data":[]}`, "", to.body) got := from.run(copyArgs("--name", "Invoice sync", "--to-project-id", "PROD", "--to-parent-folder-id", "FLD")...) @@ -184,7 +185,7 @@ func TestWorkflowCopyCreatesMissingTarget(t *testing.T) { t.Errorf("create body carries %q: %s", absent, body) } } - for field, want := range map[string]string{"name": `"Invoice sync"`, "projectId": `"PROD"`, "parentFolderId": `"FLD"`} { + for field, want := range map[string]string{"name": `"Invoice sync"`, "description": `"Syncs invoices"`, "projectId": `"PROD"`, "parentFolderId": `"FLD"`} { if string(doc[field]) != want { t.Errorf("create body %s = %s, want %s", field, doc[field], want) } diff --git a/internal/cli/workflow_test.go b/internal/cli/workflow_test.go index 2239222..e103208 100644 --- a/internal/cli/workflow_test.go +++ b/internal/cli/workflow_test.go @@ -85,6 +85,54 @@ func TestWorkflowListTextJSONAndQuery(t *testing.T) { } } +func TestWorkflowListIncludeParentFolder(t *testing.T) { + f := workflowFixture(t, `{"data":[`+ + strings.Replace(cliWorkflow, `"id":"wf-1"`, `"id":"wf-1","parentFolder":{"id":"fo-1"}`, 1)+`,`+ + strings.Replace(cliWorkflow, `"id":"wf-1"`, `"id":"wf-2","parentFolder":null`, 1)+`],"nextCursor":null}`) + got := f.run("workflow", "list", "--include-parent-folder") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if q := f.lastRequest().URL.Query().Get("includeParentFolder"); q != "true" { + t.Errorf("includeParentFolder = %q, want true", q) + } + lines := strings.Split(got.stdout, "\n") + var header, first, second string + for _, line := range lines { + switch { + case strings.HasPrefix(line, "ID"): + header = line + case strings.HasPrefix(line, "wf-1"): + first = line + case strings.HasPrefix(line, "wf-2"): + second = line + } + } + if !strings.HasSuffix(strings.TrimSpace(header), "FOLDER") || !strings.HasSuffix(strings.TrimSpace(first), "fo-1") || !strings.HasSuffix(strings.TrimSpace(second), "-") { + t.Errorf("stdout lacks the folder column:\n%s", got.stdout) + } + if strings.Contains(got.stderr, "no parentFolder") { + t.Errorf("stderr warns although every row has parentFolder: %s", got.stderr) + } + + got = f.run("workflow", "list", "--include-parent-folder", "--output", "json") + if !strings.Contains(got.stdout, `"parentFolder": {`) || !strings.Contains(got.stdout, `"parentFolder": null`) { + t.Errorf("JSON lost parentFolder:\n%s", got.stdout) + } + + got = f.run("workflow", "list") + if strings.Contains(got.stdout, "FOLDER") || f.lastRequest().URL.Query().Has("includeParentFolder") { + t.Errorf("folder column or query without the flag:\n%s", got.stdout) + } + + // An instance that predates the parameter ignores it. + f.body = `{"data":[` + cliWorkflow + `],"nextCursor":null}` + got = f.run("workflow", "list", "--include-parent-folder") + if !strings.Contains(got.stderr, "no parentFolder field") { + t.Errorf("stderr = %q, want the missing field explained", got.stderr) + } +} + func TestWorkflowListRejectsUnknownActiveValue(t *testing.T) { f := workflowFixture(t, `{"data":[],"nextCursor":null}`) before := f.requestCount() @@ -324,6 +372,51 @@ func TestWorkflowCreateRejectsBadInput(t *testing.T) { }) } +// A document read back with 'get --output json' carries shapes only the read +// schema allows; they are normalized before sending, not answered with 400. +func TestWorkflowWriteNormalizesReadDocument(t *testing.T) { + read := strings.NewReplacer( + `"description":null`, `"description":"Syncs invoices","parentFolderId":null`, + `"settings":{"executionOrder":"v1"}`, `"settings":{"executionOrder":"v1","saveExecutionProgress":"DEFAULT","saveDataSuccessExecution":"DEFAULT","saveDataErrorExecution":"all"}`, + `"parameters":{"path":"hook"}`, `"parameters":{"path":"hook"},"createdAt":"2026-09-16T20:03:43.517Z"`, + ).Replace(cliWorkflow) + for _, args := range [][]string{ + {"workflow", "create"}, + {"workflow", "update", "wf-1"}, + } { + t.Run(args[1], func(t *testing.T) { + f := workflowFixture(t, cliWorkflow) + got := f.run(append(args, "--input", writeWorkflowFile(t, read))...) + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + var body map[string]json.RawMessage + if err := json.Unmarshal([]byte(f.lastBody()), &body); err != nil { + t.Fatalf("request body is not JSON: %v", err) + } + assertCLIJSON(t, `"Syncs invoices"`, string(body["description"])) + assertCLIJSON(t, `null`, string(body["parentFolderId"])) + assertCLIJSON(t, `{"executionOrder":"v1","saveDataErrorExecution":"all"}`, string(body["settings"])) + assertCLIJSON(t, `[{"id":"n-1","name":"Webhook","type":"n8n-nodes-base.webhook","typeVersion":2,"parameters":{"path":"hook"}}]`, string(body["nodes"])) + for _, want := range []string{"settings.saveExecutionProgress", "settings.saveDataSuccessExecution", "nodes[].createdAt"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("stderr missing %q: %s", want, got.stderr) + } + } + }) + } + + t.Run("null settings", func(t *testing.T) { + f := workflowFixture(t, cliWorkflow) + f.stdin = `{"name":"x","nodes":[],"connections":{},"settings":null}` + got := f.run("workflow", "update", "wf-1", "--input", "-") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + assertCLIJSON(t, `{"name":"x","nodes":[],"connections":{},"settings":{}}`, f.lastBody()) + }) +} + func TestWorkflowUpdateReplacesDefinition(t *testing.T) { t.Run("input is required", func(t *testing.T) { f := workflowFixture(t, cliWorkflow) diff --git a/internal/n8n/workflow.go b/internal/n8n/workflow.go index b2333bf..b43275e 100644 --- a/internal/n8n/workflow.go +++ b/internal/n8n/workflow.go @@ -24,7 +24,7 @@ const WorkflowsPath = "/workflows" var ( // CreateWorkflowFields are the fields POST /workflows accepts. CreateWorkflowFields = []string{ - "name", "nodes", "connections", "settings", + "name", "description", "nodes", "connections", "settings", "nodeGroups", "staticData", "pinData", "projectId", "parentFolderId", } // UpdateWorkflowFields are the fields PUT /workflows/{id} accepts. The @@ -36,12 +36,21 @@ var ( } // RequiredWorkflowFields must be present in every write document. RequiredWorkflowFields = []string{"name", "nodes", "connections", "settings"} - // nullableWorkflowFields may be sent as JSON null. Any other field read - // back as null (description is, on a workflow that has none) is dropped - // rather than sent, because the schema types it as a string. - nullableWorkflowFields = []string{"staticData", "pinData"} + // nullableWorkflowFields may be sent as JSON null. A null parentFolderId + // moves the workflow to the project root. Any other field read back as + // null (description is, on a workflow that has none) is dropped rather + // than sent, because the schema types it as a string. + nullableWorkflowFields = []string{"staticData", "pinData", "parentFolderId"} + // readOnlyNodeFields are server-owned timestamps a node may carry on + // read; the write schema marks them read-only. + readOnlyNodeFields = []string{"createdAt", "updatedAt"} ) +// workflowSettingDefault is the read-side value that means "use the instance +// default". The write schema does not accept it; omitting the key means the +// same thing. +const workflowSettingDefault = "DEFAULT" + // WorkflowDocument is a workflow definition as raw JSON, keyed by field name. // // Nodes, connections, settings and pinned data are open-ended documents whose @@ -78,6 +87,11 @@ func (d WorkflowDocument) Set(field string, value any) error { // plus the names of the fields it dropped, sorted. Callers report the dropped // names: silently discarding part of a user's document would be worse than the // 400 it prevents. +// +// Within the kept fields, settings whose value is "DEFAULT" (reported as +// settings.NAME) and node timestamps (reported as nodes[].createdAt and +// nodes[].updatedAt) are removed too, and a null settings becomes {}: reads +// may carry all three, writes reject them. func (d WorkflowDocument) ForCreate() (WorkflowDocument, []string) { return d.forWrite(CreateWorkflowFields) } @@ -95,8 +109,20 @@ func (d WorkflowDocument) forWrite(allowed []string) (WorkflowDocument, []string switch { case !slices.Contains(allowed, field): dropped = append(dropped, field) + case field == "settings" && isJSONNull(raw): + // Settings are nullable on read but required on write; an empty + // object keeps every setting at the instance default. + kept[field] = json.RawMessage(`{}`) case isJSONNull(raw) && !slices.Contains(nullableWorkflowFields, field): dropped = append(dropped, field) + case field == "settings": + settings, removed := withoutDefaultSettings(raw) + kept[field] = settings + dropped = append(dropped, removed...) + case field == "nodes": + nodes, removed := withoutNodeTimestamps(raw) + kept[field] = nodes + dropped = append(dropped, removed...) default: kept[field] = raw } @@ -105,6 +131,64 @@ func (d WorkflowDocument) forWrite(allowed []string) (WorkflowDocument, []string return kept, dropped } +// withoutDefaultSettings removes settings whose value is the read-only +// "DEFAULT" marker and returns the removed names as settings.NAME. Settings +// that are not an object are returned unchanged for the server to judge; so +// are settings with nothing to remove, byte for byte. +func withoutDefaultSettings(raw json.RawMessage) (json.RawMessage, []string) { + var settings map[string]json.RawMessage + if err := json.Unmarshal(raw, &settings); err != nil { + return raw, nil + } + var removed []string + for name, value := range settings { + var text string + if json.Unmarshal(value, &text) == nil && text == workflowSettingDefault { + delete(settings, name) + removed = append(removed, "settings."+name) + } + } + if len(removed) == 0 { + return raw, nil + } + encoded, err := json.Marshal(settings) + if err != nil { + return raw, nil + } + return encoded, removed +} + +// withoutNodeTimestamps removes the read-only timestamps from every node and +// returns the removed names once each, as nodes[].NAME. Nodes are decoded +// one level deep only; anything that is not an array of objects, and any +// array with nothing to remove, is returned unchanged. +func withoutNodeTimestamps(raw json.RawMessage) (json.RawMessage, []string) { + var nodes []map[string]json.RawMessage + if err := json.Unmarshal(raw, &nodes); err != nil { + return raw, nil + } + var removed []string + for _, node := range nodes { + for _, field := range readOnlyNodeFields { + if _, ok := node[field]; !ok { + continue + } + delete(node, field) + if name := "nodes[]." + field; !slices.Contains(removed, name) { + removed = append(removed, name) + } + } + } + if len(removed) == 0 { + return raw, nil + } + encoded, err := json.Marshal(nodes) + if err != nil { + return raw, nil + } + return encoded, removed +} + // Validate rejects a write document the API would reject. func (d WorkflowDocument) Validate() error { var missing []string @@ -245,6 +329,23 @@ func (w Workflow) Document() (WorkflowDocument, error) { return doc, nil } +// ParentFolderID returns the id of the folder holding the workflow, from the +// parentFolder field a list with includeParentFolder adds. It is empty at the +// project root, and ok is false when the response has no parentFolder field. +func (w Workflow) ParentFolderID() (id string, ok bool) { + raw, ok := w.Extra["parentFolder"] + if !ok { + return "", false + } + var folder *struct { + ID string `json:"id"` + } + if err := json.Unmarshal(raw, &folder); err != nil || folder == nil { + return "", true + } + return folder.ID, true +} + // WorkflowNode is the part of a node every node type has, which is what list // and summary output needs. The full node, including its parameters, stays in // [Workflow.Nodes]. @@ -319,6 +420,10 @@ type ListWorkflowsOptions struct { // ExcludePinnedData drops pinned sample data from the response, which is // the bulk of it on workflows that carry any. ExcludePinnedData bool + // IncludeParentFolder adds parentFolder to each workflow: {"id": ...} for + // the containing folder, or null at the project root. It is kept in + // [Workflow.Extra]; read it with [Workflow.ParentFolderID]. + IncludeParentFolder bool } // Validate rejects options the API would reject or that indicate a bug. @@ -361,6 +466,9 @@ func (o ListWorkflowsOptions) apply() url.Values { if o.ExcludePinnedData { query.Set("excludePinnedData", "true") } + if o.IncludeParentFolder { + query.Set("includeParentFolder", "true") + } return query } diff --git a/internal/n8n/workflow_test.go b/internal/n8n/workflow_test.go index ffe512c..d7eafea 100644 --- a/internal/n8n/workflow_test.go +++ b/internal/n8n/workflow_test.go @@ -66,13 +66,14 @@ func TestListWorkflowsQueryAndDecoding(t *testing.T) { `{"data":[`+workflowResponse+`],"nextCursor":"next/one?x=1"}`)) active := true page, err := server.client(t).ListWorkflows(context.Background(), ListWorkflowsOptions{ - ListOptions: ListOptions{Limit: 50, Cursor: "prev/one?x=1"}, - Offset: 10, - Active: &active, - Tags: []string{"production", "finance"}, - Name: "Invoice sync", - ProjectID: "pr-1", - ExcludePinnedData: true, + ListOptions: ListOptions{Limit: 50, Cursor: "prev/one?x=1"}, + Offset: 10, + Active: &active, + Tags: []string{"production", "finance"}, + Name: "Invoice sync", + ProjectID: "pr-1", + ExcludePinnedData: true, + IncludeParentFolder: true, }) if err != nil { t.Fatalf("ListWorkflows: %v", err) @@ -89,14 +90,15 @@ func TestListWorkflowsQueryAndDecoding(t *testing.T) { } query := req.URL.Query() for field, want := range map[string]string{ - "limit": "50", - "cursor": "prev/one?x=1", - "offset": "10", - "active": "true", - "tags": "production,finance", - "name": "Invoice sync", - "projectId": "pr-1", - "excludePinnedData": "true", + "limit": "50", + "cursor": "prev/one?x=1", + "offset": "10", + "active": "true", + "tags": "production,finance", + "name": "Invoice sync", + "projectId": "pr-1", + "excludePinnedData": "true", + "includeParentFolder": "true", } { if got := query.Get(field); got != want { t.Errorf("query %s = %q, want %q", field, got, want) @@ -237,7 +239,7 @@ func TestWorkflowDocumentForWriteDropsReadOnlyFields(t *testing.T) { create, _ := doc.ForCreate() if _, ok := create["description"]; ok { - t.Error("create body carries description, which POST /workflows does not accept") + t.Error("create body carries a null description, which the API rejects") } if err := create.Set("projectId", "pr-2"); err != nil { t.Fatalf("Set: %v", err) @@ -247,6 +249,91 @@ func TestWorkflowDocumentForWriteDropsReadOnlyFields(t *testing.T) { } } +func TestWorkflowDocumentForWriteNormalizesReadShapes(t *testing.T) { + read := WorkflowDocument{ + "name": json.RawMessage(`"x"`), + "description": json.RawMessage(`"Syncs invoices"`), + "parentFolderId": json.RawMessage(`null`), + "nodes": json.RawMessage(`[ + {"id":"n-1","name":"Webhook","createdAt":"2026-09-16T20:03:43.517Z","updatedAt":"2026-09-16T20:03:43.517Z"}, + {"id":"n-2","name":"Set","createdAt":"2026-09-16T20:03:43.517Z"} + ]`), + "connections": json.RawMessage(`{}`), + "settings": json.RawMessage(`{"executionOrder":"v1","saveExecutionProgress":"DEFAULT",` + + `"saveManualExecutions":true,"saveDataErrorExecution":"DEFAULT","saveDataSuccessExecution":"all"}`), + } + wantDropped := []string{"nodes[].createdAt", "nodes[].updatedAt", "settings.saveDataErrorExecution", "settings.saveExecutionProgress"} + for name, forWrite := range map[string]func() (WorkflowDocument, []string){ + "create": read.ForCreate, + "update": read.ForUpdate, + } { + t.Run(name, func(t *testing.T) { + doc, dropped := forWrite() + if !slices.Equal(dropped, wantDropped) { + t.Errorf("dropped = %v, want %v", dropped, wantDropped) + } + if doc.Text("description") != "Syncs invoices" { + t.Errorf("description = %s, want it kept", doc["description"]) + } + if string(doc["parentFolderId"]) != "null" { + t.Errorf("parentFolderId = %s, want null (move to the project root)", doc["parentFolderId"]) + } + assertJSONEqual(t, `{"executionOrder":"v1","saveManualExecutions":true,"saveDataSuccessExecution":"all"}`, string(doc["settings"])) + assertJSONEqual(t, `[{"id":"n-1","name":"Webhook"},{"id":"n-2","name":"Set"}]`, string(doc["nodes"])) + if err := doc.Validate(); err != nil { + t.Errorf("Validate: %v", err) + } + }) + } + + // Nothing to remove: the raw bytes are sent as written. + clean := writeDocument() + clean["nodes"] = json.RawMessage(`[{"name":"Webhook", "id":"n-1"}]`) + kept, dropped := clean.ForUpdate() + if len(dropped) != 0 || string(kept["nodes"]) != string(clean["nodes"]) || string(kept["settings"]) != string(clean["settings"]) { + t.Errorf("clean document changed: dropped %v, nodes %s, settings %s", dropped, kept["nodes"], kept["settings"]) + } + + // Settings are nullable on read but required on write. + nullSettings := writeDocument() + nullSettings["settings"] = json.RawMessage(`null`) + kept, dropped = nullSettings.ForCreate() + if string(kept["settings"]) != `{}` || len(dropped) != 0 { + t.Errorf("null settings = %s (dropped %v), want {}", kept["settings"], dropped) + } + if err := kept.Validate(); err != nil { + t.Errorf("Validate with null settings: %v", err) + } +} + +func TestWorkflowParentFolderID(t *testing.T) { + for name, tt := range map[string]struct { + body string + wantID string + wantOK bool + }{ + "folder": {body: `{"id":"wf-1","active":false,"isArchived":false,"parentFolder":{"id":"fo-1"}}`, wantID: "fo-1", wantOK: true}, + "root": {body: `{"id":"wf-1","active":false,"isArchived":false,"parentFolder":null}`, wantOK: true}, + "absent": {body: `{"id":"wf-1","active":false,"isArchived":false}`}, + } { + t.Run(name, func(t *testing.T) { + var workflow Workflow + if err := json.Unmarshal([]byte(tt.body), &workflow); err != nil { + t.Fatalf("decode: %v", err) + } + id, ok := workflow.ParentFolderID() + if id != tt.wantID || ok != tt.wantOK { + t.Errorf("ParentFolderID = %q, %t; want %q, %t", id, ok, tt.wantID, tt.wantOK) + } + encoded, err := json.Marshal(workflow) + if err != nil { + t.Fatalf("encode: %v", err) + } + assertJSONEqual(t, tt.body, string(encoded)) + }) + } +} + func TestWorkflowDocumentValidate(t *testing.T) { tests := []struct { name string From 308ef96851371c46149a0ec59885bbcfd5d98a32 Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 23:48:07 -0500 Subject: [PATCH 3/7] fix(workflow): name the saved draft and blocking review on 403/409 The API adds reason, versionId and workflowReviewRequestId to the 403 a republishing update answers and to the 409 a blocked publish answers; the error decoder dropped them. APIError now keeps them, update names the draft it saved and the review that blocked republication, and publish/copy name the review instead of guessing between a review and a webhook conflict. Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/cli/workflow.go | 50 +++++++++++++++++++++++++++++-- internal/cli/workflow_copy.go | 4 +-- internal/cli/workflow_test.go | 56 +++++++++++++++++++++++++++++++++++ internal/n8n/errors.go | 20 +++++++++++++ internal/n8n/errors_test.go | 17 +++++++++++ 5 files changed, 142 insertions(+), 5 deletions(-) diff --git a/internal/cli/workflow.go b/internal/cli/workflow.go index 89c9f5a..5a6f786 100644 --- a/internal/cli/workflow.go +++ b/internal/cli/workflow.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -524,12 +525,23 @@ func runWorkflowUpdate(ctx context.Context, opts Options, id string, f workflowU updated, err := client.UpdateWorkflow(ctx, id, doc, updateOpts) if err != nil { if n8n.IsForbidden(err) && !f.noPublish { + saved := "the new version may have been saved as a draft while the published version stays live" + if apiErr, ok := errors.AsType[*n8n.APIError](err); ok && apiErr.VersionID != "" { + saved = fmt.Sprintf("the new version was saved as draft %s while the published version stays live", apiErr.VersionID) + } return forbiddenScopeError(err, resolution, fmt.Sprintf("publishing the update to workflow %q", id), allOf("workflow:activate"), fmt.Sprintf("republishing also needs the project's workflow:publish permission.\n"+ - " the new version may have been saved as a draft while the published version stays live: check with 'n8n workflow get %s'.\n"+ - " re-run with --no-publish to save a draft without this error.", id), + " %s: check with 'n8n workflow get %s'.\n"+ + " re-run with --no-publish to save a draft without this error.", saved, id), workflowResource) } + if n8n.IsConflict(err) && !f.noPublish { + if review := workflowReviewBlock(err); review != "" { + return fmt.Errorf("%s saved the update to workflow %q as a draft but refused to republish it (409): %s; "+ + "the published version stays live. Resolve the review in the n8n UI, or re-run with --no-publish to save a draft without this error: %w", + resolution.URL, id, review, err) + } + } return workflowAPIError(err, resolution, "update") } return writeWorkflowResult(opts, resolution, "Updated", updated, f.output) @@ -823,7 +835,7 @@ func runWorkflowPublish(ctx context.Context, opts Options, id string, f workflow workflow, err := call(ctx, id, request) if err != nil { if n8n.IsConflict(err) { - return fmt.Errorf("%s refused to publish workflow %q (409): an open workflow review or a webhook path already in use is blocking it: %w", resolution.URL, id, err) + return fmt.Errorf("%s refused to publish workflow %q (409): %s is blocking it: %w", resolution.URL, id, workflowPublishConflictCause(err), err) } return workflowAPIError(err, resolution, "publish") } @@ -1375,6 +1387,38 @@ func validateWorkflowArgument(field, value string) error { // status code does not: workflow scopes are per-action, and a 404 can mean the // workflow is gone, archived out of view, or in a project the credential cannot // see. +// workflowReviewBlock describes the open workflow review a 409 names, or +// returns "" when the 409 carries no review (a webhook path conflict). +func workflowReviewBlock(err error) string { + apiErr, ok := errors.AsType[*n8n.APIError](err) + if !ok { + return "" + } + review := "an open workflow review" + if apiErr.ReviewRequestID != "" { + review += " (" + apiErr.ReviewRequestID + ")" + } + switch apiErr.Reason { + case "review_pending": + return review + " is still pending" + case "changes_requested": + return review + " requested changes" + } + if apiErr.ReviewRequestID != "" { + return review + " is blocking publication" + } + return "" +} + +// workflowPublishConflictCause names what blocked a publication: the review +// the 409 reports, or both documented causes when it reports none. +func workflowPublishConflictCause(err error) string { + if review := workflowReviewBlock(err); review != "" { + return review + } + return "an open workflow review or a webhook path already in use" +} + func workflowAPIError(err error, resolution config.Resolution, action string) error { if n8n.IsForbidden(err) { need := workflowScope(action) diff --git a/internal/cli/workflow_copy.go b/internal/cli/workflow_copy.go index bc4a4fc..758476e 100644 --- a/internal/cli/workflow_copy.go +++ b/internal/cli/workflow_copy.go @@ -379,8 +379,8 @@ func workflowCopyPublishError(err error, written *n8n.Workflow, r config.Resolut r.URL, written.Name, written.ID, written.ID, contextName) } if n8n.IsConflict(err) { - return fmt.Errorf("%s refused to publish workflow %q (409): an open workflow review or a webhook path already in use is blocking it. "+ - "The definition was copied and saved; only publication failed: %w", r.URL, written.ID, err) + return fmt.Errorf("%s refused to publish workflow %q (409): %s is blocking it. "+ + "The definition was copied and saved; only publication failed: %w", r.URL, written.ID, workflowPublishConflictCause(err), err) } return fmt.Errorf("target: %w", workflowAPIError(err, r, "publish")) } diff --git a/internal/cli/workflow_test.go b/internal/cli/workflow_test.go index e103208..28c8834 100644 --- a/internal/cli/workflow_test.go +++ b/internal/cli/workflow_test.go @@ -465,6 +465,43 @@ func TestWorkflowUpdateReplacesDefinition(t *testing.T) { }) } +func TestWorkflowUpdateNamesSavedDraftAndReview(t *testing.T) { + t.Run("403 names the draft", func(t *testing.T) { + f := workflowFixture(t, cliWorkflow) + f.route = func(*http.Request, int) (int, string) { + return http.StatusForbidden, `{"message":"missing scope","reason":"insufficient_api_key_scope","versionId":"ver-9"}` + } + got := f.run("workflow", "update", "wf-1", "--input", writeWorkflowFile(t, cliWorkflow)) + if got.code != ExitError || !strings.Contains(got.stderr, "saved as draft ver-9") { + t.Errorf("result = %+v, want the saved draft named", got) + } + }) + + t.Run("409 review keeps the draft", func(t *testing.T) { + f := workflowFixture(t, cliWorkflow) + f.route = func(*http.Request, int) (int, string) { + return http.StatusConflict, `{"message":"pending review","reason":"review_pending","workflowReviewRequestId":"rev-1"}` + } + got := f.run("workflow", "update", "wf-1", "--input", writeWorkflowFile(t, cliWorkflow)) + for _, want := range []string{"409", "as a draft", "review (rev-1) is still pending", "--no-publish"} { + if got.code != ExitError || !strings.Contains(got.stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, got.stderr) + } + } + }) + + t.Run("409 without review is not called a draft", func(t *testing.T) { + f := workflowFixture(t, cliWorkflow) + f.route = func(*http.Request, int) (int, string) { + return http.StatusConflict, `{"message":"webhook path in use"}` + } + got := f.run("workflow", "update", "wf-1", "--input", writeWorkflowFile(t, cliWorkflow)) + if got.code != ExitError || strings.Contains(got.stderr, "as a draft") || !strings.Contains(got.stderr, "webhook path in use") { + t.Errorf("result = %+v", got) + } + }) +} + // A 403 on update is a partial success: the draft is saved, the published // version stays live. The message has to say so, because nothing else will. func TestWorkflowUpdateExplainsPublishDenial(t *testing.T) { @@ -536,6 +573,25 @@ func TestWorkflowPublishOptionsAndConflict(t *testing.T) { assertCLIJSON(t, `{"versionId":"ver-2","name":"Release","description":"retry branch"}`, f.lastBody()) }) + t.Run("conflict names the review", func(t *testing.T) { + f := workflowFixture(t, cliWorkflow) + f.route = func(*http.Request, int) (int, string) { + return http.StatusConflict, `{"message":"pending review","reason":"changes_requested","workflowReviewRequestId":"rev-1"}` + } + got := f.run("workflow", "publish", "wf-1") + if got.code != ExitError { + t.Fatalf("exit = %d, want an error", got.code) + } + for _, want := range []string{"409", "review (rev-1) requested changes"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, got.stderr) + } + } + if strings.Contains(got.stderr, "webhook path") { + t.Errorf("stderr guesses a webhook conflict despite the reported review:\n%s", got.stderr) + } + }) + t.Run("conflict explains the block", func(t *testing.T) { f := workflowFixture(t, cliWorkflow) f.status = http.StatusConflict diff --git a/internal/n8n/errors.go b/internal/n8n/errors.go index 02d9db7..0261001 100644 --- a/internal/n8n/errors.go +++ b/internal/n8n/errors.go @@ -30,6 +30,16 @@ type APIError struct { Hint string // remediation hint, when sent Body string // truncated raw body, set when it was not decodable JSON Truncated bool // body was longer than maxErrorBody + + // Reason is the machine-readable cause some endpoints add, e.g. + // review_pending on a 409 from workflow publish. + Reason string + // VersionID names the draft a workflow update saved before its + // republication was refused (403). + VersionID string + // ReviewRequestID names the open workflow review that blocked a + // publication (409). + ReviewRequestID string } func (e *APIError) Error() string { @@ -41,6 +51,9 @@ func (e *APIError) Error() string { if e.Code != "" { fmt.Fprintf(&b, " [%s]", e.Code) } + if e.Reason != "" && e.Reason != e.Code { + fmt.Fprintf(&b, " [%s]", e.Reason) + } switch { case e.Message != "": b.WriteString(": ") @@ -128,6 +141,10 @@ type errorBody struct { Code json.RawMessage `json:"code"` Hint json.RawMessage `json:"hint"` Description json.RawMessage `json:"description"` + + Reason json.RawMessage `json:"reason"` + VersionID json.RawMessage `json:"versionId"` + WorkflowReviewRequestID json.RawMessage `json:"workflowReviewRequestId"` } // newAPIError builds an error from a response body that has already been read @@ -151,6 +168,9 @@ func newAPIError(resp *http.Response, method, path string, body []byte, truncate apiErr.Message = firstText(decoded.Message, decoded.Error, decoded.Description) apiErr.Code = firstText(decoded.Code) apiErr.Hint = firstText(decoded.Hint) + apiErr.Reason = firstText(decoded.Reason) + apiErr.VersionID = firstText(decoded.VersionID) + apiErr.ReviewRequestID = firstText(decoded.WorkflowReviewRequestID) if apiErr.Message == "" && apiErr.Code == "" { // Valid JSON in a shape we do not know: keep it rather than drop it. apiErr.Body = truncateText(strings.TrimSpace(string(body)), 512) diff --git a/internal/n8n/errors_test.go b/internal/n8n/errors_test.go index 564726d..cdae356 100644 --- a/internal/n8n/errors_test.go +++ b/internal/n8n/errors_test.go @@ -131,6 +131,23 @@ func TestAPIErrorMessage(t *testing.T) { } } +func TestAPIErrorWorkflowReviewDetails(t *testing.T) { + conflict := decodeError(t, http.StatusConflict, nil, + `{"message":"Workflow has a pending review","reason":"review_pending","workflowReviewRequestId":"rev-1"}`) + if conflict.Reason != "review_pending" || conflict.ReviewRequestID != "rev-1" || conflict.Message == "" { + t.Errorf("conflict = %+v", conflict) + } + if !strings.Contains(conflict.Error(), "[review_pending]") { + t.Errorf("Error() = %q, want the reason", conflict) + } + + draft := decodeError(t, http.StatusForbidden, nil, + `{"message":"missing workflow:activate","reason":"insufficient_api_key_scope","versionId":"ver-9"}`) + if draft.Reason != "insufficient_api_key_scope" || draft.VersionID != "ver-9" { + t.Errorf("draft = %+v", draft) + } +} + func TestAPIErrorMessageWithoutStatusText(t *testing.T) { err := &APIError{StatusCode: 599} if got := err.Error(); got != "HTTP 599" { From d888632ca7585f0699a9ee10fb91c97c3359011d Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 23:51:07 -0500 Subject: [PATCH 4/7] fix(credential): accept description and custom id, keep usageScope Create now accepts description (at most 512 characters) and a caller-chosen id (1-16 of [a-zA-Z0-9_-]), validated locally; update accepts description, where null or blank clears it. Reads keep description (absent vs null preserved) and the usageScope delete returns. Unknown response fields are still discarded rather than kept in an Extra map, so an unexpected secret-bearing field cannot reach output. Adds n8n.Nullable for write fields where null differs from omission. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/n8n_credential_create.md | 7 ++- docs/n8n_credential_update.md | 10 ++-- internal/cli/credential.go | 23 ++++++--- internal/cli/credential_test.go | 51 ++++++++++++++++++ internal/n8n/credential.go | 74 +++++++++++++++++++++----- internal/n8n/credential_test.go | 92 +++++++++++++++++++++++++++++++++ internal/n8n/nullable.go | 50 ++++++++++++++++++ internal/n8n/nullable_test.go | 40 ++++++++++++++ 8 files changed, 321 insertions(+), 26 deletions(-) create mode 100644 internal/n8n/nullable.go create mode 100644 internal/n8n/nullable_test.go diff --git a/docs/n8n_credential_create.md b/docs/n8n_credential_create.md index e55cc18..8dda298 100644 --- a/docs/n8n_credential_create.md +++ b/docs/n8n_credential_create.md @@ -5,8 +5,11 @@ Create a credential from secret JSON ### Synopsis Create a credential from one JSON document. Required fields are name, type and -data; optional fields are projectId and isResolvable. Because data contains -secrets, JSON is accepted only through --file or piped --stdin, never argv. +data; optional fields are projectId, isResolvable, description (plain text, at +most 512 characters; ignored when the instance has descriptions disabled) and +id (1 to 16 letters, digits, underscores or hyphens, kept exactly; omit it to +have one generated). Because data contains secrets, JSON is accepted only +through --file or piped --stdin, never argv. The request body is excluded from debug logs. Output contains metadata only. Requires credential:create; project creation can have additional role restrictions. diff --git a/docs/n8n_credential_update.md b/docs/n8n_credential_update.md index 535fc21..f9e7a87 100644 --- a/docs/n8n_credential_update.md +++ b/docs/n8n_credential_update.md @@ -4,10 +4,12 @@ Update a credential from secret JSON ### Synopsis -Update an owned credential from one JSON document. Accepted fields are name, type, -data, isGlobal, isResolvable and isPartialData. Set isPartialData=true to merge -provided data with stored data; false replaces the full data object. Changing type -requires data. Managed credentials cannot be edited. +Update an owned credential from one JSON document. Accepted fields are name, +description, type, data, isGlobal, isResolvable and isPartialData. Set +isPartialData=true to merge provided data with stored data; false replaces the +full data object. Changing type requires data. description is at most 512 +characters; null or "" clears it and omitting it keeps it. Managed credentials +cannot be edited. Secret JSON is accepted only through --file or piped --stdin and is excluded from debug logs and output. Requires credential:update and ownership. diff --git a/internal/cli/credential.go b/internal/cli/credential.go index aef8d20..fe2dc96 100644 --- a/internal/cli/credential.go +++ b/internal/cli/credential.go @@ -217,8 +217,11 @@ func newCredentialCreateCommand(opts Options) *cobra.Command { Use: "create", Short: "Create a credential from secret JSON", Long: "Create a credential from one JSON document. Required fields are name, type and\n" + - "data; optional fields are projectId and isResolvable. Because data contains\n" + - "secrets, JSON is accepted only through --file or piped --stdin, never argv.\n\n" + + "data; optional fields are projectId, isResolvable, description (plain text, at\n" + + "most 512 characters; ignored when the instance has descriptions disabled) and\n" + + "id (1 to 16 letters, digits, underscores or hyphens, kept exactly; omit it to\n" + + "have one generated). Because data contains secrets, JSON is accepted only\n" + + "through --file or piped --stdin, never argv.\n\n" + "The request body is excluded from debug logs. Output contains metadata only.\n" + "Requires credential:create; project creation can have additional role restrictions.", Example: " n8n credential create --file credential.json\n" + @@ -259,10 +262,12 @@ func newCredentialUpdateCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "update ", Short: "Update a credential from secret JSON", - Long: "Update an owned credential from one JSON document. Accepted fields are name, type,\n" + - "data, isGlobal, isResolvable and isPartialData. Set isPartialData=true to merge\n" + - "provided data with stored data; false replaces the full data object. Changing type\n" + - "requires data. Managed credentials cannot be edited.\n\n" + + Long: "Update an owned credential from one JSON document. Accepted fields are name,\n" + + "description, type, data, isGlobal, isResolvable and isPartialData. Set\n" + + "isPartialData=true to merge provided data with stored data; false replaces the\n" + + "full data object. Changing type requires data. description is at most 512\n" + + "characters; null or \"\" clears it and omitting it keeps it. Managed credentials\n" + + "cannot be edited.\n\n" + "Secret JSON is accepted only through --file or piped --stdin and is excluded from\n" + "debug logs and output. Requires credential:update and ownership.", Example: " n8n credential update CREDENTIAL_ID --file update.json\n" + @@ -362,6 +367,12 @@ func writeCredentialResult(opts Options, resolution config.Resolution, action st fmt.Fprintf(tw, "%s:\t%s\n", action, credential.ID) fmt.Fprintf(tw, "Name:\t%s\n", credential.Name) fmt.Fprintf(tw, "Type:\t%s\n", credential.Type) + if credential.Description.Set { + fmt.Fprintf(tw, "Description:\t%s\n", emptyDash(credential.Description.Value)) + } + if credential.UsageScope != "" { + fmt.Fprintf(tw, "Usage scope:\t%s\n", credential.UsageScope) + } fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) if credential.UpdatedAt != "" { fmt.Fprintf(tw, "Updated:\t%s\n", credential.UpdatedAt) diff --git a/internal/cli/credential_test.go b/internal/cli/credential_test.go index 58839fa..be59f7b 100644 --- a/internal/cli/credential_test.go +++ b/internal/cli/credential_test.go @@ -125,6 +125,57 @@ func TestCredentialUpdateFromPipedStdin(t *testing.T) { } } +func TestCredentialDescriptionAndCustomID(t *testing.T) { + response := strings.Replace(cliCredential, `"id":"credential-id",`, `"id":"credential-id","description":"Read-only key","usageScope":"instance",`, 1) + + t.Run("create", func(t *testing.T) { + f := credentialFixture(t, response) + f.interactive = false + f.stdin = `{"id":"gh_prod-1","name":"GitHub","description":"Read-only key","type":"githubApi","data":{"accessToken":"` + cliCredentialSecret + `"}}` + got := f.run("credential", "create", "--stdin") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + assertCLIJSON(t, f.stdin, f.lastBody()) + for _, want := range []string{"Description:", "Read-only key", "Usage scope:", "instance"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + assertNoCredentialSecret(t, got) + }) + + t.Run("update clears with null", func(t *testing.T) { + f := credentialFixture(t, response) + f.interactive = false + f.stdin = `{"description":null}` + got := f.run("credential", "update", "credential-id", "--stdin", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + assertCLIJSON(t, `{"description":null}`, f.lastBody()) + if !strings.Contains(got.stdout, `"usageScope": "instance"`) || !strings.Contains(got.stdout, `"description": "Read-only key"`) { + t.Errorf("stdout lost description or usageScope:\n%s", got.stdout) + } + }) + + for name, stdin := range map[string]string{ + "invalid id": `{"id":"has space","name":"x","type":"t","data":{}}`, + "long description": `{"name":"x","type":"t","data":{},"description":"` + strings.Repeat("a", 513) + `"}`, + } { + t.Run(name, func(t *testing.T) { + f := credentialFixture(t, response) + f.interactive = false + f.stdin = stdin + before := f.requestCount() + got := f.run("credential", "create", "--stdin") + if got.code != ExitError || f.requestCount() != before { + t.Errorf("result = %+v, want a local validation error", got) + } + }) + } +} + func TestCredentialGetDropsUnexpectedData(t *testing.T) { f := credentialFixture(t, cliCredential) got := f.run("credential", "get", "credential-id", "--output", "json") diff --git a/internal/n8n/credential.go b/internal/n8n/credential.go index ea17263..4b08710 100644 --- a/internal/n8n/credential.go +++ b/internal/n8n/credential.go @@ -8,7 +8,9 @@ import ( "fmt" "log/slog" "net/http" + "regexp" "strings" + "unicode/utf8" ) // CredentialsPath is the collection endpoint for credentials. @@ -29,6 +31,13 @@ type Credential struct { CreatedAt string `json:"createdAt,omitempty"` UpdatedAt string `json:"updatedAt,omitempty"` Shared []CredentialShare `json:"shared,omitempty"` + // Description is absent when the instance has credential descriptions + // disabled and null when the credential has none. + Description Nullable[string] `json:"description,omitzero"` + // UsageScope is project or instance; delete reports it. + UsageScope string `json:"usageScope,omitempty"` + // No Extra map here, unlike other read models: an unknown field may be + // secret-bearing, so anything not named above is discarded. } // CredentialShare identifies a project with which a credential is shared. @@ -84,10 +93,20 @@ func (d CredentialData) LogValue() slog.Value { return slog.StringValue(Redac func (d CredentialData) valid() bool { return len(d.raw) != 0 } func (d CredentialData) reveal() json.RawMessage { return append(json.RawMessage(nil), d.raw...) } +// MaxCredentialDescription is the longest description the API accepts, in +// characters. +const MaxCredentialDescription = 512 + +// credentialIDPattern is the shape of a caller-chosen credential ID. +var credentialIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,16}$`) + // CreateCredentialRequest is the secret-bearing document used to create one // credential. Data is required; optional booleans retain omitted-vs-false. +// ID is optional: omit it and the instance generates one. type CreateCredentialRequest struct { + ID string `json:"id,omitempty"` Name string `json:"name"` + Description *string `json:"description,omitempty"` Type string `json:"type"` Data CredentialData `json:"data"` IsResolvable *bool `json:"isResolvable,omitempty"` @@ -96,9 +115,17 @@ type CreateCredentialRequest struct { // Validate rejects malformed create documents before transport. func (r CreateCredentialRequest) Validate() error { + if r.ID != "" && !credentialIDPattern.MatchString(r.ID) { + return fmt.Errorf("credential id %q is invalid: use 1 to 16 letters, digits, underscores or hyphens, or omit it to have one generated", r.ID) + } if err := validateCredentialText("name", r.Name, true); err != nil { return err } + if r.Description != nil { + if err := validateCredentialDescription(*r.Description); err != nil { + return err + } + } if err := validateCredentialText("type", r.Type, true); err != nil { return err } @@ -113,13 +140,17 @@ func (r CreateCredentialRequest) Validate() error { // UpdateCredentialRequest contains fields accepted by PATCH /credentials/{id}. // Pointers preserve omitted values, especially false booleans and empty data. +// +// Description is tri-state: omitted keeps the stored value, null or blank +// clears it. type UpdateCredentialRequest struct { - Name *string `json:"name,omitempty"` - Type *string `json:"type,omitempty"` - Data *CredentialData `json:"data,omitempty"` - IsGlobal *bool `json:"isGlobal,omitempty"` - IsResolvable *bool `json:"isResolvable,omitempty"` - IsPartialData *bool `json:"isPartialData,omitempty"` + Name *string `json:"name,omitempty"` + Description Nullable[string] `json:"description,omitzero"` + Type *string `json:"type,omitempty"` + Data *CredentialData `json:"data,omitempty"` + IsGlobal *bool `json:"isGlobal,omitempty"` + IsResolvable *bool `json:"isResolvable,omitempty"` + IsPartialData *bool `json:"isPartialData,omitempty"` } // Validate rejects invalid text and an invalid programmatically-built data @@ -130,6 +161,11 @@ func (r UpdateCredentialRequest) Validate() error { return err } } + if r.Description.Set && !r.Description.Null { + if err := validateCredentialDescription(r.Description.Value); err != nil { + return err + } + } if r.Type != nil { if err := validateCredentialText("type", *r.Type, true); err != nil { return err @@ -168,12 +204,14 @@ func (c *Client) CreateCredential(ctx context.Context, request CreateCredentialR return nil, err } wire := struct { + ID string `json:"id,omitempty"` Name string `json:"name"` + Description *string `json:"description,omitempty"` Type string `json:"type"` Data json.RawMessage `json:"data"` IsResolvable *bool `json:"isResolvable,omitempty"` ProjectID string `json:"projectId,omitempty"` - }{request.Name, request.Type, request.Data.reveal(), request.IsResolvable, request.ProjectID} + }{request.ID, request.Name, request.Description, request.Type, request.Data.reveal(), request.IsResolvable, request.ProjectID} var created Credential if _, err := c.Do(ctx, Request{Method: http.MethodPost, Path: CredentialsPath, Body: wire}, &created); err != nil { return nil, redactCredentialAPIError(err) @@ -203,13 +241,14 @@ func (c *Client) UpdateCredential(ctx context.Context, id string, request Update return nil, err } wire := struct { - Name *string `json:"name,omitempty"` - Type *string `json:"type,omitempty"` - Data json.RawMessage `json:"data,omitempty"` - IsGlobal *bool `json:"isGlobal,omitempty"` - IsResolvable *bool `json:"isResolvable,omitempty"` - IsPartialData *bool `json:"isPartialData,omitempty"` - }{Name: request.Name, Type: request.Type, IsGlobal: request.IsGlobal, IsResolvable: request.IsResolvable, IsPartialData: request.IsPartialData} + Name *string `json:"name,omitempty"` + Description Nullable[string] `json:"description,omitzero"` + Type *string `json:"type,omitempty"` + Data json.RawMessage `json:"data,omitempty"` + IsGlobal *bool `json:"isGlobal,omitempty"` + IsResolvable *bool `json:"isResolvable,omitempty"` + IsPartialData *bool `json:"isPartialData,omitempty"` + }{Name: request.Name, Description: request.Description, Type: request.Type, IsGlobal: request.IsGlobal, IsResolvable: request.IsResolvable, IsPartialData: request.IsPartialData} if request.Data != nil { wire.Data = request.Data.reveal() } @@ -279,6 +318,13 @@ func validateCredentialID(id string) error { return validateCredentialText("ID", id, true) } +func validateCredentialDescription(value string) error { + if n := utf8.RuneCountInString(value); n > MaxCredentialDescription { + return fmt.Errorf("credential description is %d characters; the API accepts at most %d", n, MaxCredentialDescription) + } + return nil +} + func validateCredentialText(field, value string, required bool) error { if required && strings.TrimSpace(value) == "" { return fmt.Errorf("credential %s is required", field) diff --git a/internal/n8n/credential_test.go b/internal/n8n/credential_test.go index 6833c9c..231d1a4 100644 --- a/internal/n8n/credential_test.go +++ b/internal/n8n/credential_test.go @@ -217,6 +217,98 @@ func TestCredentialMutationErrorRedaction(t *testing.T) { } } +func TestCredentialDescriptionUsageScopeAndCustomID(t *testing.T) { + for name, tt := range map[string]struct { + field string + want Nullable[string] + json string + }{ + "value": {field: `"description":"Read-only key",`, want: SetValue("Read-only key"), json: `"description":"Read-only key"`}, + "null": {field: `"description":null,`, want: SetNull[string](), json: `"description":null`}, + "absent": {}, + } { + t.Run(name, func(t *testing.T) { + body := strings.Replace(credentialResponse, `"id":"cred/one?x=1",`, `"id":"cred/one?x=1",`+tt.field+`"usageScope":"project",`, 1) + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + deleted, err := server.client(t).DeleteCredential(context.Background(), "cred-1") + if err != nil { + t.Fatalf("DeleteCredential: %v", err) + } + if deleted.Description != tt.want || deleted.UsageScope != "project" { + t.Errorf("credential = %+v", deleted) + } + encoded, err := json.Marshal(deleted) + if err != nil { + t.Fatalf("encode: %v", err) + } + if tt.json == "" && strings.Contains(string(encoded), "description") { + t.Errorf("encoded = %s, want description omitted", encoded) + } + if tt.json != "" && !strings.Contains(string(encoded), tt.json) { + t.Errorf("encoded = %s, want %s", encoded, tt.json) + } + if strings.Contains(string(encoded), "server-secret") { + t.Errorf("encoded leaked data: %s", encoded) + } + }) + } + + t.Run("create sends id and description", func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, credentialResponse)) + description := "Read-only key" + _, err := server.client(t).CreateCredential(context.Background(), CreateCredentialRequest{ + ID: "gh_prod-1", Name: "GitHub", Description: &description, Type: "githubApi", + Data: mustCredentialData(t, `{"accessToken":"x"}`), + }) + if err != nil { + t.Fatalf("CreateCredential: %v", err) + } + _, body := server.last(t) + assertJSONEqual(t, `{"id":"gh_prod-1","name":"GitHub","description":"Read-only key","type":"githubApi","data":{"accessToken":"x"}}`, body) + }) + + for name, tt := range map[string]struct { + request UpdateCredentialRequest + body string + }{ + "update sets description": {request: UpdateCredentialRequest{Description: SetValue("new")}, body: `{"description":"new"}`}, + "update clears with null": {request: UpdateCredentialRequest{Description: SetNull[string]()}, body: `{"description":null}`}, + "update omits description": {request: UpdateCredentialRequest{Name: new("renamed")}, body: `{"name":"renamed"}`}, + } { + t.Run(name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, credentialResponse)) + if _, err := server.client(t).UpdateCredential(context.Background(), "cred-1", tt.request); err != nil { + t.Fatalf("UpdateCredential: %v", err) + } + _, body := server.last(t) + assertJSONEqual(t, tt.body, body) + }) + } +} + +func TestCredentialDescriptionAndIDLimits(t *testing.T) { + data := mustCredentialData(t, `{"accessToken":"x"}`) + atLimit := strings.Repeat("é", MaxCredentialDescription) + overLimit := atLimit + "x" + valid := CreateCredentialRequest{Name: "n", Type: "t", Data: data, Description: &atLimit, ID: "abcDEF0123_-xyzQ"} + if err := valid.Validate(); err != nil { + t.Errorf("512-character description and 16-character id: %v", err) + } + for name, request := range map[string]CreateCredentialRequest{ + "long description": {Name: "n", Type: "t", Data: data, Description: &overLimit}, + "long id": {Name: "n", Type: "t", Data: data, ID: "abcdefghijklmnopq"}, + "id with slash": {Name: "n", Type: "t", Data: data, ID: "a/b"}, + "id with space": {Name: "n", Type: "t", Data: data, ID: "a b"}, + } { + if err := request.Validate(); err == nil { + t.Errorf("%s: want a validation error", name) + } + } + if err := (UpdateCredentialRequest{Description: SetValue(overLimit)}).Validate(); err == nil { + t.Error("update with a 513-character description: want a validation error") + } +} + func TestCredentialValidationBeforeRequest(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, credentialResponse)) client := server.client(t) diff --git a/internal/n8n/nullable.go b/internal/n8n/nullable.go new file mode 100644 index 0000000..38245e7 --- /dev/null +++ b/internal/n8n/nullable.go @@ -0,0 +1,50 @@ +package n8n + +import ( + "bytes" + "encoding/json" +) + +// Nullable is an optional write field that can also be sent as JSON null, +// for schemas where null means something omission does not (clear a +// description, move a variable to global scope). The zero value is "omitted"; +// tag the field with omitzero so it is left out of the request. +type Nullable[T any] struct { + Value T + // Null sends an explicit JSON null instead of Value. + Null bool + // Set reports that the field is present at all. + Set bool +} + +// SetValue returns a present, non-null field. +func SetValue[T any](value T) Nullable[T] { return Nullable[T]{Value: value, Set: true} } + +// SetNull returns a present field sent as JSON null. +func SetNull[T any]() Nullable[T] { return Nullable[T]{Null: true, Set: true} } + +// IsZero reports an omitted field, for the omitzero tag option. +func (n Nullable[T]) IsZero() bool { return !n.Set } + +// MarshalJSON writes null or the value. +func (n Nullable[T]) MarshalJSON() ([]byte, error) { + if n.Null || !n.Set { + return []byte("null"), nil + } + return json.Marshal(n.Value) +} + +// UnmarshalJSON records presence, so a strict input document can clear a +// field with null rather than have the null read as "omitted". +func (n *Nullable[T]) UnmarshalJSON(data []byte) error { + if bytes.Equal(bytes.TrimSpace(data), []byte("null")) { + *n = SetNull[T]() + return nil + } + var value T + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *n = SetValue(value) + return nil +} diff --git a/internal/n8n/nullable_test.go b/internal/n8n/nullable_test.go new file mode 100644 index 0000000..e89af3b --- /dev/null +++ b/internal/n8n/nullable_test.go @@ -0,0 +1,40 @@ +package n8n + +import ( + "encoding/json" + "testing" +) + +func TestNullableEncodesOmittedNullAndValue(t *testing.T) { + type doc struct { + Field Nullable[string] `json:"field,omitzero"` + } + for name, tt := range map[string]struct { + value Nullable[string] + json string + }{ + "omitted": {json: `{}`}, + "null": {value: SetNull[string](), json: `{"field":null}`}, + "value": {value: SetValue("x"), json: `{"field":"x"}`}, + "empty": {value: SetValue(""), json: `{"field":""}`}, + } { + t.Run(name, func(t *testing.T) { + encoded, err := json.Marshal(doc{Field: tt.value}) + if err != nil || string(encoded) != tt.json { + t.Errorf("Marshal = %s (error: %v), want %s", encoded, err, tt.json) + } + var decoded doc + if err := json.Unmarshal([]byte(tt.json), &decoded); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + if decoded.Field != tt.value { + t.Errorf("Unmarshal = %+v, want %+v", decoded.Field, tt.value) + } + }) + } + + var bad doc + if err := json.Unmarshal([]byte(`{"field":1}`), &bad); err == nil { + t.Error("a number decoded into Nullable[string]") + } +} From a67e97f2dcf1abc8eaf8439eea8be8c8d56dfa61 Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 23:53:07 -0500 Subject: [PATCH 5/7] fix(datatable): drop json columns, validate sort order and column names - column type json is gone from the contract: refuse it locally with a message pointing at string, for table and column creation - table list --sort-by is a closed enum (name|createdAt|updatedAt|size x asc|desc); row sort keeps the columnName:asc|desc shape check - column names (create, add, rename, row filters) must match ^[a-zA-Z][a-zA-Z0-9_]*$ and be at most 63 characters Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/n8n_data-table_column_create.md | 4 +- docs/n8n_data-table_create.md | 14 +++-- docs/n8n_data-table_list.md | 8 +-- internal/cli/datatable.go | 28 +++++---- internal/cli/datatable_test.go | 13 ++++- internal/n8n/datatable.go | 86 ++++++++++++++++++++-------- internal/n8n/datatable_test.go | 26 ++++++++- 7 files changed, 129 insertions(+), 50 deletions(-) diff --git a/docs/n8n_data-table_column_create.md b/docs/n8n_data-table_column_create.md index 4083966..b8b2823 100644 --- a/docs/n8n_data-table_column_create.md +++ b/docs/n8n_data-table_column_create.md @@ -5,7 +5,9 @@ Add a column to a data table ### Synopsis Add one column to an existing data table. The type is one of string, number, boolean, date -and cannot be changed afterwards; recreate the column to change it. +and cannot be changed afterwards; recreate the column to change it. The name +starts with a letter, uses only letters, digits and underscores, and is at +most 63 characters. Without --index the column is appended after the existing ones. Existing rows get an empty value in the new column. A name already used in the table comes diff --git a/docs/n8n_data-table_create.md b/docs/n8n_data-table_create.md index b1e10d2..55dfb2b 100644 --- a/docs/n8n_data-table_create.md +++ b/docs/n8n_data-table_create.md @@ -7,11 +7,13 @@ Create a data table Create one data table with its columns. Pass --column once per column as NAME:TYPE; at least one is required, and the column order is the order given. -Documented types are string, number, boolean, date and json, though instances -can reject json with a 400. Without --project-id the table is created in the -caller's personal project. The system columns id, createdAt and updatedAt are -added by n8n; do not declare them. Add more columns later with -'n8n data-table column create'. Requires dataTable:create. +Types are string, number, boolean, date; the API no longer accepts json, +so store JSON in a string column. Column names start with a letter, use only +letters, digits and underscores, and are at most 63 characters. Without +--project-id the table is created in the caller's personal project. The +system columns id, createdAt and updatedAt are added by n8n; do not declare +them. Add more columns later with 'n8n data-table column create'. Requires +dataTable:create. ``` n8n data-table create [flags] @@ -28,7 +30,7 @@ n8n data-table create [flags] ### Options ``` - --column stringArray column as NAME:TYPE, repeatable and required, e.g. email:string (types: string, number, boolean, date, json) + --column stringArray column as NAME:TYPE, repeatable and required, e.g. email:string (types: string, number, boolean, date) --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') -h, --help help for create --output string output format: text or json (JSON is the created table) (default "text") diff --git a/docs/n8n_data-table_list.md b/docs/n8n_data-table_list.md index d9bd400..f9745b1 100644 --- a/docs/n8n_data-table_list.md +++ b/docs/n8n_data-table_list.md @@ -9,9 +9,9 @@ time. Pass a returned cursor to --cursor for the next page, or use --all to follow every cursor, capped at 10,000 tables. Use this to find the table ID every other command takes. --name is the only -filter the API documents. --sort-by takes field:asc or field:desc, for example -name:asc or size:desc, where size orders by the reported sizeBytes. Requires -dataTable:list and API-key authentication. +filter the API documents. --sort-by takes name, createdAt, updatedAt or size, +then :asc or :desc, for example name:asc or size:desc, where size orders by +the reported sizeBytes. Requires dataTable:list and API-key authentication. With --all, JSON output adds a collection object. Its truncated field is true, and a warning goes to stderr, when the walk stopped at the 10,000-item limit @@ -43,7 +43,7 @@ n8n data-table list [flags] --limit int tables per API page, 1 to 250 (default: server default of 100) --name string only tables with this name (default: every table) --output string output format: text or json (JSON is a page object with data and nextCursor, plus collection with --all) (default "text") - --sort-by string sort order as field:asc or field:desc, e.g. name:asc or size:desc (default: the server's order) + --sort-by string sort order, one of name:asc, name:desc, createdAt:asc, createdAt:desc, updatedAt:asc, updatedAt:desc, size:asc, size:desc (default: the server's order) --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) ``` diff --git a/internal/cli/datatable.go b/internal/cli/datatable.go index 29639c2..c4a6652 100644 --- a/internal/cli/datatable.go +++ b/internal/cli/datatable.go @@ -93,9 +93,9 @@ func newDataTableListCommand(opts Options) *cobra.Command { "time. Pass a returned cursor to --cursor for the next page, or use --all to\n" + "follow every cursor, capped at 10,000 tables.\n\n" + "Use this to find the table ID every other command takes. --name is the only\n" + - "filter the API documents. --sort-by takes field:asc or field:desc, for example\n" + - "name:asc or size:desc, where size orders by the reported sizeBytes. Requires\n" + - "dataTable:list and API-key authentication.\n\n" + cursorCollectionHelp, + "filter the API documents. --sort-by takes name, createdAt, updatedAt or size,\n" + + "then :asc or :desc, for example name:asc or size:desc, where size orders by\n" + + "the reported sizeBytes. Requires dataTable:list and API-key authentication.\n\n" + cursorCollectionHelp, Example: " n8n data-table list\n" + " n8n data-table list --name customers\n" + " n8n data-table list --sort-by size:desc --limit 50 --output json\n" + @@ -110,7 +110,7 @@ func newDataTableListCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.cursor, "cursor", "", "pagination cursor returned by a previous list (default: the first page)") cmd.Flags().BoolVar(&f.all, "all", false, "follow every page instead of one (maximum 10,000 tables; hitting it warns and sets JSON collection.truncated)") cmd.Flags().StringVar(&f.name, "name", "", "only tables with this name (default: every table)") - cmd.Flags().StringVar(&f.sortBy, "sort-by", "", "sort order as field:asc or field:desc, e.g. name:asc or size:desc (default: the server's order)") + cmd.Flags().StringVar(&f.sortBy, "sort-by", "", "sort order, one of "+strings.Join(n8n.DataTableSortOrders, ", ")+" (default: the server's order)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is a page object with data and nextCursor, plus collection with --all)") return cmd } @@ -191,11 +191,13 @@ func newDataTableCreateCommand(opts Options) *cobra.Command { Short: "Create a data table", Long: "Create one data table with its columns. Pass --column once per column as\n" + "NAME:TYPE; at least one is required, and the column order is the order given.\n\n" + - "Documented types are string, number, boolean, date and json, though instances\n" + - "can reject json with a 400. Without --project-id the table is created in the\n" + - "caller's personal project. The system columns id, createdAt and updatedAt are\n" + - "added by n8n; do not declare them. Add more columns later with\n" + - "'n8n data-table column create'. Requires dataTable:create.", + "Types are " + strings.Join(n8n.DataTableColumnTypes, ", ") + "; the API no longer accepts json,\n" + + "so store JSON in a string column. Column names start with a letter, use only\n" + + "letters, digits and underscores, and are at most 63 characters. Without\n" + + "--project-id the table is created in the caller's personal project. The\n" + + "system columns id, createdAt and updatedAt are added by n8n; do not declare\n" + + "them. Add more columns later with 'n8n data-table column create'. Requires\n" + + "dataTable:create.", Example: " n8n data-table create customers --column email:string --column age:number\n" + " n8n data-table create orders --column total:number --column paid:boolean --column placed:date\n" + " n8n data-table create customers --column email:string --project-id PROJECT_ID --output json", @@ -205,7 +207,7 @@ func newDataTableCreateCommand(opts Options) *cobra.Command { }, } f.instance.register(cmd) - cmd.Flags().StringArrayVar(&f.columns, "column", nil, "column as NAME:TYPE, repeatable and required, e.g. email:string (types: "+strings.Join(n8n.DataTableCreateColumnTypes, ", ")+")") + cmd.Flags().StringArrayVar(&f.columns, "column", nil, "column as NAME:TYPE, repeatable and required, e.g. email:string (types: "+strings.Join(n8n.DataTableColumnTypes, ", ")+")") cmd.Flags().StringVar(&f.projectID, "project-id", "", "project to create the table in (default: the caller's personal project)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the created table)") return cmd @@ -244,7 +246,7 @@ func dataTableColumnDefinitions(values []string) ([]n8n.DataTableColumnDefinitio for _, value := range values { name, columnType, ok := strings.Cut(value, ":") if !ok { - return nil, fmt.Errorf("--column %q is not NAME:TYPE: pass the column name, a colon, then one of %s", value, strings.Join(n8n.DataTableCreateColumnTypes, ", ")) + return nil, fmt.Errorf("--column %q is not NAME:TYPE: pass the column name, a colon, then one of %s", value, strings.Join(n8n.DataTableColumnTypes, ", ")) } if seen[name] { return nil, fmt.Errorf("--column %q is given twice", name) @@ -1241,7 +1243,9 @@ func newDataTableColumnCreateCommand(opts Options) *cobra.Command { Short: "Add a column to a data table", Long: "Add one column to an existing data table. The type is one of " + strings.Join(n8n.DataTableColumnTypes, ", ") + "\n" + - "and cannot be changed afterwards; recreate the column to change it.\n\n" + + "and cannot be changed afterwards; recreate the column to change it. The name\n" + + "starts with a letter, uses only letters, digits and underscores, and is at\n" + + "most 63 characters.\n\n" + "Without --index the column is appended after the existing ones. Existing rows\n" + "get an empty value in the new column. A name already used in the table comes\n" + "back as a 409. Requires dataTableColumn:create.", diff --git a/internal/cli/datatable_test.go b/internal/cli/datatable_test.go index d6164cb..bcdeff3 100644 --- a/internal/cli/datatable_test.go +++ b/internal/cli/datatable_test.go @@ -530,7 +530,12 @@ func TestDataTableValidationBeforeRequest(t *testing.T) { }{ {name: "unknown output", args: []string{"data-table", "list", "--output", "yaml"}, want: "unknown output format"}, {name: "large limit", args: []string{"data-table", "list", "--limit", "251"}, want: "must not exceed 250"}, - {name: "malformed sort", args: []string{"data-table", "list", "--sort-by", "name"}, want: "field:asc"}, + {name: "malformed sort", args: []string{"data-table", "list", "--sort-by", "name"}, want: "unknown data table sort order"}, + {name: "unsortable field", args: []string{"data-table", "list", "--sort-by", "id:asc"}, want: "size:desc"}, + {name: "create json column", args: []string{"data-table", "create", "customers", "--column", "meta:json"}, want: "json columns are no longer supported"}, + {name: "create column name with dash", args: []string{"data-table", "create", "customers", "--column", "e-mail:string"}, want: "start with a letter"}, + {name: "create column name too long", args: []string{"data-table", "create", "customers", "--column", strings.Repeat("a", 64) + ":string"}, want: "at most 63"}, + {name: "row sort malformed", args: []string{"data-table", "row", "list", "dt-1", "--sort-by", "age"}, want: "columnName:asc"}, {name: "create without columns", args: []string{"data-table", "create", "customers"}, want: "--column is required"}, {name: "create malformed column", args: []string{"data-table", "create", "customers", "--column", "email"}, want: "NAME:TYPE"}, {name: "create duplicate column", args: []string{"data-table", "create", "customers", "--column", "a:string", "--column", "a:number"}, want: "given twice"}, @@ -555,7 +560,11 @@ func TestDataTableValidationBeforeRequest(t *testing.T) { {name: "row upsert without filter", args: []string{"data-table", "row", "upsert", "dt-1", "--set", "a=1"}, want: "--where or --filter is required"}, {name: "row delete without filter", args: []string{"data-table", "row", "delete", "dt-1", "--yes"}, want: "--where or --filter is required"}, {name: "row clear blank table", args: []string{"data-table", "row", "clear", " ", "--yes"}, want: "data table ID is required"}, - {name: "column create unknown type", args: []string{"data-table", "column", "create", "dt-1", "meta", "json"}, want: "unknown column type"}, + {name: "column create json type", args: []string{"data-table", "column", "create", "dt-1", "meta", "json"}, want: "json columns are no longer supported"}, + {name: "column create unknown type", args: []string{"data-table", "column", "create", "dt-1", "meta", "text"}, want: "unknown column type"}, + {name: "column create digit name", args: []string{"data-table", "column", "create", "dt-1", "1st", "string"}, want: "start with a letter"}, + {name: "column rename invalid", args: []string{"data-table", "column", "update", "dt-1", "co-1", "--name", "has space"}, want: "start with a letter"}, + {name: "where invalid column", args: []string{"data-table", "row", "delete", "dt-1", "--where", "bad-col=1", "--yes"}, want: "start with a letter"}, {name: "column create negative index", args: []string{"data-table", "column", "create", "dt-1", "a", "string", "--index", "-1"}, want: "must not be negative"}, {name: "column update without fields", args: []string{"data-table", "column", "update", "dt-1", "co-1"}, want: "--name or --index is required"}, {name: "column delete blank column", args: []string{"data-table", "column", "delete", "dt-1", " ", "--yes"}, want: "column ID is required"}, diff --git a/internal/n8n/datatable.go b/internal/n8n/datatable.go index 5c45785..86f977f 100644 --- a/internal/n8n/datatable.go +++ b/internal/n8n/datatable.go @@ -22,12 +22,23 @@ const maxDataTablePageSize = 250 // maxDataTableNameLength is the documented name limit for a table. const maxDataTableNameLength = 128 -// DataTableColumnTypes are the column types an existing table accepts. +// maxDataTableColumnNameLength is the documented column name limit. +const maxDataTableColumnNameLength = 63 + +// DataTableColumnTypes are the column types table creation and column +// creation accept. Older contracts also listed "json"; the API no longer +// does. var DataTableColumnTypes = []string{"string", "number", "boolean", "date"} -// DataTableCreateColumnTypes are the column types the create-table request -// documents. It adds "json", which some instances reject with a 400. -var DataTableCreateColumnTypes = []string{"string", "number", "boolean", "date", "json"} +// DataTableSortOrders are the sort orders the table list accepts. +var DataTableSortOrders = []string{ + "name:asc", "name:desc", "createdAt:asc", "createdAt:desc", + "updatedAt:asc", "updatedAt:desc", "size:asc", "size:desc", +} + +// dataTableColumnNamePattern is the documented column name shape: a letter, +// then letters, digits and underscores. +var dataTableColumnNamePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*$`) // DataTableRowConditions are the comparison operators of a row filter. var DataTableRowConditions = []string{"eq", "neq", "like", "ilike", "gt", "gte", "lt", "lte"} @@ -46,10 +57,10 @@ const ( // [InsertReturnAll]. var DataTableInsertReturnTypes = []string{InsertReturnCount, InsertReturnID, InsertReturnAll} -// sortByPattern is the documented sort format, field:asc or field:desc. The -// API does not document which fields are sortable, so only the shape is -// checked here and an unknown field comes back as a 400. -var sortByPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*:(asc|desc)$`) +// rowSortByPattern is the row sort format, columnName:asc or columnName:desc. +// Sortable fields are the table's own columns, so only the shape is checked +// here and an unknown column comes back as a 400. +var rowSortByPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*:(asc|desc)$`) // DataTable is one data table with its column definitions. type DataTable struct { @@ -145,7 +156,7 @@ type ListDataTablesOptions struct { ListOptions // Filter narrows the tables returned. The zero value sends no filter. Filter DataTableFilter - // SortBy is "field:asc" or "field:desc", e.g. "name:asc" or "size:desc". + // SortBy is one of [DataTableSortOrders], e.g. "name:asc" or "size:desc". SortBy string } @@ -154,8 +165,8 @@ func (o ListDataTablesOptions) Validate() error { if err := validateDataTablePagination(o.ListOptions); err != nil { return err } - if err := validateSortBy(o.SortBy); err != nil { - return err + if o.SortBy != "" && !slices.Contains(DataTableSortOrders, o.SortBy) { + return fmt.Errorf("unknown data table sort order %q: use one of %s", o.SortBy, strings.Join(DataTableSortOrders, ", ")) } return validateDataTableText("filter name", o.Filter.Name, false) } @@ -184,7 +195,7 @@ type RowCondition struct { // Validate rejects a malformed condition before transport. func (c RowCondition) Validate() error { - if err := validateDataTableText("filter column name", c.ColumnName, true); err != nil { + if err := validateDataTableColumnName("filter column name", c.ColumnName); err != nil { return err } if !slices.Contains(DataTableRowConditions, c.Condition) { @@ -243,7 +254,7 @@ func (o ListRowsOptions) Validate() error { if err := validateDataTablePagination(o.ListOptions); err != nil { return err } - if err := validateSortBy(o.SortBy); err != nil { + if err := validateRowSortBy(o.SortBy); err != nil { return err } if !o.Filter.IsZero() { @@ -295,11 +306,11 @@ func (r CreateDataTableRequest) Validate() error { return fmt.Errorf("a data table needs at least one column") } for i, column := range r.Columns { - if err := validateDataTableText("column name", column.Name, true); err != nil { + if err := validateDataTableColumnName("column name", column.Name); err != nil { return fmt.Errorf("column %d: %w", i+1, err) } - if !slices.Contains(DataTableCreateColumnTypes, column.Type) { - return fmt.Errorf("column %d: unknown column type %q: the API defines %s", i+1, column.Type, strings.Join(DataTableCreateColumnTypes, ", ")) + if err := validateDataTableColumnType(column.Type); err != nil { + return fmt.Errorf("column %d: %w", i+1, err) } } return validateDataTableText("project ID", r.ProjectID, false) @@ -406,11 +417,11 @@ type CreateColumnRequest struct { // Validate rejects a malformed column before transport. func (r CreateColumnRequest) Validate() error { - if err := validateDataTableText("column name", r.Name, true); err != nil { + if err := validateDataTableColumnName("column name", r.Name); err != nil { return err } - if !slices.Contains(DataTableColumnTypes, r.Type) { - return fmt.Errorf("unknown column type %q: this endpoint defines %s", r.Type, strings.Join(DataTableColumnTypes, ", ")) + if err := validateDataTableColumnType(r.Type); err != nil { + return err } if r.Index != nil && *r.Index < 0 { return fmt.Errorf("column index must not be negative, got %d", *r.Index) @@ -430,8 +441,10 @@ func (r UpdateColumnRequest) Validate() error { if r.Name == "" && r.Index == nil { return fmt.Errorf("a column update needs a new name or a new index") } - if err := validateDataTableText("column name", r.Name, false); err != nil { - return err + if r.Name != "" { + if err := validateDataTableColumnName("column name", r.Name); err != nil { + return err + } } if r.Index != nil && *r.Index < 0 { return fmt.Errorf("column index must not be negative, got %d", *r.Index) @@ -814,12 +827,37 @@ func validateDataTablePagination(opts ListOptions) error { return nil } -func validateSortBy(sortBy string) error { +func validateRowSortBy(sortBy string) error { if sortBy == "" { return nil } - if !sortByPattern.MatchString(sortBy) { - return fmt.Errorf("sort order %q is not field:asc or field:desc", sortBy) + if !rowSortByPattern.MatchString(sortBy) { + return fmt.Errorf("sort order %q is not columnName:asc or columnName:desc", sortBy) + } + return nil +} + +// validateDataTableColumnType rejects a type outside the contract, naming +// json specifically because older contracts and CLI versions offered it. +func validateDataTableColumnType(columnType string) error { + if columnType == "json" { + return fmt.Errorf("json columns are no longer supported by the n8n API; use string and store the JSON as text") + } + if !slices.Contains(DataTableColumnTypes, columnType) { + return fmt.Errorf("unknown column type %q: the API defines %s", columnType, strings.Join(DataTableColumnTypes, ", ")) + } + return nil +} + +func validateDataTableColumnName(field, name string) error { + if err := validateDataTableText(field, name, true); err != nil { + return err + } + if len(name) > maxDataTableColumnNameLength { + return fmt.Errorf("data table %s %q is %d characters; the API accepts at most %d", field, name, len(name), maxDataTableColumnNameLength) + } + if !dataTableColumnNamePattern.MatchString(name) { + return fmt.Errorf("data table %s %q is invalid: start with a letter, then use only letters, digits and underscores", field, name) } return nil } diff --git a/internal/n8n/datatable_test.go b/internal/n8n/datatable_test.go index 5b4ed6f..8ed9f48 100644 --- a/internal/n8n/datatable_test.go +++ b/internal/n8n/datatable_test.go @@ -502,6 +502,26 @@ func TestDataTableValidationBeforeRequest(t *testing.T) { _, err := client.ListDataTables(ctx, ListDataTablesOptions{SortBy: "name"}) return err }, + "unsortable field": func() error { + _, err := client.ListDataTables(ctx, ListDataTablesOptions{SortBy: "projectId:asc"}) + return err + }, + "create json column": func() error { + _, err := client.CreateDataTable(ctx, CreateDataTableRequest{Name: "t", Columns: []DataTableColumnDefinition{{Name: "meta", Type: "json"}}}) + return err + }, + "create invalid column name": func() error { + _, err := client.CreateDataTable(ctx, CreateDataTableRequest{Name: "t", Columns: []DataTableColumnDefinition{{Name: "_meta", Type: "string"}}}) + return err + }, + "create long column name": func() error { + _, err := client.CreateDataTable(ctx, CreateDataTableRequest{Name: "t", Columns: []DataTableColumnDefinition{{Name: strings.Repeat("a", 64), Type: "string"}}}) + return err + }, + "filter invalid column name": func() error { + _, err := client.ListDataTableRows(ctx, "dt-1", ListRowsOptions{Filter: RowFilter{Filters: []RowCondition{{ColumnName: "a b", Condition: "eq", Value: json.RawMessage(`1`)}}}}) + return err + }, "blank create name": func() error { _, err := client.CreateDataTable(ctx, CreateDataTableRequest{Name: " ", Columns: []DataTableColumnDefinition{{Name: "a", Type: "string"}}}) return err @@ -576,10 +596,14 @@ func TestDataTableValidationBeforeRequest(t *testing.T) { _, err := client.ClearDataTableRows(ctx, "") return err }, - "column create unknown type": func() error { + "column create json type": func() error { _, err := client.CreateDataTableColumn(ctx, "dt-1", CreateColumnRequest{Name: "a", Type: "json"}) return err }, + "column rename invalid": func() error { + _, err := client.UpdateDataTableColumn(ctx, "dt-1", "co-1", UpdateColumnRequest{Name: "9lives"}) + return err + }, "column create negative index": func() error { _, err := client.CreateDataTableColumn(ctx, "dt-1", CreateColumnRequest{Name: "a", Type: "string", Index: intPtr(-1)}) return err From 9a59ccdab2d60491466f36f8d8457dbbe3c37c61 Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 23:57:10 -0500 Subject: [PATCH 6/7] fix(project,variable): keep full project read model, add create fields - Project gains icon, description, customTelemetryTags, creatorId, timestamps, and the role/scopes create returns, plus Extra for unknown fields; nullable fields keep absent vs null. VariableProject and folder homeProject share it. - project create sends --id, --description, --icon TYPE:VALUE, --icon-color and --telemetry-tag KEY=VALUE; CreateProject takes a CreateProjectRequest. Name (255), ID (36), description (512) validated. - variable key/value/projectId limits validated locally (create key may not start with a digit; update allows it). Update help no longer claims omitting --project-id moves the variable to global scope: the contract does not say. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/n8n_project_create.md | 35 ++++--- docs/n8n_variable_create.md | 11 ++- docs/n8n_variable_update.md | 15 +-- internal/cli/project.go | 85 ++++++++++++++--- internal/cli/project_test.go | 31 +++++++ internal/cli/variable.go | 24 +++-- internal/cli/variable_test.go | 3 + internal/n8n/extra.go | 60 ++++++++++++ internal/n8n/extra_test.go | 39 ++++++++ internal/n8n/project.go | 154 ++++++++++++++++++++++++++++--- internal/n8n/project_test.go | 71 +++++++++++++- internal/n8n/variable.go | 66 ++++++++++--- internal/n8n/variable_test.go | 51 ++++++++++ test/integration/project_test.go | 2 +- 14 files changed, 569 insertions(+), 78 deletions(-) create mode 100644 internal/n8n/extra.go create mode 100644 internal/n8n/extra_test.go diff --git a/docs/n8n_project_create.md b/docs/n8n_project_create.md index 255695c..f9034cf 100644 --- a/docs/n8n_project_create.md +++ b/docs/n8n_project_create.md @@ -4,13 +4,17 @@ Create a project ### Synopsis -Create one project with the given name. Name is the only writable field; the ID -and type are assigned by the instance. - -The API contract declares no response body for this call, so an instance that -returns none is reported as created without an ID; run 'n8n project list' to -recover it. Quote names containing spaces. Add members afterwards with -'n8n project user add'. Requires project:create and a licensed instance. +Create one team project with the given name, at most 255 characters. The +instance assigns the ID unless --id picks one (at most 36 characters; an ID +already in use is a 409). --description, --icon and --telemetry-tag set the +optional fields; after creation only the name can be changed, with +'n8n project update'. + +The output is the created project, including the caller's role and scopes in +it. Older instances answer with no body; that is reported as created without +an ID, and 'n8n project list' recovers it. Quote names containing spaces. Add +members afterwards with 'n8n project user add'. Requires project:create and a +licensed instance. ``` n8n project create [flags] @@ -20,16 +24,23 @@ n8n project create [flags] ``` n8n project create "Billing automation" - n8n project create Staging --output json + n8n project create Marketing --description "Workflows the marketing team owns" --icon emoji:📣 + n8n project create Ops --icon icon:server --icon-color "#ff6d5a" --telemetry-tag team=ops + n8n project create Staging --id staging --output json ``` ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - -h, --help help for create - --output string output format: text or json (JSON is the project object) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --description string plain-text description, at most 512 characters (default: none) + -h, --help help for create + --icon string icon as emoji:EMOJI or icon:NAME, e.g. emoji:📣 or icon:server (default: none) + --icon-color string icon color, e.g. #ff6d5a; requires --icon (default: the instance's color) + --id string project ID to use, at most 36 characters (default: generated by the instance) + --output string output format: text or json (JSON is the project object) (default "text") + --telemetry-tag stringArray custom telemetry tag as KEY=VALUE, repeatable (default: none) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) ``` ### SEE ALSO diff --git a/docs/n8n_variable_create.md b/docs/n8n_variable_create.md index 63be5f0..20639d9 100644 --- a/docs/n8n_variable_create.md +++ b/docs/n8n_variable_create.md @@ -6,11 +6,12 @@ Create a variable Create one variable with a complete key and value. Omit --project-id for a global variable, or pass a project ID for project scope. A key must be unique -within that scope; a duplicate fails with a conflict. +within that scope; a duplicate fails with a conflict. Keys start with a letter +or underscore, then use letters, digits and underscores, at most 50 in all. ---value is required, though an explicitly empty value is valid. The submitted -value is sent to n8n but never repeated in CLI diagnostics or acknowledgement -output. Requires variable:create. +--value is required, though an explicitly empty value is valid; it is at most +1000 characters. The submitted value is sent to n8n but never repeated in CLI +diagnostics or acknowledgement output. Requires variable:create. ``` n8n variable create [flags] @@ -30,7 +31,7 @@ n8n variable create [flags] --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') -h, --help help for create --output string output format: text or json (acknowledgement excludes the submitted value) (default "text") - --project-id string project scope ID (default: global scope; on update this replaces current scope) + --project-id string project scope ID, at most 36 characters (default: global scope on create; on update see the command help) --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) --value string complete variable value; pass an empty string to store an empty value (required, not repeated in diagnostics) ``` diff --git a/docs/n8n_variable_update.md b/docs/n8n_variable_update.md index 5925b5d..529af59 100644 --- a/docs/n8n_variable_update.md +++ b/docs/n8n_variable_update.md @@ -5,12 +5,15 @@ Fully replace a variable ### Synopsis Fully replace one variable by ID. This is a PUT, so --key and --value are both -required even when one is unchanged. Omitting --project-id replaces the current -scope with global scope; pass its project ID to keep or select project scope. +required even when one is unchanged. The API contract makes projectId optional +and nullable here without saying what omitting it does to the current scope, +so pass --project-id to keep or select project scope, and check the result +with 'n8n variable list'. -A key already used in the resulting scope fails with a conflict. An explicitly -empty value is valid. Submitted values never appear in diagnostics or success -acknowledgements. Requires variable:update. +Keys use letters, digits and underscores, at most 50; values are at most 1000 +characters. A key already used in the resulting scope fails with a conflict. +An explicitly empty value is valid. Submitted values never appear in +diagnostics or success acknowledgements. Requires variable:update. ``` n8n variable update [flags] @@ -31,7 +34,7 @@ n8n variable update [flags] -h, --help help for update --key string complete replacement key (required, even when unchanged) --output string output format: text or json (acknowledgement excludes the submitted value) (default "text") - --project-id string project scope ID (default: global scope; on update this replaces current scope) + --project-id string project scope ID, at most 36 characters (default: global scope on create; on update see the command help) --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) --value string complete variable value; pass an empty string to store an empty value (required, not repeated in diagnostics) ``` diff --git a/internal/cli/project.go b/internal/cli/project.go index 04b3c11..f0e78b4 100644 --- a/internal/cli/project.go +++ b/internal/cli/project.go @@ -164,47 +164,93 @@ func (f *projectWriteFlags) register(cmd *cobra.Command) { cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the project object)") } +type projectCreateFlags struct { + write projectWriteFlags + id string + description string + icon string + iconColor string + telemetryTags []string +} + func newProjectCreateCommand(opts Options) *cobra.Command { - var f projectWriteFlags + var f projectCreateFlags cmd := &cobra.Command{ Use: "create ", Short: "Create a project", - Long: "Create one project with the given name. Name is the only writable field; the ID\n" + - "and type are assigned by the instance.\n\n" + - "The API contract declares no response body for this call, so an instance that\n" + - "returns none is reported as created without an ID; run 'n8n project list' to\n" + - "recover it. Quote names containing spaces. Add members afterwards with\n" + - "'n8n project user add'. Requires project:create and a licensed instance.", + Long: "Create one team project with the given name, at most 255 characters. The\n" + + "instance assigns the ID unless --id picks one (at most 36 characters; an ID\n" + + "already in use is a 409). --description, --icon and --telemetry-tag set the\n" + + "optional fields; after creation only the name can be changed, with\n" + + "'n8n project update'.\n\n" + + "The output is the created project, including the caller's role and scopes in\n" + + "it. Older instances answer with no body; that is reported as created without\n" + + "an ID, and 'n8n project list' recovers it. Quote names containing spaces. Add\n" + + "members afterwards with 'n8n project user add'. Requires project:create and a\n" + + "licensed instance.", Example: " n8n project create \"Billing automation\"\n" + - " n8n project create Staging --output json", + " n8n project create Marketing --description \"Workflows the marketing team owns\" --icon emoji:📣\n" + + " n8n project create Ops --icon icon:server --icon-color \"#ff6d5a\" --telemetry-tag team=ops\n" + + " n8n project create Staging --id staging --output json", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return runProjectCreate(cmd.Context(), opts, args[0], f) }, } - f.register(cmd) + f.write.register(cmd) + cmd.Flags().StringVar(&f.id, "id", "", "project ID to use, at most 36 characters (default: generated by the instance)") + cmd.Flags().StringVar(&f.description, "description", "", "plain-text description, at most 512 characters (default: none)") + cmd.Flags().StringVar(&f.icon, "icon", "", "icon as emoji:EMOJI or icon:NAME, e.g. emoji:📣 or icon:server (default: none)") + cmd.Flags().StringVar(&f.iconColor, "icon-color", "", "icon color, e.g. #ff6d5a; requires --icon (default: the instance's color)") + cmd.Flags().StringArrayVar(&f.telemetryTags, "telemetry-tag", nil, "custom telemetry tag as KEY=VALUE, repeatable (default: none)") return cmd } -func runProjectCreate(ctx context.Context, opts Options, name string, f projectWriteFlags) error { - if err := validateOutput(f.output); err != nil { +func runProjectCreate(ctx context.Context, opts Options, name string, f projectCreateFlags) error { + if err := validateOutput(f.write.output); err != nil { return err } - if err := validateProjectName(name); err != nil { + request, err := projectCreateRequest(name, f) + if err != nil { return err } - client, resolution, err := opts.apiClient(f.instance) + if err := request.Validate(); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.write.instance) if err != nil { return err } - project, err := client.CreateProject(ctx, name) + project, err := client.CreateProject(ctx, request) if err != nil { return projectAPIError(err, resolution, "create") } if project.Name == "" { project.Name = name } - return writeProjectResult(opts, resolution, "Created", project, f.output) + return writeProjectResult(opts, resolution, "Created", project, f.write.output) +} + +// projectCreateRequest builds the create document from the flags. +func projectCreateRequest(name string, f projectCreateFlags) (n8n.CreateProjectRequest, error) { + request := n8n.CreateProjectRequest{Name: name, ID: f.id, Description: f.description} + if f.icon != "" { + iconType, value, ok := strings.Cut(f.icon, ":") + if !ok || value == "" { + return request, fmt.Errorf("--icon %q is not TYPE:VALUE: use emoji:EMOJI or icon:NAME, e.g. emoji:📣", f.icon) + } + request.Icon = &n8n.ProjectIcon{Type: iconType, Value: value, Color: f.iconColor} + } else if f.iconColor != "" { + return request, fmt.Errorf("--icon-color needs --icon: the color applies to an icon") + } + for _, tag := range f.telemetryTags { + key, value, ok := strings.Cut(tag, "=") + if !ok { + return request, fmt.Errorf("--telemetry-tag %q is not KEY=VALUE", tag) + } + request.CustomTelemetryTags = append(request.CustomTelemetryTags, n8n.ProjectTelemetryTag{Key: key, Value: value}) + } + return request, nil } type projectUpdateFlags struct { @@ -679,6 +725,15 @@ func writeProjectResult(opts Options, resolution config.Resolution, action strin if project.Type != "" { fmt.Fprintf(tw, "Type:\t%s\n", project.Type) } + if project.Description.Set && project.Description.Value != "" { + fmt.Fprintf(tw, "Description:\t%s\n", project.Description.Value) + } + if project.Icon.Set && !project.Icon.Null { + fmt.Fprintf(tw, "Icon:\t%s:%s\n", project.Icon.Value.Type, project.Icon.Value.Value) + } + if project.Role != "" { + fmt.Fprintf(tw, "Your role:\t%s\n", project.Role) + } fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) if err := tw.Flush(); err != nil { return err diff --git a/internal/cli/project_test.go b/internal/cli/project_test.go index 6f332b6..f147a28 100644 --- a/internal/cli/project_test.go +++ b/internal/cli/project_test.go @@ -168,6 +168,32 @@ func TestProjectCreateUpdateAndDelete(t *testing.T) { }) } +func TestProjectCreateOptionalFields(t *testing.T) { + f := projectFixture(t, `{"id":"ops","name":"Ops","type":"team","icon":{"type":"icon","value":"server","color":"#ff6d5a"},`+ + `"description":"Runbooks","customTelemetryTags":[{"key":"team","value":"ops"}],"creatorId":"us-1",`+ + `"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z","role":"project:admin","scopes":["project:read"]}`) + got := f.run("project", "create", "Ops", "--id", "ops", "--description", "Runbooks", "--icon", "icon:server", + "--icon-color", "#ff6d5a", "--telemetry-tag", "team=ops", "--telemetry-tag", "tier=") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + assertCLIJSON(t, `{"name":"Ops","id":"ops","icon":{"type":"icon","value":"server","color":"#ff6d5a"},"description":"Runbooks",`+ + `"customTelemetryTags":[{"key":"team","value":"ops"},{"key":"tier","value":""}]}`, f.lastBody()) + for _, want := range []string{"Created:", "Ops", "Description:", "Runbooks", "Icon:", "icon:server", "Your role:", "project:admin"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + + got = f.run("project", "create", "Ops", "--output", "json") + for _, want := range []string{`"scopes": [`, `"creatorId": "us-1"`, `"customTelemetryTags": [`} { + if !strings.Contains(got.stdout, want) { + t.Errorf("JSON missing %q:\n%s", want, got.stdout) + } + } + assertCLIJSON(t, `{"name":"Ops"}`, f.lastBody()) +} + func TestProjectUserListTextAndJSON(t *testing.T) { f := projectFixture(t, `{"data":[`+cliProjectMember+`],"nextCursor":"next"}`) got := f.run("project", "user", "list", "pr/one?x=1", "--limit", "10") @@ -289,6 +315,11 @@ func TestProjectValidationBeforeRequest(t *testing.T) { {name: "large limit", args: []string{"project", "list", "--limit", "251"}, want: "must not exceed 250"}, {name: "unknown output", args: []string{"project", "list", "--output", "yaml"}, want: "unknown output format"}, {name: "blank create name", args: []string{"project", "create", " "}, want: "project name is required"}, + {name: "malformed icon", args: []string{"project", "create", "Ops", "--icon", "rocket"}, want: "TYPE:VALUE"}, + {name: "unknown icon type", args: []string{"project", "create", "Ops", "--icon", "image:x"}, want: "use emoji or icon"}, + {name: "icon color without icon", args: []string{"project", "create", "Ops", "--icon-color", "#fff"}, want: "--icon-color needs --icon"}, + {name: "malformed telemetry tag", args: []string{"project", "create", "Ops", "--telemetry-tag", "team"}, want: "KEY=VALUE"}, + {name: "long description", args: []string{"project", "create", "Ops", "--description", strings.Repeat("d", 513)}, want: "at most 512"}, {name: "missing update name", args: []string{"project", "update", "pr-1"}, want: "--name is required"}, {name: "padded update name", args: []string{"project", "update", "pr-1", "--name", " Billing"}, want: "whitespace"}, {name: "padded delete ID", args: []string{"project", "delete", " pr-1", "--yes"}, want: "whitespace"}, diff --git a/internal/cli/variable.go b/internal/cli/variable.go index fd18e62..cbc9a1a 100644 --- a/internal/cli/variable.go +++ b/internal/cli/variable.go @@ -166,7 +166,7 @@ type variableWriteFlags struct { func (f *variableWriteFlags) register(cmd *cobra.Command) { f.instance.register(cmd) cmd.Flags().StringVar(&f.value, "value", "", "complete variable value; pass an empty string to store an empty value (required, not repeated in diagnostics)") - cmd.Flags().StringVar(&f.projectID, "project-id", "", "project scope ID (default: global scope; on update this replaces current scope)") + cmd.Flags().StringVar(&f.projectID, "project-id", "", "project scope ID, at most 36 characters (default: global scope on create; on update see the command help)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (acknowledgement excludes the submitted value)") } @@ -177,10 +177,11 @@ func newVariableCreateCommand(opts Options) *cobra.Command { Short: "Create a variable", Long: "Create one variable with a complete key and value. Omit --project-id for a\n" + "global variable, or pass a project ID for project scope. A key must be unique\n" + - "within that scope; a duplicate fails with a conflict.\n\n" + - "--value is required, though an explicitly empty value is valid. The submitted\n" + - "value is sent to n8n but never repeated in CLI diagnostics or acknowledgement\n" + - "output. Requires variable:create.", + "within that scope; a duplicate fails with a conflict. Keys start with a letter\n" + + "or underscore, then use letters, digits and underscores, at most 50 in all.\n\n" + + "--value is required, though an explicitly empty value is valid; it is at most\n" + + "1000 characters. The submitted value is sent to n8n but never repeated in CLI\n" + + "diagnostics or acknowledgement output. Requires variable:create.", Example: " n8n variable create API_HOST --value https://api.example.com\n" + " n8n variable create OPTIONAL_VALUE --value \"\"\n" + " n8n variable create API_HOST --value https://api.example.com --project-id PROJECT_ID --output json", @@ -219,11 +220,14 @@ func newVariableUpdateCommand(opts Options) *cobra.Command { Use: "update ", Short: "Fully replace a variable", Long: "Fully replace one variable by ID. This is a PUT, so --key and --value are both\n" + - "required even when one is unchanged. Omitting --project-id replaces the current\n" + - "scope with global scope; pass its project ID to keep or select project scope.\n\n" + - "A key already used in the resulting scope fails with a conflict. An explicitly\n" + - "empty value is valid. Submitted values never appear in diagnostics or success\n" + - "acknowledgements. Requires variable:update.", + "required even when one is unchanged. The API contract makes projectId optional\n" + + "and nullable here without saying what omitting it does to the current scope,\n" + + "so pass --project-id to keep or select project scope, and check the result\n" + + "with 'n8n variable list'.\n\n" + + "Keys use letters, digits and underscores, at most 50; values are at most 1000\n" + + "characters. A key already used in the resulting scope fails with a conflict.\n" + + "An explicitly empty value is valid. Submitted values never appear in\n" + + "diagnostics or success acknowledgements. Requires variable:update.", Example: " n8n variable update VARIABLE_ID --key API_HOST --value https://api.internal\n" + " n8n variable update VARIABLE_ID --key API_HOST --value \"\" --project-id PROJECT_ID\n" + " n8n variable update VARIABLE_ID --key API_HOST --value VALUE --output json", diff --git a/internal/cli/variable_test.go b/internal/cli/variable_test.go index 0d9d468..321ba42 100644 --- a/internal/cli/variable_test.go +++ b/internal/cli/variable_test.go @@ -246,6 +246,9 @@ func TestVariableValidationBeforeRequest(t *testing.T) { {name: "missing update value", args: []string{"variable", "update", "id", "--key", "KEY"}, want: "--value is required"}, {name: "blank delete ID", args: []string{"variable", "delete", " ", "--yes"}, want: "variable ID is required"}, {name: "missing create argument", args: []string{"variable", "create", "--value", "value"}, want: "accepts 1 arg"}, + {name: "create key with leading digit", args: []string{"variable", "create", "1KEY", "--value", "value"}, want: "start with a letter or underscore"}, + {name: "update key with dash", args: []string{"variable", "update", "id", "--key", "API-HOST", "--value", "value"}, want: "only letters, digits and underscores"}, + {name: "long value", args: []string{"variable", "create", "KEY", "--value", strings.Repeat("v", 1001)}, want: "at most 1000"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/n8n/extra.go b/internal/n8n/extra.go new file mode 100644 index 0000000..d5750e0 --- /dev/null +++ b/internal/n8n/extra.go @@ -0,0 +1,60 @@ +package n8n + +import ( + "bytes" + "encoding/json" + "maps" + "slices" +) + +// unknownFields returns the top-level fields of a JSON object that are not in +// known, or nil when there are none. Read models keep them in an Extra map so +// `--output json` does not lose what a newer instance sends. +func unknownFields(data []byte, known []string) (map[string]json.RawMessage, error) { + var rest map[string]json.RawMessage + if err := json.Unmarshal(data, &rest); err != nil { + return nil, err + } + for _, name := range known { + delete(rest, name) + } + if len(rest) == 0 { + return nil, nil + } + return rest, nil +} + +// appendExtra writes extra into the encoded object base, after its own +// fields and in sorted key order, so output is deterministic. Keys base +// already holds are skipped: the named field wins. +func appendExtra(base []byte, extra map[string]json.RawMessage) ([]byte, error) { + if len(extra) == 0 { + return base, nil + } + var named map[string]json.RawMessage + if err := json.Unmarshal(base, &named); err != nil { + return nil, err + } + var b bytes.Buffer + b.Grow(len(base) + len(extra)*32) + b.Write(bytes.TrimSuffix(bytes.TrimSpace(base), []byte("}"))) + first := len(named) == 0 + for _, name := range slices.Sorted(maps.Keys(extra)) { + if _, ok := named[name]; ok { + continue + } + if !first { + b.WriteByte(',') + } + first = false + key, err := json.Marshal(name) + if err != nil { + return nil, err + } + b.Write(key) + b.WriteByte(':') + b.Write(extra[name]) + } + b.WriteByte('}') + return b.Bytes(), nil +} diff --git a/internal/n8n/extra_test.go b/internal/n8n/extra_test.go new file mode 100644 index 0000000..25383fd --- /dev/null +++ b/internal/n8n/extra_test.go @@ -0,0 +1,39 @@ +package n8n + +import ( + "encoding/json" + "testing" +) + +func TestAppendExtra(t *testing.T) { + for name, tt := range map[string]struct { + base string + extra map[string]json.RawMessage + want string + }{ + "no extra": {base: `{"a":1}`, want: `{"a":1}`}, + "empty base": {base: `{}`, extra: map[string]json.RawMessage{"b": json.RawMessage(`2`)}, want: `{"b":2}`}, + "sorted after": {base: `{"a":1}`, extra: map[string]json.RawMessage{"c": json.RawMessage(`3`), "b": json.RawMessage(`2`)}, want: `{"a":1,"b":2,"c":3}`}, + "named field wins": {base: `{"a":1}`, extra: map[string]json.RawMessage{"a": json.RawMessage(`9`)}, want: `{"a":1}`}, + } { + t.Run(name, func(t *testing.T) { + got, err := appendExtra([]byte(tt.base), tt.extra) + if err != nil || string(got) != tt.want { + t.Errorf("appendExtra = %s (error: %v), want %s", got, err, tt.want) + } + if !json.Valid(got) { + t.Errorf("appendExtra produced invalid JSON: %s", got) + } + }) + } +} + +func TestUnknownFields(t *testing.T) { + rest, err := unknownFields([]byte(`{"a":1,"b":2}`), []string{"a"}) + if err != nil || len(rest) != 1 || string(rest["b"]) != "2" { + t.Errorf("unknownFields = %v (error: %v)", rest, err) + } + if rest, err := unknownFields([]byte(`{"a":1}`), []string{"a"}); err != nil || rest != nil { + t.Errorf("unknownFields = %v (error: %v), want nil", rest, err) + } +} diff --git a/internal/n8n/project.go b/internal/n8n/project.go index c09c4dc..5e4fc43 100644 --- a/internal/n8n/project.go +++ b/internal/n8n/project.go @@ -2,9 +2,11 @@ package n8n import ( "context" + "encoding/json" "fmt" "net/http" "strings" + "unicode/utf8" ) // ProjectsPath is the collection endpoint for projects. @@ -13,16 +15,132 @@ const ProjectsPath = "/projects" // maxProjectPageSize is the page size the API documents as its maximum. const maxProjectPageSize = 250 -// Project is one n8n project. Name is the only writable field: the API marks -// id and type read-only and rejects any other property. +// Project is one n8n project as the API returns it. Icon, description and +// creatorId are nullable on read, so they keep the difference between absent +// and null. Fields this type does not name are kept in Extra and written back +// out, so `--output json` does not lose what a newer instance sends. type Project struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type,omitempty"` + ID string `json:"id,omitempty"` + Name string `json:"name"` + Type string `json:"type,omitempty"` + Icon Nullable[ProjectIcon] `json:"icon,omitzero"` + Description Nullable[string] `json:"description,omitzero"` + CustomTelemetryTags []ProjectTelemetryTag `json:"customTelemetryTags,omitzero"` + CreatorID Nullable[string] `json:"creatorId,omitzero"` + CreatedAt string `json:"createdAt,omitempty"` + UpdatedAt string `json:"updatedAt,omitempty"` + // Role and Scopes are the caller's, returned by create only. + Role string `json:"role,omitempty"` + Scopes []string `json:"scopes,omitzero"` + + Extra map[string]json.RawMessage `json:"-"` +} + +// projectFields are the field names [Project] decodes itself. +var projectFields = []string{ + "id", "name", "type", "icon", "description", "customTelemetryTags", + "creatorId", "createdAt", "updatedAt", "role", "scopes", +} + +// UnmarshalJSON decodes the named fields and keeps the rest in Extra. +func (p *Project) UnmarshalJSON(data []byte) error { + type plain Project + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + rest, err := unknownFields(data, projectFields) + if err != nil { + return err + } + *p = Project(decoded) + p.Extra = rest + return nil +} + +// MarshalJSON writes the named fields followed by Extra in sorted order. +func (p Project) MarshalJSON() ([]byte, error) { + type plain Project + base, err := json.Marshal(plain(p)) + if err != nil { + return nil, err + } + return appendExtra(base, p.Extra) +} + +// Project icon types. +const ( + ProjectIconEmoji = "emoji" + ProjectIconIcon = "icon" +) + +// ProjectIcon is a project's icon: an emoji or a named icon, with an optional +// color. +type ProjectIcon struct { + Type string `json:"type"` + Value string `json:"value"` + Color string `json:"color,omitempty"` +} + +// ProjectTelemetryTag is one key/value pair attached to a project's +// telemetry. +type ProjectTelemetryTag struct { + Key string `json:"key"` + Value string `json:"value"` +} + +// Project field limits from the contract. +const ( + MaxProjectName = 255 + MaxProjectID = 36 + MaxProjectDescription = 512 +) + +// CreateProjectRequest is the write document for POST /projects. Only Name +// is required; the instance generates the ID when it is empty. It is separate +// from [Project] so read-only fields are never sent. +type CreateProjectRequest struct { + Name string `json:"name"` + ID string `json:"id,omitempty"` + Icon *ProjectIcon `json:"icon,omitempty"` + Description string `json:"description,omitempty"` + CustomTelemetryTags []ProjectTelemetryTag `json:"customTelemetryTags,omitempty"` } -// projectRequest is the write document for create and update. It is separate -// from [Project] so read-only fields are never sent back to the server. +// Validate rejects a creation the API would reject. +func (r CreateProjectRequest) Validate() error { + if err := validateProjectName(r.Name); err != nil { + return err + } + if r.ID != "" { + if err := validateProjectText("ID", r.ID, true); err != nil { + return err + } + if n := utf8.RuneCountInString(r.ID); n > MaxProjectID { + return fmt.Errorf("project ID is %d characters; the API accepts at most %d", n, MaxProjectID) + } + } + if r.Icon != nil { + if r.Icon.Type != ProjectIconEmoji && r.Icon.Type != ProjectIconIcon { + return fmt.Errorf("project icon type %q is invalid: use %s or %s", r.Icon.Type, ProjectIconEmoji, ProjectIconIcon) + } + if r.Icon.Value == "" { + return fmt.Errorf("project icon value is required") + } + } + if n := utf8.RuneCountInString(r.Description); n > MaxProjectDescription { + return fmt.Errorf("project description is %d characters; the API accepts at most %d", n, MaxProjectDescription) + } + for i, tag := range r.CustomTelemetryTags { + if strings.TrimSpace(tag.Key) == "" { + return fmt.Errorf("telemetry tag %d has an empty key", i+1) + } + } + return nil +} + +// projectRequest is the write document for update, whose only writable field +// is the name. type projectRequest struct { Name string `json:"name"` } @@ -66,18 +184,18 @@ func (c *Client) ListProjects(ctx context.Context, opts ListOptions) (Page[Proje return page, nil } -// CreateProject creates a project. The contract declares a 201 with no -// documented body, so the returned project carries whatever the instance sent -// and may be empty; list the projects to recover the ID in that case. -func (c *Client) CreateProject(ctx context.Context, name string) (*Project, error) { - if err := validateProjectName(name); err != nil { +// CreateProject creates a team project and returns it with the caller's role +// and scopes in it. Older instances answered 201 with no body, so the +// returned project may be empty; list the projects to recover the ID then. +func (c *Client) CreateProject(ctx context.Context, request CreateProjectRequest) (*Project, error) { + if err := request.Validate(); err != nil { return nil, err } var created Project if _, err := c.Do(ctx, Request{ Method: http.MethodPost, Path: ProjectsPath, - Body: projectRequest{Name: name}, + Body: request, }, &created); err != nil { return nil, err } @@ -206,7 +324,15 @@ func validateProjectListOptions(opts ListOptions) error { func validateProjectID(id string) error { return validateProjectText("ID", id, true) } -func validateProjectName(name string) error { return validateProjectText("name", name, true) } +func validateProjectName(name string) error { + if err := validateProjectText("name", name, true); err != nil { + return err + } + if n := utf8.RuneCountInString(name); n > MaxProjectName { + return fmt.Errorf("project name is %d characters; the API accepts at most %d", n, MaxProjectName) + } + return nil +} func validateProjectText(field, value string, required bool) error { if required && strings.TrimSpace(value) == "" { diff --git a/internal/n8n/project_test.go b/internal/n8n/project_test.go index af55954..e28fb54 100644 --- a/internal/n8n/project_test.go +++ b/internal/n8n/project_test.go @@ -2,6 +2,7 @@ package n8n import ( "context" + "encoding/json" "net/http" "strings" "testing" @@ -62,7 +63,7 @@ func TestListProjectsDefaultQuery(t *testing.T) { func TestCreateProjectSendsNameAndToleratesEmptyBody(t *testing.T) { t.Run("body returned", func(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusCreated, projectResponse)) - project, err := server.client(t).CreateProject(context.Background(), "Billing automation") + project, err := server.client(t).CreateProject(context.Background(), CreateProjectRequest{Name: "Billing automation"}) if err != nil { t.Fatalf("CreateProject: %v", err) } @@ -80,7 +81,7 @@ func TestCreateProjectSendsNameAndToleratesEmptyBody(t *testing.T) { server := newCommunityPackageServer(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusCreated) }) - project, err := server.client(t).CreateProject(context.Background(), "Billing automation") + project, err := server.client(t).CreateProject(context.Background(), CreateProjectRequest{Name: "Billing automation"}) if err != nil { t.Fatalf("CreateProject: %v", err) } @@ -90,6 +91,46 @@ func TestCreateProjectSendsNameAndToleratesEmptyBody(t *testing.T) { }) } +const fullProjectResponse = `{ + "id":"pr-1", + "name":"Marketing", + "type":"team", + "icon":{"type":"emoji","value":"📣"}, + "description":null, + "customTelemetryTags":[], + "creatorId":"us-1", + "createdAt":"2026-01-01T00:00:00.000Z", + "updatedAt":"2026-01-02T00:00:00.000Z", + "role":"project:admin", + "scopes":["project:read","project:update"], + "fieldAddedLater":{"keep":"me"} +}` + +func TestCreateProjectSendsOptionalFieldsAndKeepsReadFields(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusCreated, fullProjectResponse)) + project, err := server.client(t).CreateProject(context.Background(), CreateProjectRequest{ + Name: "Marketing", + ID: "marketing", + Icon: &ProjectIcon{Type: ProjectIconEmoji, Value: "📣", Color: "#ff6d5a"}, + Description: "Workflows the marketing team owns.", + CustomTelemetryTags: []ProjectTelemetryTag{{Key: "team", Value: "growth"}}, + }) + if err != nil { + t.Fatalf("CreateProject: %v", err) + } + _, body := server.last(t) + assertJSONEqual(t, `{"name":"Marketing","id":"marketing","icon":{"type":"emoji","value":"📣","color":"#ff6d5a"},`+ + `"description":"Workflows the marketing team owns.","customTelemetryTags":[{"key":"team","value":"growth"}]}`, body) + if project.Icon.Value.Value != "📣" || !project.Description.Null || project.CreatorID.Value != "us-1" || project.Role != "project:admin" || len(project.Scopes) != 2 { + t.Errorf("project = %+v", project) + } + encoded, err := json.Marshal(project) + if err != nil { + t.Fatalf("encode: %v", err) + } + assertJSONEqual(t, fullProjectResponse, string(encoded)) +} + func TestProjectAndMemberRequests(t *testing.T) { projectID := "pr/one?x=1" userID := "us/two?y=2" @@ -205,7 +246,31 @@ func TestProjectValidationBeforeRequest(t *testing.T) { return err }, "blank create name": func() error { - _, err := client.CreateProject(context.Background(), " ") + _, err := client.CreateProject(context.Background(), CreateProjectRequest{Name: " "}) + return err + }, + "long create name": func() error { + _, err := client.CreateProject(context.Background(), CreateProjectRequest{Name: strings.Repeat("n", 256)}) + return err + }, + "long create ID": func() error { + _, err := client.CreateProject(context.Background(), CreateProjectRequest{Name: "n", ID: strings.Repeat("i", 37)}) + return err + }, + "unknown icon type": func() error { + _, err := client.CreateProject(context.Background(), CreateProjectRequest{Name: "n", Icon: &ProjectIcon{Type: "image", Value: "x"}}) + return err + }, + "empty icon value": func() error { + _, err := client.CreateProject(context.Background(), CreateProjectRequest{Name: "n", Icon: &ProjectIcon{Type: "emoji"}}) + return err + }, + "long description": func() error { + _, err := client.CreateProject(context.Background(), CreateProjectRequest{Name: "n", Description: strings.Repeat("d", 513)}) + return err + }, + "empty telemetry key": func() error { + _, err := client.CreateProject(context.Background(), CreateProjectRequest{Name: "n", CustomTelemetryTags: []ProjectTelemetryTag{{Value: "v"}}}) return err }, "padded update name": func() error { diff --git a/internal/n8n/variable.go b/internal/n8n/variable.go index d96fead..9cd6019 100644 --- a/internal/n8n/variable.go +++ b/internal/n8n/variable.go @@ -6,7 +6,9 @@ import ( "fmt" "net/http" "net/url" + "regexp" "strings" + "unicode/utf8" ) // VariablesPath is the collection endpoint for instance and project variables. @@ -23,12 +25,9 @@ type Variable struct { Project *VariableProject `json:"project,omitempty"` } -// VariableProject identifies the project scope attached to a variable. -type VariableProject struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type,omitempty"` -} +// VariableProject is the project scope attached to a variable. The API +// returns the full project there, so it is the same model as [Project]. +type VariableProject = Project // VariableState is an optional server-side list filter. type VariableState string @@ -72,22 +71,65 @@ func (o ListVariablesOptions) apply() url.Values { return query } +// Variable field limits from the contract. +const ( + MaxVariableKey = 50 + MaxVariableValue = 1000 + MaxVariableProjectID = 36 +) + +var ( + // variableCreateKeyPattern is the key shape create accepts: no leading + // digit. + variableCreateKeyPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + // variableUpdateKeyPattern is the looser key shape update accepts. + variableUpdateKeyPattern = regexp.MustCompile(`^[A-Za-z0-9_]+$`) +) + // VariableRequest is the complete create or replacement document. ProjectID is -// optional; omitting it addresses global scope. Value is required by the API -// but may be the empty string. +// optional; omitting it on create addresses global scope. Value is required +// by the API but may be the empty string. type VariableRequest struct { Key string `json:"key"` Value string `json:"value"` ProjectID string `json:"projectId,omitempty"` } -// Validate rejects malformed documents before transport without including the -// value in any diagnostic. +// Validate rejects malformed replacement documents before transport without +// including the value in any diagnostic. Create is stricter about the key; +// see [VariableRequest.ValidateCreate]. func (r VariableRequest) Validate() error { if err := validateVariableText("key", r.Key, true); err != nil { return err } - return validateVariableText("project ID", r.ProjectID, false) + if len(r.Key) > MaxVariableKey { + return fmt.Errorf("variable key is %d characters; the API accepts at most %d", len(r.Key), MaxVariableKey) + } + if !variableUpdateKeyPattern.MatchString(r.Key) { + return fmt.Errorf("variable key %q is invalid: use only letters, digits and underscores", r.Key) + } + if n := utf8.RuneCountInString(r.Value); n > MaxVariableValue { + return fmt.Errorf("variable value is %d characters; the API accepts at most %d", n, MaxVariableValue) + } + if err := validateVariableText("project ID", r.ProjectID, false); err != nil { + return err + } + if len(r.ProjectID) > MaxVariableProjectID { + return fmt.Errorf("variable project ID is %d characters; the API accepts at most %d", len(r.ProjectID), MaxVariableProjectID) + } + return nil +} + +// ValidateCreate is [VariableRequest.Validate] plus the create-only rule +// that a key must not start with a digit. +func (r VariableRequest) ValidateCreate() error { + if err := r.Validate(); err != nil { + return err + } + if !variableCreateKeyPattern.MatchString(r.Key) { + return fmt.Errorf("variable key %q is invalid: start with a letter or underscore, then use only letters, digits and underscores", r.Key) + } + return nil } // ListVariables returns one cursor-paginated page. Returned values are API @@ -106,7 +148,7 @@ func (c *Client) ListVariables(ctx context.Context, opts ListVariablesOptions) ( // CreateVariable creates a global or project-scoped variable. The documented // 201 response has no body. func (c *Client) CreateVariable(ctx context.Context, request VariableRequest) error { - if err := request.Validate(); err != nil { + if err := request.ValidateCreate(); err != nil { return err } _, err := c.Do(ctx, Request{Method: http.MethodPost, Path: VariablesPath, Body: request}, nil) diff --git a/internal/n8n/variable_test.go b/internal/n8n/variable_test.go index a487abf..de28422 100644 --- a/internal/n8n/variable_test.go +++ b/internal/n8n/variable_test.go @@ -2,6 +2,7 @@ package n8n import ( "context" + "encoding/json" "net/http" "strings" "testing" @@ -163,6 +164,38 @@ func TestVariableWriteErrorsRedactSubmittedValue(t *testing.T) { } } +func TestVariableKeyRulesDifferBetweenCreateAndUpdate(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusNoContent, ``)) + client := server.client(t) + // Update accepts a leading digit, create does not. + if err := client.UpdateVariable(context.Background(), "id", VariableRequest{Key: "1KEY", Value: strings.Repeat("é", 1000)}); err != nil { + t.Errorf("update with a leading digit and a 1000-character value: %v", err) + } + if err := client.CreateVariable(context.Background(), VariableRequest{Key: "_" + strings.Repeat("K", 49), Value: ""}); err != nil { + t.Errorf("create with a 50-character underscore key: %v", err) + } + if len(server.requests) != 2 { + t.Errorf("%d requests, want both valid writes sent", len(server.requests)) + } +} + +func TestVariableProjectKeepsFullProject(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"data":[{"id":"v-1","key":"K","value":"","project":{"id":"p-1","name":"Ops","type":"team","icon":null,"description":"Runbooks","customTelemetryTags":[],"creatorId":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}}],"nextCursor":null}`)) + page, err := server.client(t).ListVariables(context.Background(), ListVariablesOptions{}) + if err != nil { + t.Fatalf("ListVariables: %v", err) + } + project := page.Data[0].Project + if project == nil || project.Description.Value != "Runbooks" || !project.Icon.Null || project.CreatedAt == "" { + t.Fatalf("project = %+v", project) + } + encoded, err := json.Marshal(project) + if err != nil { + t.Fatalf("encode: %v", err) + } + assertJSONEqual(t, `{"id":"p-1","name":"Ops","type":"team","icon":null,"description":"Runbooks","customTelemetryTags":[],"creatorId":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}`, string(encoded)) +} + func TestVariableValidationBeforeRequest(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{}`)) client := server.client(t) @@ -188,6 +221,24 @@ func TestVariableValidationBeforeRequest(t *testing.T) { "padded write project": func() error { return client.CreateVariable(context.Background(), VariableRequest{Key: "KEY", Value: "allowed", ProjectID: " project"}) }, + "create key with leading digit": func() error { + return client.CreateVariable(context.Background(), VariableRequest{Key: "1KEY", Value: "allowed"}) + }, + "create key with dash": func() error { + return client.CreateVariable(context.Background(), VariableRequest{Key: "API-HOST", Value: "allowed"}) + }, + "long key": func() error { + return client.CreateVariable(context.Background(), VariableRequest{Key: strings.Repeat("K", 51), Value: "allowed"}) + }, + "long value": func() error { + return client.CreateVariable(context.Background(), VariableRequest{Key: "KEY", Value: strings.Repeat("v", 1001)}) + }, + "long project ID": func() error { + return client.CreateVariable(context.Background(), VariableRequest{Key: "KEY", Value: "allowed", ProjectID: strings.Repeat("p", 37)}) + }, + "update key with dash": func() error { + return client.UpdateVariable(context.Background(), "id", VariableRequest{Key: "API-HOST", Value: "allowed"}) + }, "empty update ID": func() error { return client.UpdateVariable(context.Background(), "", VariableRequest{Key: "KEY", Value: "allowed"}) }, diff --git a/test/integration/project_test.go b/test/integration/project_test.go index 0bbf29a..4c55fbb 100644 --- a/test/integration/project_test.go +++ b/test/integration/project_test.go @@ -50,7 +50,7 @@ func TestProjectLifecycle(t *testing.T) { ctx := context.Background() name := fmt.Sprintf("%sproject-%d", integration.ResourcePrefix, time.Now().UnixNano()) - created, err := client.CreateProject(ctx, name) + created, err := client.CreateProject(ctx, n8n.CreateProjectRequest{Name: name}) if err != nil { skipUnlicensed(t, err) t.Fatalf("CreateProject(%q): %v", name, err) From dc66e5362f2273bb04b8c0cebc4c68220b8e4a2d Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 23:58:30 -0500 Subject: [PATCH 7/7] fix(folder): validate name and folder ID limits, document move to root Folder names are at most 128 characters; parentFolderId on create and transferToFolderId on delete at most 36. The contract now documents parentFolderId "0" on update as moving the folder to the project root, so the help no longer says that is impossible. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/n8n_folder_update.md | 9 ++++---- internal/cli/folder.go | 9 ++++---- internal/cli/folder_test.go | 10 +++++++++ internal/n8n/folder.go | 44 ++++++++++++++++++++++++++++++++----- internal/n8n/folder_test.go | 15 +++++++++++++ 5 files changed, 73 insertions(+), 14 deletions(-) diff --git a/docs/n8n_folder_update.md b/docs/n8n_folder_update.md index d97c03b..30104ec 100644 --- a/docs/n8n_folder_update.md +++ b/docs/n8n_folder_update.md @@ -9,9 +9,9 @@ Update one folder. This is a partial update: --name renames the folder, and passing both does both. At least one of them is required; anything left out stays as it is. -The API has no way to clear a parent, so a folder cannot be moved back to the -project root with this command, and the target folder must be in the same -project. Requires folder:update. +--parent-folder-id 0 moves the folder back to the project root. Otherwise the +target folder must be in the same project. Names are at most 128 characters. +Requires folder:update. ``` n8n folder update [flags] @@ -22,6 +22,7 @@ n8n folder update [flags] ``` n8n folder update PROJECT_ID FOLDER_ID --name "Paid invoices" n8n folder update PROJECT_ID FOLDER_ID --parent-folder-id OTHER_FOLDER_ID + n8n folder update PROJECT_ID FOLDER_ID --parent-folder-id 0 n8n folder update PROJECT_ID FOLDER_ID --name Archive --parent-folder-id OTHER_FOLDER_ID --output json ``` @@ -32,7 +33,7 @@ n8n folder update [flags] -h, --help help for update --name string new folder name (required unless --parent-folder-id is given) --output string output format: text or json (JSON is the updated folder) (default "text") - --parent-folder-id string move the folder inside this folder (required unless --name is given) + --parent-folder-id string move the folder inside this folder, or 0 for the project root (required unless --name is given) --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) ``` diff --git a/internal/cli/folder.go b/internal/cli/folder.go index 4fde220..ad9d821 100644 --- a/internal/cli/folder.go +++ b/internal/cli/folder.go @@ -349,11 +349,12 @@ func newFolderUpdateCommand(opts Options) *cobra.Command { "--parent-folder-id moves it (with everything inside it) under another folder,\n" + "and passing both does both. At least one of them is required; anything left out\n" + "stays as it is.\n\n" + - "The API has no way to clear a parent, so a folder cannot be moved back to the\n" + - "project root with this command, and the target folder must be in the same\n" + - "project. Requires folder:update.", + "--parent-folder-id 0 moves the folder back to the project root. Otherwise the\n" + + "target folder must be in the same project. Names are at most 128 characters.\n" + + "Requires folder:update.", Example: " n8n folder update PROJECT_ID FOLDER_ID --name \"Paid invoices\"\n" + " n8n folder update PROJECT_ID FOLDER_ID --parent-folder-id OTHER_FOLDER_ID\n" + + " n8n folder update PROJECT_ID FOLDER_ID --parent-folder-id 0\n" + " n8n folder update PROJECT_ID FOLDER_ID --name Archive --parent-folder-id OTHER_FOLDER_ID --output json", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { @@ -362,7 +363,7 @@ func newFolderUpdateCommand(opts Options) *cobra.Command { } f.write.instance.register(cmd) cmd.Flags().StringVar(&f.name, "name", "", "new folder name (required unless --parent-folder-id is given)") - cmd.Flags().StringVar(&f.write.parent, "parent-folder-id", "", "move the folder inside this folder (required unless --name is given)") + cmd.Flags().StringVar(&f.write.parent, "parent-folder-id", "", "move the folder inside this folder, or 0 for the project root (required unless --name is given)") cmd.Flags().StringVar(&f.write.output, "output", outputText, "output format: text or json (JSON is the updated folder)") return cmd } diff --git a/internal/cli/folder_test.go b/internal/cli/folder_test.go index 0f918bc..d55eaa5 100644 --- a/internal/cli/folder_test.go +++ b/internal/cli/folder_test.go @@ -302,6 +302,15 @@ func TestFolderDeleteConfirmationAndTransfer(t *testing.T) { }) } +func TestFolderUpdateMovesToProjectRoot(t *testing.T) { + f := folderFixture(t, cliFolder) + got := f.run("folder", "update", "pr-1", "fo-1", "--parent-folder-id", n8n.FolderRootID) + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + assertCLIJSON(t, `{"parentFolderId":"0"}`, f.lastBody()) +} + func TestFolderValidationBeforeRequest(t *testing.T) { tests := []struct { name string @@ -309,6 +318,7 @@ func TestFolderValidationBeforeRequest(t *testing.T) { want string }{ {name: "blank project", args: []string{"folder", "list", " "}, want: "project ID is required"}, + {name: "long name", args: []string{"folder", "create", "pr-1", strings.Repeat("n", 129)}, want: "at most 128"}, {name: "unknown output", args: []string{"folder", "list", "pr-1", "--output", "yaml"}, want: "unknown output format"}, {name: "negative skip", args: []string{"folder", "list", "pr-1", "--skip", "-1"}, want: "skip must not be negative"}, {name: "negative take", args: []string{"folder", "list", "pr-1", "--take", "-1"}, want: "take must not be negative"}, diff --git a/internal/n8n/folder.go b/internal/n8n/folder.go index 1431234..82a941c 100644 --- a/internal/n8n/folder.go +++ b/internal/n8n/folder.go @@ -9,6 +9,7 @@ import ( "slices" "strconv" "strings" + "unicode/utf8" ) // DefaultFolderPageSize is the page size used when following every page. The @@ -171,6 +172,16 @@ func (o ListFoldersOptions) apply() (url.Values, error) { return query, nil } +// Folder field limits from the contract. +const ( + MaxFolderName = 128 + MaxFolderID = 36 +) + +// FolderRootID is the parent folder ID that moves a folder to the project +// root in an update. +const FolderRootID = "0" + // CreateFolderRequest is the write document for folder creation. ParentFolderID // is optional: without it the folder is created at the project root. type CreateFolderRequest struct { @@ -180,16 +191,15 @@ type CreateFolderRequest struct { // Validate rejects a malformed creation before transport. func (r CreateFolderRequest) Validate() error { - if err := validateFolderText("name", r.Name, true); err != nil { + if err := validateFolderName(r.Name, true); err != nil { return err } - return validateFolderText("parent folder ID", r.ParentFolderID, false) + return validateFolderLinkedID("parent folder ID", r.ParentFolderID) } // UpdateFolderRequest is the partial write document for a folder update. At // least one field must be set, because the API requires a non-empty document. -// There is no way to clear a parent: moving a folder back to the project root -// is not part of this contract. +// ParentFolderID [FolderRootID] moves the folder to the project root. type UpdateFolderRequest struct { Name string `json:"name,omitempty"` ParentFolderID string `json:"parentFolderId,omitempty"` @@ -200,7 +210,7 @@ func (r UpdateFolderRequest) Validate() error { if r.Name == "" && r.ParentFolderID == "" { return fmt.Errorf("a folder update needs a new name or a new parent folder ID") } - if err := validateFolderText("name", r.Name, false); err != nil { + if err := validateFolderName(r.Name, false); err != nil { return err } return validateFolderText("parent folder ID", r.ParentFolderID, false) @@ -298,7 +308,7 @@ func (c *Client) DeleteFolder(ctx context.Context, projectID, folderID, transfer if err := validateFolderID(folderID); err != nil { return err } - if err := validateFolderText("transfer target folder ID", transferToFolderID, false); err != nil { + if err := validateFolderLinkedID("transfer target folder ID", transferToFolderID); err != nil { return err } query := url.Values{} @@ -404,6 +414,28 @@ func validateFolderProjectID(id string) error { return validateFolderText("proje func validateFolderID(id string) error { return validateFolderText("ID", id, true) } +func validateFolderName(name string, required bool) error { + if err := validateFolderText("name", name, required); err != nil { + return err + } + if n := utf8.RuneCountInString(name); n > MaxFolderName { + return fmt.Errorf("folder name is %d characters; the API accepts at most %d", n, MaxFolderName) + } + return nil +} + +// validateFolderLinkedID checks an optional folder ID sent in a body or +// query, where the contract caps the length. +func validateFolderLinkedID(field, id string) error { + if err := validateFolderText(field, id, false); err != nil { + return err + } + if len(id) > MaxFolderID { + return fmt.Errorf("folder %s is %d characters; the API accepts at most %d", field, len(id), MaxFolderID) + } + return nil +} + func validateFolderText(field, value string, required bool) error { if required && strings.TrimSpace(value) == "" { return fmt.Errorf("folder %s is required", field) diff --git a/internal/n8n/folder_test.go b/internal/n8n/folder_test.go index 909159d..d3762fa 100644 --- a/internal/n8n/folder_test.go +++ b/internal/n8n/folder_test.go @@ -293,6 +293,21 @@ func TestFolderValidationBeforeRequest(t *testing.T) { _, err := client.ListFolders(context.Background(), " ", ListFoldersOptions{}) return err }, + "long create name": func() error { + _, err := client.CreateFolder(context.Background(), "pr-1", CreateFolderRequest{Name: strings.Repeat("n", 129)}) + return err + }, + "long create parent": func() error { + _, err := client.CreateFolder(context.Background(), "pr-1", CreateFolderRequest{Name: "n", ParentFolderID: strings.Repeat("p", 37)}) + return err + }, + "long update name": func() error { + _, err := client.UpdateFolder(context.Background(), "pr-1", "fo-1", UpdateFolderRequest{Name: strings.Repeat("n", 129)}) + return err + }, + "long transfer target": func() error { + return client.DeleteFolder(context.Background(), "pr-1", "fo-1", strings.Repeat("t", 37)) + }, "negative skip": func() error { _, err := client.ListFolders(context.Background(), "pr-1", ListFoldersOptions{Skip: -1}) return err