From f79313fc5eb7300b9ab6e0fb15ab292c710fa1f6 Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Tue, 3 Nov 2026 21:52:06 -0500 Subject: [PATCH] feat(dependencies): add workflow, credential and data-table dependency lookups - n8n workflow|credential|data-table dependencies : GET /{workflows,credentials,data-tables}/{id}/dependencies (n8n 2.46.4), one shared DependencyPage client type with path-escaped IDs. - --limit (1-250, validated locally), --cursor, --all (10,000 cap with collection report), --output text|json. JSON keeps the API page shape incl. inaccessibleCount; text adds a uses / used-by relation column and notes hidden dependencies on stderr. - 403 names the required scope (workflow:read, credential:read, dataTable:read); 404 points at the matching list command and at 'n8n discover' for instances that predate the endpoints. - data-table dependencies keeps the group's API-key-only rule. - Manifest: phase 34 implemented; deliveredThrough raised to 34. - Client + CLI tests, read-only opt-in integration test, docs. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 3 + docs/n8n_credential.md | 1 + docs/n8n_credential_dependencies.md | 58 ++++++ docs/n8n_data-table.md | 1 + docs/n8n_data-table_dependencies.md | 58 ++++++ docs/n8n_workflow.md | 1 + docs/n8n_workflow_dependencies.md | 59 ++++++ internal/cli/credential.go | 3 +- internal/cli/datatable.go | 3 +- internal/cli/dependency.go | 287 ++++++++++++++++++++++++++++ internal/cli/dependency_test.go | 227 ++++++++++++++++++++++ internal/cli/help_test.go | 3 + internal/cli/scope_test.go | 3 + internal/cli/workflow.go | 3 +- internal/coverage/coverage_test.go | 2 +- internal/coverage/manifest.json | 12 +- internal/n8n/credential.go | 9 + internal/n8n/datatable.go | 9 + internal/n8n/dependency.go | 89 +++++++++ internal/n8n/dependency_test.go | 133 +++++++++++++ internal/n8n/workflow.go | 10 + test/integration/dependency_test.go | 130 +++++++++++++ 22 files changed, 1094 insertions(+), 10 deletions(-) create mode 100644 docs/n8n_credential_dependencies.md create mode 100644 docs/n8n_data-table_dependencies.md create mode 100644 docs/n8n_workflow_dependencies.md create mode 100644 internal/cli/dependency.go create mode 100644 internal/cli/dependency_test.go create mode 100644 internal/n8n/dependency.go create mode 100644 internal/n8n/dependency_test.go create mode 100644 test/integration/dependency_test.go diff --git a/docs/README.md b/docs/README.md index 22fa57a..f599254 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n community-package`](n8n_community-package.md) | Manage community node packages | | [`n8n credential create`](n8n_credential_create.md) | Create a credential from secret JSON | | [`n8n credential delete`](n8n_credential_delete.md) | Permanently delete a credential | +| [`n8n credential dependencies`](n8n_credential_dependencies.md) | List the workflows and agents that use a credential | | [`n8n credential get`](n8n_credential_get.md) | Get credential metadata | | [`n8n credential list`](n8n_credential_list.md) | List credential metadata | | [`n8n credential schema`](n8n_credential_schema.md) | Show credential data JSON Schema | @@ -46,6 +47,7 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n data-table column`](n8n_data-table_column.md) | Manage the columns of a data table | | [`n8n data-table create`](n8n_data-table_create.md) | Create a data table | | [`n8n data-table delete`](n8n_data-table_delete.md) | Permanently delete a data table and every row in it | +| [`n8n data-table dependencies`](n8n_data-table_dependencies.md) | List the workflows that use a data table | | [`n8n data-table get`](n8n_data-table_get.md) | Show one data table and its columns | | [`n8n data-table list`](n8n_data-table_list.md) | List data tables | | [`n8n data-table row clear`](n8n_data-table_row_clear.md) | Permanently delete every row of a data table | @@ -229,6 +231,7 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n workflow archive`](n8n_workflow_archive.md) | Archive a workflow, the reversible soft delete | | [`n8n workflow create`](n8n_workflow_create.md) | Create a workflow from a definition or as an empty one | | [`n8n workflow delete`](n8n_workflow_delete.md) | Permanently delete a workflow | +| [`n8n workflow dependencies`](n8n_workflow_dependencies.md) | List what a workflow uses and what uses it | | [`n8n workflow get`](n8n_workflow_get.md) | Show one workflow with its definition | | [`n8n workflow history`](n8n_workflow_history.md) | List the saved versions of a workflow | | [`n8n workflow list`](n8n_workflow_list.md) | List workflows | diff --git a/docs/n8n_credential.md b/docs/n8n_credential.md index b07141b..80922c3 100644 --- a/docs/n8n_credential.md +++ b/docs/n8n_credential.md @@ -38,6 +38,7 @@ n8n credential [flags] * [n8n](n8n.md) - Command-line client for the n8n API * [n8n credential create](n8n_credential_create.md) - Create a credential from secret JSON * [n8n credential delete](n8n_credential_delete.md) - Permanently delete a credential +* [n8n credential dependencies](n8n_credential_dependencies.md) - List the workflows and agents that use a credential * [n8n credential get](n8n_credential_get.md) - Get credential metadata * [n8n credential list](n8n_credential_list.md) - List credential metadata * [n8n credential schema](n8n_credential_schema.md) - Show credential data JSON Schema diff --git a/docs/n8n_credential_dependencies.md b/docs/n8n_credential_dependencies.md new file mode 100644 index 0000000..1b0a20c --- /dev/null +++ b/docs/n8n_credential_dependencies.md @@ -0,0 +1,58 @@ +## n8n credential dependencies + +List the workflows and agents that use a credential + +### Synopsis + +List the workflows and agents that use one credential. Check this before +deleting, transferring or rotating a credential. Only metadata is returned; +credential data is never requested. Requires credential:read. + +TYPE is the relation to the requested resource: + credential, dataTable, subWorkflow, errorWorkflow + the requested workflow uses this resource + parentWorkflow this workflow uses the requested resource + errorWorkflowParent this workflow uses the requested workflow as its error + workflow + agent this agent uses the requested resource + +Dependencies the account in use cannot access are not listed; the summary +counts them as Inaccessible (JSON: inaccessibleCount, over the whole list, not +one page). Pass a returned cursor to --cursor for the next page, or use --all +to follow every cursor, capped at 10,000 dependencies. + +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 +without reaching the end. nextCursor then resumes the walk when the limit fell +between pages; it stays empty when the limit fell inside a page, because +resuming from the next page would skip items: narrow the filters or page +explicitly with --limit and --cursor instead. + +``` +n8n credential dependencies [flags] +``` + +### Examples + +``` + n8n credential dependencies CREDENTIAL_ID + n8n credential dependencies CREDENTIAL_ID --all --output json + n8n credential dependencies CREDENTIAL_ID --limit 50 --cursor CURSOR +``` + +### Options + +``` + --all follow every page instead of one (maximum 10,000 dependencies; hitting it warns and sets JSON collection.truncated) + --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 page (default: the first page) + -h, --help help for dependencies + --limit int dependencies per API page, 1 to 250 (default: server default of 100) + --output string output format: text or json (JSON is a page object with data, nextCursor and inaccessibleCount, plus collection with --all) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n credential](n8n_credential.md) - Manage node credentials without exposing secrets + diff --git a/docs/n8n_data-table.md b/docs/n8n_data-table.md index d91e4f6..adb83a9 100644 --- a/docs/n8n_data-table.md +++ b/docs/n8n_data-table.md @@ -42,6 +42,7 @@ n8n data-table [flags] * [n8n data-table column](n8n_data-table_column.md) - Manage the columns of a data table * [n8n data-table create](n8n_data-table_create.md) - Create a data table * [n8n data-table delete](n8n_data-table_delete.md) - Permanently delete a data table and every row in it +* [n8n data-table dependencies](n8n_data-table_dependencies.md) - List the workflows that use a data table * [n8n data-table get](n8n_data-table_get.md) - Show one data table and its columns * [n8n data-table list](n8n_data-table_list.md) - List data tables * [n8n data-table row](n8n_data-table_row.md) - Read and change the rows of a data table diff --git a/docs/n8n_data-table_dependencies.md b/docs/n8n_data-table_dependencies.md new file mode 100644 index 0000000..89a179d --- /dev/null +++ b/docs/n8n_data-table_dependencies.md @@ -0,0 +1,58 @@ +## n8n data-table dependencies + +List the workflows that use a data table + +### Synopsis + +List the workflows that use one data table. Check this before deleting the +table, clearing its rows or changing its columns. Like every data-table +command it requires API-key authentication, and it requires dataTable:read. + +TYPE is the relation to the requested resource: + credential, dataTable, subWorkflow, errorWorkflow + the requested workflow uses this resource + parentWorkflow this workflow uses the requested resource + errorWorkflowParent this workflow uses the requested workflow as its error + workflow + agent this agent uses the requested resource + +Dependencies the account in use cannot access are not listed; the summary +counts them as Inaccessible (JSON: inaccessibleCount, over the whole list, not +one page). Pass a returned cursor to --cursor for the next page, or use --all +to follow every cursor, capped at 10,000 dependencies. + +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 +without reaching the end. nextCursor then resumes the walk when the limit fell +between pages; it stays empty when the limit fell inside a page, because +resuming from the next page would skip items: narrow the filters or page +explicitly with --limit and --cursor instead. + +``` +n8n data-table dependencies [flags] +``` + +### Examples + +``` + n8n data-table dependencies TABLE_ID + n8n data-table dependencies TABLE_ID --all --output json + n8n data-table dependencies TABLE_ID --limit 50 --cursor CURSOR +``` + +### Options + +``` + --all follow every page instead of one (maximum 10,000 dependencies; hitting it warns and sets JSON collection.truncated) + --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 page (default: the first page) + -h, --help help for dependencies + --limit int dependencies per API page, 1 to 250 (default: server default of 100) + --output string output format: text or json (JSON is a page object with data, nextCursor and inaccessibleCount, plus collection with --all) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n data-table](n8n_data-table.md) - Manage data tables, their rows and their columns + diff --git a/docs/n8n_workflow.md b/docs/n8n_workflow.md index 7974abe..898f164 100644 --- a/docs/n8n_workflow.md +++ b/docs/n8n_workflow.md @@ -50,6 +50,7 @@ n8n workflow [flags] * [n8n workflow copy](n8n_workflow_copy.md) - Copy a saved workflow definition from one context to another * [n8n workflow create](n8n_workflow_create.md) - Create a workflow from a definition or as an empty one * [n8n workflow delete](n8n_workflow_delete.md) - Permanently delete a workflow +* [n8n workflow dependencies](n8n_workflow_dependencies.md) - List what a workflow uses and what uses it * [n8n workflow diff](n8n_workflow_diff.md) - Compare saved workflows across two contexts * [n8n workflow get](n8n_workflow_get.md) - Show one workflow with its definition * [n8n workflow history](n8n_workflow_history.md) - List the saved versions of a workflow diff --git a/docs/n8n_workflow_dependencies.md b/docs/n8n_workflow_dependencies.md new file mode 100644 index 0000000..1cdd57f --- /dev/null +++ b/docs/n8n_workflow_dependencies.md @@ -0,0 +1,59 @@ +## n8n workflow dependencies + +List what a workflow uses and what uses it + +### Synopsis + +List the dependencies of one workflow in both directions: the credentials, data +tables, sub-workflows and error workflow it uses, and the workflows and agents +that use it, as a sub-workflow or as their error workflow. Check this before +archiving, deleting or transferring a workflow. Requires workflow:read. + +TYPE is the relation to the requested resource: + credential, dataTable, subWorkflow, errorWorkflow + the requested workflow uses this resource + parentWorkflow this workflow uses the requested resource + errorWorkflowParent this workflow uses the requested workflow as its error + workflow + agent this agent uses the requested resource + +Dependencies the account in use cannot access are not listed; the summary +counts them as Inaccessible (JSON: inaccessibleCount, over the whole list, not +one page). Pass a returned cursor to --cursor for the next page, or use --all +to follow every cursor, capped at 10,000 dependencies. + +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 +without reaching the end. nextCursor then resumes the walk when the limit fell +between pages; it stays empty when the limit fell inside a page, because +resuming from the next page would skip items: narrow the filters or page +explicitly with --limit and --cursor instead. + +``` +n8n workflow dependencies [flags] +``` + +### Examples + +``` + n8n workflow dependencies WORKFLOW_ID + n8n workflow dependencies WORKFLOW_ID --all --output json + n8n workflow dependencies WORKFLOW_ID --limit 50 --cursor CURSOR +``` + +### Options + +``` + --all follow every page instead of one (maximum 10,000 dependencies; hitting it warns and sets JSON collection.truncated) + --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 page (default: the first page) + -h, --help help for dependencies + --limit int dependencies per API page, 1 to 250 (default: server default of 100) + --output string output format: text or json (JSON is a page object with data, nextCursor and inaccessibleCount, plus collection with --all) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n workflow](n8n_workflow.md) - Manage workflows, their versions and their tags + diff --git a/internal/cli/credential.go b/internal/cli/credential.go index a20e5b1..e1547ee 100644 --- a/internal/cli/credential.go +++ b/internal/cli/credential.go @@ -43,6 +43,7 @@ func newCredentialCommand(opts Options) *cobra.Command { newCredentialListCommand(opts), newCredentialCreateCommand(opts), newCredentialGetCommand(opts), + newCredentialDependenciesCommand(opts), newCredentialUpdateCommand(opts), newCredentialDeleteCommand(opts), newCredentialTestCommand(opts), @@ -615,7 +616,7 @@ func credentialScope(action string) scopeNeed { switch action { case "list": return allOf("credential:list") - case "get", "test": + case "get", "test", dependencyAction: return allOf("credential:read") case "create": return allOf("credential:create") diff --git a/internal/cli/datatable.go b/internal/cli/datatable.go index e83271d..dd1bcba 100644 --- a/internal/cli/datatable.go +++ b/internal/cli/datatable.go @@ -53,6 +53,7 @@ func newDataTableCommand(opts Options) *cobra.Command { newDataTableListCommand(opts), newDataTableCreateCommand(opts), newDataTableGetCommand(opts), + newDataTableDependenciesCommand(opts), newDataTableUpdateCommand(opts), newDataTableDeleteCommand(opts), newDataTableRowCommand(opts), @@ -1561,7 +1562,7 @@ func dataTableScope(action string) scopeNeed { switch action { case "list": return allOf("dataTable:list") - case "read": + case "read", dependencyAction: return allOf("dataTable:read") case "create": return allOf("dataTable:create") diff --git a/internal/cli/dependency.go b/internal/cli/dependency.go new file mode 100644 index 0000000..43f0a56 --- /dev/null +++ b/internal/cli/dependency.go @@ -0,0 +1,287 @@ +package cli + +import ( + "context" + "fmt" + "io" + "text/tabwriter" + + "github.com/spf13/cobra" + + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" +) + +// dependencyAction is the action name the scope mappers know the dependency +// lookups by. +const dependencyAction = "dependencies" + +// dependencyTarget is what differs between the workflow, credential and data +// table dependency lookups; the command shape, output and errors are shared. +type dependencyTarget struct { + // noun names the resource in messages, e.g. "data table"; label is the + // same as a text summary heading, e.g. "Data table". + noun string + label string + // group is the command group, e.g. "data-table". + group string + // idArg is the argument placeholder, e.g. "workflow-id". + idArg string + // placeholder is the ID in examples, e.g. "WORKFLOW_ID". + placeholder string + // listCommand finds valid IDs, e.g. "n8n workflow list". + listCommand string + // resource is the 'n8n discover' resource key. + resource string + // scope is what the API requires; the manifest records the same scope. + scope scopeNeed + // forbiddenCause is the other reason a 403 can have, besides the scope. + forbiddenCause string + short string + long string + // validate checks the ID argument before any request. + validate func(string) error + // client resolves the API client, enforcing any auth restriction. + client func(Options, instanceFlags) (*n8n.Client, config.Resolution, error) + // fetch selects the client method for one page. + fetch func(*n8n.Client) n8n.DependencyFunc +} + +type dependencyFlags struct { + instance instanceFlags + limit int + cursor string + all bool + output string +} + +// dependencyTypesHelp explains every type the API reports. Each lookup only +// returns the subset that applies to its resource. +const dependencyTypesHelp = "TYPE is the relation to the requested resource:\n" + + " credential, dataTable, subWorkflow, errorWorkflow\n" + + " the requested workflow uses this resource\n" + + " parentWorkflow this workflow uses the requested resource\n" + + " errorWorkflowParent this workflow uses the requested workflow as its error\n" + + " workflow\n" + + " agent this agent uses the requested resource" + +// dependencyAccessHelp explains inaccessibleCount and the pagination flags. +const dependencyAccessHelp = "Dependencies the account in use cannot access are not listed; the summary\n" + + "counts them as Inaccessible (JSON: inaccessibleCount, over the whole list, not\n" + + "one page). Pass a returned cursor to --cursor for the next page, or use --all\n" + + "to follow every cursor, capped at 10,000 dependencies.\n\n" + cursorCollectionHelp + +func newDependencyCommand(opts Options, target dependencyTarget) *cobra.Command { + var f dependencyFlags + cmd := &cobra.Command{ + Use: "dependencies <" + target.idArg + ">", + Short: target.short, + Long: target.long + "\n\n" + dependencyTypesHelp + "\n\n" + dependencyAccessHelp, + Example: " n8n " + target.group + " dependencies " + target.placeholder + "\n" + + " n8n " + target.group + " dependencies " + target.placeholder + " --all --output json\n" + + " n8n " + target.group + " dependencies " + target.placeholder + " --limit 50 --cursor CURSOR", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runDependencies(cmd.Context(), opts, target, args[0], f) + }, + } + f.instance.register(cmd) + cmd.Flags().IntVar(&f.limit, "limit", 0, fmt.Sprintf("dependencies per API page, 1 to %d (default: server default of 100)", n8n.MaxDependencyLimit)) + cmd.Flags().StringVar(&f.cursor, "cursor", "", "pagination cursor returned by a previous page (default: the first page)") + cmd.Flags().BoolVar(&f.all, "all", false, "follow every page instead of one (maximum 10,000 dependencies; hitting it warns and sets JSON collection.truncated)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is a page object with data, nextCursor and inaccessibleCount, plus collection with --all)") + return cmd +} + +func runDependencies(ctx context.Context, opts Options, target dependencyTarget, id string, f dependencyFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := target.validate(id); err != nil { + return err + } + listOpts := n8n.ListOptions{Limit: f.limit, Cursor: f.cursor} + if err := n8n.ValidateDependencyOptions(listOpts); err != nil { + return err + } + client, resolution, err := target.client(opts, f.instance) + if err != nil { + return err + } + lookup := target.fetch(client) + // inaccessibleCount counts the whole list, so every page repeats it; the + // largest value seen is kept in case a page reports none. + inaccessible := 0 + fetch := func(ctx context.Context, pagination n8n.ListOptions) (n8n.Page[n8n.Dependency], error) { + page, err := lookup(ctx, id, pagination) + if err != nil { + return n8n.Page[n8n.Dependency]{}, err + } + inaccessible = max(inaccessible, page.InaccessibleCount) + return page.Page(), nil + } + var page n8n.Page[n8n.Dependency] + var collection *listCollection + if f.all { + page, collection, err = collectPage(ctx, fetch, listOpts) + } else { + page, err = fetch(ctx, listOpts) + } + if err != nil { + return dependencyAPIError(err, resolution, target) + } + result := n8n.DependencyPage{Data: page.Data, NextCursor: page.NextCursor, InaccessibleCount: inaccessible} + if result.Data == nil { + result.Data = []n8n.Dependency{} + } + if f.output == outputJSON { + err = writeDependencyJSON(opts.Streams.Out, result, collection) + } else { + err = writeDependencyText(opts, resolution, target, id, result) + } + return finishCollection(opts.Streams.Err, collection, err) +} + +// collectedDependencyPage is the JSON of a bounded dependency collection: the +// API page shape plus the collection report. +type collectedDependencyPage struct { + Data []n8n.Dependency `json:"data"` + NextCursor string `json:"nextCursor"` + InaccessibleCount int `json:"inaccessibleCount"` + Collection collectionInfo `json:"collection"` +} + +func writeDependencyJSON(w io.Writer, page n8n.DependencyPage, c *listCollection) error { + if c == nil { + return writeJSON(w, page) + } + return writeJSON(w, collectedDependencyPage{ + Data: page.Data, NextCursor: page.NextCursor, InaccessibleCount: page.InaccessibleCount, Collection: c.info, + }) +} + +func writeDependencyText(opts Options, resolution config.Resolution, target dependencyTarget, id string, page n8n.DependencyPage) error { + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "%s:\t%s\n", target.label, id) + fmt.Fprintf(tw, "Dependencies:\t%d\n", len(page.Data)) + fmt.Fprintf(tw, "Inaccessible:\t%d\n", page.InaccessibleCount) + fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) + if len(page.Data) > 0 { + fmt.Fprintln(tw, "\nRELATION\tTYPE\tID\tNAME\tPROJECT") + for _, dep := range page.Data { + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", + dependencyRelation(dep.Type), emptyDash(dep.Type), emptyDash(dep.ID), emptyDash(dep.Name), emptyDash(dep.ProjectID)) + } + } + if page.NextCursor != "" { + fmt.Fprintf(tw, "\nNext cursor:\t%s\n", page.NextCursor) + } + if err := tw.Flush(); err != nil { + return err + } + if len(page.Data) == 0 && page.InaccessibleCount == 0 { + fmt.Fprintf(opts.Streams.Err, "No dependencies: nothing this %s uses or is used by was found.\n", target.noun) + } + if page.InaccessibleCount > 0 { + fmt.Fprintf(opts.Streams.Err, "%d %s not listed because the account in use cannot access %s; a user with access to their projects, or an owner or admin, sees them.\n", + page.InaccessibleCount, plural(page.InaccessibleCount, "dependency is", "dependencies are"), plural(page.InaccessibleCount, "it", "them")) + } + return nil +} + +// dependencyRelation says which way a dependency points: something the +// requested resource uses, or something that uses it. +func dependencyRelation(kind string) string { + switch kind { + case n8n.DependencyCredential, n8n.DependencyDataTable, n8n.DependencySubWorkflow, n8n.DependencyErrorWorkflow: + return "uses" + case n8n.DependencyParentWorkflow, n8n.DependencyErrorWorkflowParent, n8n.DependencyAgent: + return "used by" + } + return "-" +} + +// dependencyAPIError names the scope on a 403 and, on a 404, both causes: an +// unknown ID, or an instance that predates the dependency endpoints. +func dependencyAPIError(err error, resolution config.Resolution, target dependencyTarget) error { + switch { + case n8n.IsForbidden(err): + return forbiddenScopeError(err, resolution, target.noun+" dependency lookup", target.scope, target.forbiddenCause, target.resource) + case n8n.IsNotFound(err): + return fmt.Errorf("%s answered 404 for the %s dependency lookup: either the %s does not exist (check the ID with '%s') or the instance does not serve dependency lookups yet (run %s to see what it offers): %w", + resolution.URL, target.noun, target.noun, target.listCommand, discoverHint(target.resource), err) + default: + return apiError(err, resolution, target.resource) + } +} + +func plural(n int, one, many string) string { + if n == 1 { + return one + } + return many +} + +func newWorkflowDependenciesCommand(opts Options) *cobra.Command { + return newDependencyCommand(opts, dependencyTarget{ + noun: "workflow", + label: "Workflow", + group: "workflow", + idArg: "workflow-id", + placeholder: "WORKFLOW_ID", + listCommand: "n8n workflow list", + resource: workflowResource, + scope: workflowScope(dependencyAction), + forbiddenCause: "a 403 can also mean no access to the workflow's project.", + short: "List what a workflow uses and what uses it", + long: "List the dependencies of one workflow in both directions: the credentials, data\n" + + "tables, sub-workflows and error workflow it uses, and the workflows and agents\n" + + "that use it, as a sub-workflow or as their error workflow. Check this before\n" + + "archiving, deleting or transferring a workflow. Requires workflow:read.", + validate: func(id string) error { return validateWorkflowArgument("workflow ID", id) }, + client: Options.apiClient, + fetch: func(c *n8n.Client) n8n.DependencyFunc { return c.WorkflowDependencies }, + }) +} + +func newCredentialDependenciesCommand(opts Options) *cobra.Command { + return newDependencyCommand(opts, dependencyTarget{ + noun: "credential", + label: "Credential", + group: "credential", + idArg: "credential-id", + placeholder: "CREDENTIAL_ID", + listCommand: "n8n credential list", + resource: credentialResource, + scope: credentialScope(dependencyAction), + forbiddenCause: "a 403 can also mean no access to the credential's project.", + short: "List the workflows and agents that use a credential", + long: "List the workflows and agents that use one credential. Check this before\n" + + "deleting, transferring or rotating a credential. Only metadata is returned;\n" + + "credential data is never requested. Requires credential:read.", + validate: validateCredentialArgument, + client: Options.apiClient, + fetch: func(c *n8n.Client) n8n.DependencyFunc { return c.CredentialDependencies }, + }) +} + +func newDataTableDependenciesCommand(opts Options) *cobra.Command { + return newDependencyCommand(opts, dependencyTarget{ + noun: "data table", + label: "Data table", + group: "data-table", + idArg: "table-id", + placeholder: "TABLE_ID", + listCommand: "n8n data-table list", + resource: dataTableResource, + scope: dataTableScope(dependencyAction), + forbiddenCause: "a 403 can also mean the instance is not licensed for data tables.", + short: "List the workflows that use a data table", + long: "List the workflows that use one data table. Check this before deleting the\n" + + "table, clearing its rows or changing its columns. Like every data-table\n" + + "command it requires API-key authentication, and it requires dataTable:read.", + validate: func(id string) error { return validateDataTableArgument("data table ID", id) }, + client: Options.dataTableClient, + fetch: func(c *n8n.Client) n8n.DependencyFunc { return c.DataTableDependencies }, + }) +} diff --git a/internal/cli/dependency_test.go b/internal/cli/dependency_test.go new file mode 100644 index 0000000..fe544ec --- /dev/null +++ b/internal/cli/dependency_test.go @@ -0,0 +1,227 @@ +package cli + +import ( + "net/http" + "strings" + "testing" + + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" +) + +const cliDependencyPage = `{ + "data":[ + {"type":"credential","id":"cred-1","name":"GitHub","projectId":"project-1"}, + {"type":"parentWorkflow","id":"wf-2","name":"Caller"} + ], + "nextCursor":"next/one?x=1", + "inaccessibleCount":3 +}` + +// dependencyCommands is one entry per dependency lookup: the argv prefix, the +// escaped request path for ID "a/b", and the names its messages must use. +var dependencyCommands = []struct { + name string + args []string + escaped string + label string + scope string + list string + discover string +}{ + {name: "workflow", args: []string{"workflow", "dependencies"}, escaped: "/workflows/a%2Fb/dependencies", label: "Workflow:", scope: "workflow:read", list: "'n8n workflow list'", discover: "discover --resource workflow"}, + {name: "credential", args: []string{"credential", "dependencies"}, escaped: "/credentials/a%2Fb/dependencies", label: "Credential:", scope: "credential:read", list: "'n8n credential list'", discover: "discover --resource credential"}, + {name: "data table", args: []string{"data-table", "dependencies"}, escaped: "/data-tables/a%2Fb/dependencies", label: "Data table:", scope: "dataTable:read", list: "'n8n data-table list'", discover: "discover --resource datatable"}, +} + +func dependencyArgs(prefix []string, rest ...string) []string { + return append(append([]string(nil), prefix...), rest...) +} + +func TestDependenciesTextOutputAndRequest(t *testing.T) { + for _, tc := range dependencyCommands { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + f.login() + f.body = cliDependencyPage + got := f.run(dependencyArgs(tc.args, "a/b", "--limit", "25", "--cursor", "start/one")...) + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{ + tc.label, "a/b", "Dependencies: 2", "Inaccessible: 3", + "RELATION", "uses", "credential", "cred-1", "GitHub", "project-1", + "used by", "parentWorkflow", "wf-2", "Caller", + "Next cursor:", "next/one?x=1", + } { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + if !strings.Contains(got.stderr, "3 dependencies are not listed") { + t.Errorf("stderr = %q, want the inaccessible note", got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodGet || req.URL.EscapedPath() != n8n.BasePath+tc.escaped { + t.Errorf("request = %s %s, want GET %s", req.Method, req.URL.EscapedPath(), n8n.BasePath+tc.escaped) + } + if q := req.URL.Query(); q.Get("limit") != "25" || q.Get("cursor") != "start/one" { + t.Errorf("query = %q", req.URL.RawQuery) + } + }) + } +} + +func TestDependenciesJSONIsTheAPIPage(t *testing.T) { + for _, tc := range dependencyCommands { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + f.login() + f.body = cliDependencyPage + got := f.run(dependencyArgs(tc.args, "a/b", "--output", "json")...) + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + assertCLIJSON(t, cliDependencyPage, got.stdout) + if got.stderr != "" { + t.Errorf("stderr = %q, want empty for JSON output", got.stderr) + } + if f.lastRequest().URL.RawQuery != "" { + t.Errorf("query = %q, want none without pagination flags", f.lastRequest().URL.RawQuery) + } + }) + } +} + +func TestDependenciesEmptyResultHintsOnStderr(t *testing.T) { + f := newFixture(t) + f.login() + f.body = `{"data":[],"nextCursor":null,"inaccessibleCount":0}` + got := f.run("credential", "dependencies", "cred-1") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if !strings.Contains(got.stdout, "Dependencies: 0") || strings.Contains(got.stdout, "RELATION") || strings.Contains(got.stdout, "Next cursor") { + t.Errorf("stdout = %q", got.stdout) + } + if !strings.Contains(got.stderr, "No dependencies") { + t.Errorf("stderr = %q, want the empty-result hint", got.stderr) + } + + got = f.run("credential", "dependencies", "cred-1", "--output", "json") + assertCLIJSON(t, `{"data":[],"nextCursor":"","inaccessibleCount":0}`, got.stdout) +} + +func TestDependenciesAllFollowsCursorAndKeepsInaccessibleCount(t *testing.T) { + f := newFixture(t) + f.login() + f.bodyFunc = func(page int) string { + if page == 0 { + return `{"data":[{"type":"parentWorkflow","id":"wf-1","name":"One"}],"nextCursor":"next","inaccessibleCount":4}` + } + return `{"data":[{"type":"agent","id":"agent-1","name":"Helper"}],"nextCursor":null,"inaccessibleCount":4}` + } + before := f.requestCount() + got := f.run("workflow", "dependencies", "wf-0", "--all", "--limit", "1", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + assertCLIJSON(t, `{ + "data":[ + {"type":"parentWorkflow","id":"wf-1","name":"One"}, + {"type":"agent","id":"agent-1","name":"Helper"} + ], + "nextCursor":"", + "inaccessibleCount":4, + "collection":{"truncated":false,"limit":10000} +}`, got.stdout) + if n := f.requestCount() - before; n != 2 { + t.Fatalf("requests = %d, want 2", n) + } + if q := f.lastRequest().URL.Query(); q.Get("cursor") != "next" || q.Get("limit") != "1" { + t.Errorf("second query = %q, want the returned cursor and the same limit", f.lastRequest().URL.RawQuery) + } +} + +func TestDependenciesErrorsNameScopeAndListCommand(t *testing.T) { + for _, tc := range dependencyCommands { + t.Run(tc.name, func(t *testing.T) { + for _, tt := range []struct { + status int + want []string + }{ + {status: http.StatusForbidden, want: []string{"403", tc.scope, tc.discover}}, + {status: http.StatusNotFound, want: []string{"404", tc.list, tc.discover}}, + {status: http.StatusUnauthorized, want: []string{"401", "auth login"}}, + } { + f := newFixture(t) + f.login() + f.status = tt.status + got := f.run(dependencyArgs(tc.args, "id-1")...) + if got.code != ExitError || got.stdout != "" { + t.Errorf("%d: result = %+v, want error with empty stdout", tt.status, got) + } + for _, want := range tt.want { + if !strings.Contains(got.stderr, want) { + t.Errorf("%d: stderr = %q, want %q", tt.status, got.stderr, want) + } + } + } + }) + } +} + +func TestDependenciesValidateBeforeRequest(t *testing.T) { + for _, tc := range dependencyCommands { + t.Run(tc.name, func(t *testing.T) { + for _, tt := range []struct { + args []string + want string + }{ + {args: []string{""}, want: "ID is required"}, + {args: []string{" id-1"}, want: "must not start or end with whitespace"}, + {args: []string{"id-1", "--limit", "251"}, want: "limit must not exceed 250"}, + {args: []string{"id-1", "--limit", "-1"}, want: "limit must not be negative"}, + {args: []string{"id-1", "--output", "yaml"}, want: "output"}, + {args: []string{}, want: "accepts 1 arg"}, + } { + f := newFixture(t) + f.login() + f.body = cliDependencyPage + before := f.requestCount() + got := f.run(dependencyArgs(tc.args, tt.args...)...) + if got.code == ExitSuccess || !strings.Contains(got.stderr, tt.want) { + t.Errorf("%v: result = %+v, want error containing %q", tt.args, got, tt.want) + } + if f.requestCount() != before { + t.Errorf("%v: invalid invocation reached instance", tt.args) + } + } + }) + } +} + +func TestDataTableDependenciesRequiresAPIKey(t *testing.T) { + f := newFixture(t) + f.env[config.EnvURL] = f.server.URL + f.env[config.EnvBearerToken] = "not-an-api-key" + got := f.run("data-table", "dependencies", "table-1") + if got.code != ExitError || !strings.Contains(got.stderr, "API-key") { + t.Errorf("result = %+v, want the API-key requirement", got) + } + if f.requestCount() != 0 { + t.Error("non-API-key command reached instance") + } +} + +func TestDependencyRelation(t *testing.T) { + for kind, want := range map[string]string{ + "credential": "uses", "dataTable": "uses", "subWorkflow": "uses", "errorWorkflow": "uses", + "parentWorkflow": "used by", "errorWorkflowParent": "used by", "agent": "used by", + "somethingNew": "-", + } { + if got := dependencyRelation(kind); got != want { + t.Errorf("dependencyRelation(%q) = %q, want %q", kind, got, want) + } + } +} diff --git a/internal/cli/help_test.go b/internal/cli/help_test.go index 5a1e1a8..18d7b35 100644 --- a/internal/cli/help_test.go +++ b/internal/cli/help_test.go @@ -147,10 +147,12 @@ func TestHelpSucceedsAtEveryLevel(t *testing.T) { {"folder", "get"}, {"folder", "update"}, {"folder", "delete"}, + {"credential", "dependencies"}, {"data-table"}, {"data-table", "list"}, {"data-table", "create"}, {"data-table", "get"}, + {"data-table", "dependencies"}, {"data-table", "update"}, {"data-table", "delete"}, {"data-table", "row"}, @@ -168,6 +170,7 @@ func TestHelpSucceedsAtEveryLevel(t *testing.T) { {"workflow"}, {"workflow", "list"}, {"workflow", "get"}, + {"workflow", "dependencies"}, {"workflow", "diff"}, {"workflow", "copy"}, {"workflow", "create"}, diff --git a/internal/cli/scope_test.go b/internal/cli/scope_test.go index f4ca24e..97a8ec1 100644 --- a/internal/cli/scope_test.go +++ b/internal/cli/scope_test.go @@ -69,6 +69,7 @@ func TestScopeMappersMatchManifest(t *testing.T) { {"n8n credential list", credentialScope("list")}, {"n8n credential get", credentialScope("get")}, + {"n8n credential dependencies", credentialScope(dependencyAction)}, {"n8n credential test", credentialScope("test")}, {"n8n credential create", credentialScope("create")}, {"n8n credential update", credentialScope("update")}, @@ -77,6 +78,7 @@ func TestScopeMappersMatchManifest(t *testing.T) { {"n8n data-table list", dataTableScope("list")}, {"n8n data-table get", dataTableScope("read")}, + {"n8n data-table dependencies", dataTableScope(dependencyAction)}, {"n8n data-table create", dataTableScope("create")}, {"n8n data-table update", dataTableScope("update")}, {"n8n data-table delete", dataTableScope("delete")}, @@ -94,6 +96,7 @@ func TestScopeMappersMatchManifest(t *testing.T) { {"n8n workflow list", workflowScope("list")}, {"n8n workflow get", workflowScope("read")}, {"n8n workflow get", workflowScope("get")}, + {"n8n workflow dependencies", workflowScope(dependencyAction)}, {"n8n workflow create", workflowScope("create")}, {"n8n workflow update", workflowScope("update")}, {"n8n workflow delete", workflowScope("delete")}, diff --git a/internal/cli/workflow.go b/internal/cli/workflow.go index 15ad2a1..295fad1 100644 --- a/internal/cli/workflow.go +++ b/internal/cli/workflow.go @@ -67,6 +67,7 @@ func newWorkflowCommand(opts Options) *cobra.Command { newWorkflowUnpublishCommand(opts), newWorkflowTransferCommand(opts), newWorkflowHistoryCommand(opts), + newWorkflowDependenciesCommand(opts), newWorkflowVersionCommand(opts), newWorkflowTagCommand(opts), newWorkflowActivateCommand(opts), @@ -1449,7 +1450,7 @@ func workflowScope(action string) scopeNeed { switch action { case "list": return allOf("workflow:list") - case "read", "get": + case "read", "get", dependencyAction: return allOf("workflow:read") case "create": return allOf("workflow:create") diff --git a/internal/coverage/coverage_test.go b/internal/coverage/coverage_test.go index d3a5172..5160be6 100644 --- a/internal/coverage/coverage_test.go +++ b/internal/coverage/coverage_test.go @@ -327,7 +327,7 @@ func TestAvailabilityMatchesSpecs(t *testing.T) { // // A phase is never excused because one server does not serve its resource: // every phase owns operations from the union of the documents. -const deliveredThrough = 33 +const deliveredThrough = 34 // TestPhaseCounts is how a phase exit gate reads the manifest: every operation // a delivered phase owns must be implemented, and no later phase may have diff --git a/internal/coverage/manifest.json b/internal/coverage/manifest.json index 426ec28..2e162ab 100644 --- a/internal/coverage/manifest.json +++ b/internal/coverage/manifest.json @@ -2035,8 +2035,8 @@ "scope": "workflow:read", "availability": "upstream-only", "phase": 34, - "command": "", - "status": "planned" + "command": "n8n workflow dependencies", + "status": "implemented" }, { "operationId": "getCredentialDependencies", @@ -2046,8 +2046,8 @@ "scope": "credential:read", "availability": "upstream-only", "phase": 34, - "command": "", - "status": "planned" + "command": "n8n credential dependencies", + "status": "implemented" }, { "operationId": "getDataTableDependencies", @@ -2057,8 +2057,8 @@ "scope": "dataTable:read", "availability": "upstream-only", "phase": 34, - "command": "", - "status": "planned" + "command": "n8n data-table dependencies", + "status": "implemented" }, { "operationId": "getPromotionEnvironments", diff --git a/internal/n8n/credential.go b/internal/n8n/credential.go index 4b08710..8d722a6 100644 --- a/internal/n8n/credential.go +++ b/internal/n8n/credential.go @@ -350,3 +350,12 @@ func redactCredentialAPIError(err error) error { clone.Truncated = false return &clone } + +// CredentialDependencies returns one page of the workflows and agents that use +// the credential. No credential data is requested or returned. +func (c *Client) CredentialDependencies(ctx context.Context, id string, opts ListOptions) (DependencyPage, error) { + if err := validateCredentialID(id); err != nil { + return DependencyPage{}, err + } + return c.listDependencies(ctx, PathJoin("credentials", id, "dependencies"), opts) +} diff --git a/internal/n8n/datatable.go b/internal/n8n/datatable.go index 4ee4f39..076d406 100644 --- a/internal/n8n/datatable.go +++ b/internal/n8n/datatable.go @@ -924,3 +924,12 @@ func isBareWord(trimmed string) bool { } return trimmed != "true" && trimmed != "false" && trimmed != "null" } + +// DataTableDependencies returns one page of the workflows that use the data +// table. +func (c *Client) DataTableDependencies(ctx context.Context, id string, opts ListOptions) (DependencyPage, error) { + if err := validateDataTableID(id); err != nil { + return DependencyPage{}, err + } + return c.listDependencies(ctx, PathJoin("data-tables", id, "dependencies"), opts) +} diff --git a/internal/n8n/dependency.go b/internal/n8n/dependency.go new file mode 100644 index 0000000..cf0b7b8 --- /dev/null +++ b/internal/n8n/dependency.go @@ -0,0 +1,89 @@ +package n8n + +import ( + "context" + "fmt" +) + +// Dependency types the API reports. The type names the relation to the +// requested resource, not only the kind of the listed one. +const ( + // DependencyAgent is an agent that uses the requested resource. + DependencyAgent = "agent" + // DependencyCredential is a credential the requested workflow uses. + DependencyCredential = "credential" + // DependencyDataTable is a data table the requested workflow uses. + DependencyDataTable = "dataTable" + // DependencyErrorWorkflow is the error workflow the requested workflow uses. + DependencyErrorWorkflow = "errorWorkflow" + // DependencyErrorWorkflowParent is a workflow that uses the requested + // workflow as its error workflow. + DependencyErrorWorkflowParent = "errorWorkflowParent" + // DependencyParentWorkflow is a workflow that uses the requested resource. + DependencyParentWorkflow = "parentWorkflow" + // DependencySubWorkflow is a sub-workflow the requested workflow calls. + DependencySubWorkflow = "subWorkflow" +) + +// MaxDependencyLimit is the largest page size the dependency endpoints accept. +const MaxDependencyLimit = 250 + +// Dependency is one entry of a dependency list: a resource related to the +// requested workflow, credential or data table. +type Dependency struct { + Type string `json:"type"` + ID string `json:"id"` + Name string `json:"name"` + // ProjectID is the owning project, when the server knows it. + ProjectID string `json:"projectId,omitempty"` +} + +// DependencyPage is one cursor-paginated dependency list. The three +// dependency endpoints share this shape. +type DependencyPage struct { + Data []Dependency `json:"data"` + NextCursor string `json:"nextCursor"` + // InaccessibleCount is how many dependencies exist that the caller may not + // see; they are not listed. It counts the whole list, not this page. + InaccessibleCount int `json:"inaccessibleCount"` +} + +// HasMore reports whether another page is available. +func (p DependencyPage) HasMore() bool { return p.NextCursor != "" } + +// Page returns the entries and cursor as a generic page, for the shared +// pagination helpers. +func (p DependencyPage) Page() Page[Dependency] { + return Page[Dependency]{Data: p.Data, NextCursor: p.NextCursor} +} + +// DependencyFunc fetches one dependency page of the resource with the given ID. +type DependencyFunc func(ctx context.Context, id string, opts ListOptions) (DependencyPage, error) + +// listDependencies fetches one dependency page from path. Callers validate the +// resource ID; options are checked here, before any request. +func (c *Client) listDependencies(ctx context.Context, path string, opts ListOptions) (DependencyPage, error) { + if err := ValidateDependencyOptions(opts); err != nil { + return DependencyPage{}, err + } + var page DependencyPage + if _, err := c.Do(ctx, Request{Path: path, Query: opts.Apply(nil)}, &page); err != nil { + return DependencyPage{}, err + } + if page.Data == nil { + page.Data = []Dependency{} + } + return page, nil +} + +// ValidateDependencyOptions rejects pagination the dependency endpoints +// refuse: a negative limit or one above [MaxDependencyLimit]. +func ValidateDependencyOptions(opts ListOptions) error { + if err := opts.Validate(); err != nil { + return err + } + if opts.Limit > MaxDependencyLimit { + return fmt.Errorf("limit must not exceed %d, got %d", MaxDependencyLimit, opts.Limit) + } + return nil +} diff --git a/internal/n8n/dependency_test.go b/internal/n8n/dependency_test.go new file mode 100644 index 0000000..939a3cb --- /dev/null +++ b/internal/n8n/dependency_test.go @@ -0,0 +1,133 @@ +package n8n + +import ( + "context" + "net/http" + "strings" + "testing" +) + +const dependencyResponse = `{ + "data":[ + {"type":"credential","id":"cred1","name":"GitHub","projectId":"project1"}, + {"type":"parentWorkflow","id":"wf2","name":"Caller"} + ], + "nextCursor":"next one", + "inaccessibleCount":2 +}` + +// TestDependencyLookups covers the three dependency endpoints: method, escaped +// path, pagination query, and the shared response shape. +func TestDependencyLookups(t *testing.T) { + tests := []struct { + name string + call func(*Client, context.Context, string, ListOptions) (DependencyPage, error) + id string + escaped string + }{ + {name: "workflow", call: (*Client).WorkflowDependencies, id: "wf/one?x=1", escaped: "/workflows/wf%2Fone%3Fx=1/dependencies"}, + {name: "credential", call: (*Client).CredentialDependencies, id: "cred/one?x=1", escaped: "/credentials/cred%2Fone%3Fx=1/dependencies"}, + {name: "data table", call: (*Client).DataTableDependencies, id: "table/one?x=1", escaped: "/data-tables/table%2Fone%3Fx=1/dependencies"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, dependencyResponse)) + page, err := tt.call(server.client(t), context.Background(), tt.id, ListOptions{Limit: 25, Cursor: "start one"}) + if err != nil { + t.Fatalf("call: %v", err) + } + req, body := server.last(t) + if req.Method != http.MethodGet || req.URL.EscapedPath() != BasePath+tt.escaped { + t.Errorf("request = %s %s, want GET %s", req.Method, req.URL.EscapedPath(), BasePath+tt.escaped) + } + if req.URL.Query().Get("limit") != "25" || req.URL.Query().Get("cursor") != "start one" { + t.Errorf("query = %q, want pagination", req.URL.RawQuery) + } + if body != "" { + t.Errorf("body = %q, want empty", body) + } + if len(page.Data) != 2 || page.NextCursor != "next one" || page.InaccessibleCount != 2 || !page.HasMore() { + t.Fatalf("page = %+v", page) + } + first, second := page.Data[0], page.Data[1] + if first != (Dependency{Type: DependencyCredential, ID: "cred1", Name: "GitHub", ProjectID: "project1"}) { + t.Errorf("first = %+v", first) + } + if second != (Dependency{Type: DependencyParentWorkflow, ID: "wf2", Name: "Caller"}) { + t.Errorf("second = %+v", second) + } + generic := page.Page() + if len(generic.Data) != 2 || generic.NextCursor != "next one" { + t.Errorf("Page() = %+v", generic) + } + }) + } +} + +// TestDependencyLastPage decodes a null cursor and an empty list into the +// documented zero values, so callers never see a nil slice. +func TestDependencyLastPage(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"data":[],"nextCursor":null,"inaccessibleCount":0}`)) + page, err := server.client(t).WorkflowDependencies(context.Background(), "wf1", ListOptions{}) + if err != nil { + t.Fatalf("WorkflowDependencies: %v", err) + } + if page.Data == nil || len(page.Data) != 0 || page.HasMore() || page.InaccessibleCount != 0 { + t.Errorf("page = %+v", page) + } + req, _ := server.last(t) + if req.URL.RawQuery != "" { + t.Errorf("query = %q, want none for default options", req.URL.RawQuery) + } +} + +func TestDependencyValidationBeforeRequest(t *testing.T) { + tests := []struct { + name string + call func(*Client) error + want string + }{ + {name: "workflow ID", want: "workflow ID is required", call: func(c *Client) error { + _, err := c.WorkflowDependencies(context.Background(), " ", ListOptions{}) + return err + }}, + {name: "credential ID", want: "credential ID must not start or end with whitespace", call: func(c *Client) error { + _, err := c.CredentialDependencies(context.Background(), " cred", ListOptions{}) + return err + }}, + {name: "data table ID", want: "data table ID is required", call: func(c *Client) error { + _, err := c.DataTableDependencies(context.Background(), "", ListOptions{}) + return err + }}, + {name: "negative limit", want: "limit must not be negative", call: func(c *Client) error { + _, err := c.WorkflowDependencies(context.Background(), "wf1", ListOptions{Limit: -1}) + return err + }}, + {name: "limit above maximum", want: "limit must not exceed 250", call: func(c *Client) error { + _, err := c.CredentialDependencies(context.Background(), "cred1", ListOptions{Limit: 251}) + return err + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, dependencyResponse)) + err := tt.call(server.client(t)) + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Errorf("err = %v, want %q", err, tt.want) + } + if len(server.requests) != 0 { + t.Errorf("%d requests reached server, want none", len(server.requests)) + } + }) + } +} + +func TestDependencyErrorsKeepStatus(t *testing.T) { + for _, status := range []int{http.StatusForbidden, http.StatusNotFound} { + server := newCommunityPackageServer(t, packageJSONHandler(status, `{"message":"denied"}`)) + _, err := server.client(t).DataTableDependencies(context.Background(), "table1", ListOptions{}) + if StatusCodeOf(err) != status { + t.Errorf("status = %d, want %d (err %v)", StatusCodeOf(err), status, err) + } + } +} diff --git a/internal/n8n/workflow.go b/internal/n8n/workflow.go index 9d71f05..29d4494 100644 --- a/internal/n8n/workflow.go +++ b/internal/n8n/workflow.go @@ -776,3 +776,13 @@ func validateWorkflowText(field, value string, required bool) error { } return nil } + +// WorkflowDependencies returns one page of what the workflow uses (credentials, +// data tables, sub-workflows, its error workflow) and what uses it (parent +// workflows, workflows that use it as error workflow, agents). +func (c *Client) WorkflowDependencies(ctx context.Context, id string, opts ListOptions) (DependencyPage, error) { + if err := validateWorkflowID(id); err != nil { + return DependencyPage{}, err + } + return c.listDependencies(ctx, PathJoin("workflows", id, "dependencies"), opts) +} diff --git a/test/integration/dependency_test.go b/test/integration/dependency_test.go new file mode 100644 index 0000000..6e2df36 --- /dev/null +++ b/test/integration/dependency_test.go @@ -0,0 +1,130 @@ +package integration_test + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/SomeoneWithOptions/n8n-cli/internal/cli" + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" + "github.com/SomeoneWithOptions/n8n-cli/internal/version" + "github.com/SomeoneWithOptions/n8n-cli/test/integration" +) + +// dependencyTypes are the relation types the API documents. +var dependencyTypes = map[string]bool{ + n8n.DependencyAgent: true, n8n.DependencyCredential: true, n8n.DependencyDataTable: true, + n8n.DependencyErrorWorkflow: true, n8n.DependencyErrorWorkflowParent: true, + n8n.DependencyParentWorkflow: true, n8n.DependencySubWorkflow: true, +} + +// checkDependencyPage validates one live page, skipping when the instance +// predates the dependency endpoints (a 404 for an ID that was just listed). +func checkDependencyPage(t *testing.T, what string, page n8n.DependencyPage, err error) { + t.Helper() + if n8n.IsNotFound(err) { + t.Skipf("%s dependencies: instance answered 404 for a listed ID; it does not serve dependency lookups: %v", what, err) + } + if err != nil { + t.Fatalf("%s dependencies: %v", what, err) + } + if page.Data == nil || page.InaccessibleCount < 0 { + t.Errorf("%s dependencies: page = %+v", what, page) + } + for _, dep := range page.Data { + if dep.ID == "" || !dependencyTypes[dep.Type] { + t.Errorf("%s dependency has no ID or an undocumented type: %+v", what, dep) + } + } + t.Logf("%s has %d listed and %d inaccessible dependency(ies)", what, len(page.Data), page.InaccessibleCount) +} + +// TestDependencyLookups is read-only: it looks up the dependencies of the first +// existing workflow, credential and data table, skipping any kind the instance +// has none of. +func TestDependencyLookups(t *testing.T) { + instance := integration.Require(t) + client := instance.Client(t) + ctx := context.Background() + + t.Run("workflow", func(t *testing.T) { + list, err := client.ListWorkflows(ctx, n8n.ListWorkflowsOptions{ListOptions: n8n.ListOptions{Limit: 1}, ExcludePinnedData: true}) + if err != nil { + t.Fatalf("ListWorkflows: %v", err) + } + if len(list.Data) == 0 { + t.Skip("instance has no workflow to look up") + } + page, err := client.WorkflowDependencies(ctx, list.Data[0].ID, n8n.ListOptions{Limit: 10}) + checkDependencyPage(t, "workflow", page, err) + }) + t.Run("credential", func(t *testing.T) { + list, err := client.ListCredentials(ctx, n8n.ListOptions{Limit: 1}) + if err != nil { + t.Skipf("ListCredentials needs an owner or admin key: %v", err) + } + if len(list.Data) == 0 { + t.Skip("instance has no credential to look up") + } + page, err := client.CredentialDependencies(ctx, list.Data[0].ID, n8n.ListOptions{Limit: 10}) + checkDependencyPage(t, "credential", page, err) + }) + t.Run("data table", func(t *testing.T) { + list, err := client.ListDataTables(ctx, n8n.ListDataTablesOptions{ListOptions: n8n.ListOptions{Limit: 1}}) + if err != nil { + t.Skipf("ListDataTables: %v", err) + } + if len(list.Data) == 0 { + t.Skip("instance has no data table to look up") + } + page, err := client.DataTableDependencies(ctx, list.Data[0].ID, n8n.ListOptions{Limit: 10}) + checkDependencyPage(t, "data table", page, err) + }) +} + +// TestWorkflowDependenciesCommand checks the JSON page through the full CLI. +func TestWorkflowDependenciesCommand(t *testing.T) { + instance := integration.Require(t) + list, err := instance.Client(t).ListWorkflows(context.Background(), n8n.ListWorkflowsOptions{ListOptions: n8n.ListOptions{Limit: 1}, ExcludePinnedData: true}) + if err != nil { + t.Fatalf("ListWorkflows: %v", err) + } + if len(list.Data) == 0 { + t.Skip("instance has no workflow to look up") + } + env := map[string]string{config.EnvURL: instance.URL, config.EnvAPIKey: instance.APIKey.Reveal()} + interactive := false + var out, errOut strings.Builder + code := cli.Run(context.Background(), []string{"workflow", "dependencies", list.Data[0].ID, "--all", "--output", "json"}, cli.Options{ + Streams: cli.Streams{In: strings.NewReader(""), Out: &out, Err: &errOut}, + Version: version.Get(), + ConfigDir: t.TempDir(), + Env: func(name string) string { return env[name] }, + Keyring: config.NewMemoryStore(config.StorageKeyring), + Interactive: &interactive, + }) + if code != cli.ExitSuccess && strings.Contains(errOut.String(), "404") { + t.Skipf("instance does not serve dependency lookups: %s", errOut.String()) + } + if code != cli.ExitSuccess { + t.Fatalf("workflow dependencies exit = %d, want %d (stderr: %s)", code, cli.ExitSuccess, errOut.String()) + } + var page struct { + Data []n8n.Dependency `json:"data"` + InaccessibleCount *int `json:"inaccessibleCount"` + Collection *struct { + Truncated bool `json:"truncated"` + } `json:"collection"` + } + if err := json.Unmarshal([]byte(out.String()), &page); err != nil { + t.Fatalf("stdout is not dependency page JSON: %v\n%s", err, out.String()) + } + if page.Data == nil || page.InaccessibleCount == nil || page.Collection == nil { + t.Errorf("JSON lacks data, inaccessibleCount or collection: %s", out.String()) + } + if strings.Contains(out.String()+errOut.String(), instance.APIKey.Reveal()) { + t.Error("API key leaked into output") + } +}