diff --git a/docs/README.md b/docs/README.md index e58dab6..22fa57a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,6 +22,22 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n credential test`](n8n_credential_test.md) | Test stored credential data | | [`n8n credential transfer`](n8n_credential_transfer.md) | Transfer a credential to another project | | [`n8n credential update`](n8n_credential_update.md) | Update a credential from secret JSON | +| [`n8n credential-policy attachment get`](n8n_credential-policy_attachment_get.md) | Get credential type policy attachments | +| [`n8n credential-policy attachment set`](n8n_credential-policy_attachment_set.md) | Replace credential type policy attachments | +| [`n8n credential-policy attachment`](n8n_credential-policy_attachment.md) | Manage attached credential type policy documents | +| [`n8n credential-policy document create`](n8n_credential-policy_document_create.md) | Create credential type policy documents | +| [`n8n credential-policy document delete`](n8n_credential-policy_document_delete.md) | Delete credential type policy documents | +| [`n8n credential-policy document get`](n8n_credential-policy_document_get.md) | Get credential type policy documents | +| [`n8n credential-policy document list`](n8n_credential-policy_document_list.md) | List credential type policy documents | +| [`n8n credential-policy document set`](n8n_credential-policy_document_set.md) | Replace credential type policy documents | +| [`n8n credential-policy document`](n8n_credential-policy_document.md) | Manage reusable credential type policy documents | +| [`n8n credential-policy instance get`](n8n_credential-policy_instance_get.md) | Get the instance credential type policy | +| [`n8n credential-policy instance set`](n8n_credential-policy_instance_set.md) | Replace the instance credential type policy | +| [`n8n credential-policy instance`](n8n_credential-policy_instance.md) | Manage instance credential type policies | +| [`n8n credential-policy project get`](n8n_credential-policy_project_get.md) | Get the project credential type policy | +| [`n8n credential-policy project set`](n8n_credential-policy_project_set.md) | Replace the project credential type policy | +| [`n8n credential-policy project`](n8n_credential-policy_project.md) | Manage project credential type policies | +| [`n8n credential-policy`](n8n_credential-policy.md) | Manage credential type availability policies | | [`n8n credential`](n8n_credential.md) | Manage node credentials without exposing secrets | | [`n8n data-table column create`](n8n_data-table_column_create.md) | Add a column to a data table | | [`n8n data-table column delete`](n8n_data-table_column_delete.md) | Permanently delete a column and its data | @@ -97,6 +113,15 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n log-stream event-type list`](n8n_log-stream_event-type_list.md) | List event names available for streaming | | [`n8n log-stream event-type`](n8n_log-stream_event-type.md) | Inspect streamable event types | | [`n8n log-stream`](n8n_log-stream.md) | Manage licensed log streaming destinations | +| [`n8n node-policy attachment get`](n8n_node-policy_attachment_get.md) | Get node type policy attachments | +| [`n8n node-policy attachment set`](n8n_node-policy_attachment_set.md) | Replace node type policy attachments | +| [`n8n node-policy attachment`](n8n_node-policy_attachment.md) | Manage attached node type policy documents | +| [`n8n node-policy document create`](n8n_node-policy_document_create.md) | Create node type policy documents | +| [`n8n node-policy document delete`](n8n_node-policy_document_delete.md) | Delete node type policy documents | +| [`n8n node-policy document get`](n8n_node-policy_document_get.md) | Get node type policy documents | +| [`n8n node-policy document list`](n8n_node-policy_document_list.md) | List node type policy documents | +| [`n8n node-policy document set`](n8n_node-policy_document_set.md) | Replace node type policy documents | +| [`n8n node-policy document`](n8n_node-policy_document.md) | Manage reusable node type policy documents | | [`n8n node-policy instance get`](n8n_node-policy_instance_get.md) | Get the instance node type policy | | [`n8n node-policy instance set`](n8n_node-policy_instance_set.md) | Fully replace the instance node type policy | | [`n8n node-policy instance`](n8n_node-policy_instance.md) | Manage the instance node type policy | diff --git a/docs/n8n.md b/docs/n8n.md index 9b04f93..d57938b 100644 --- a/docs/n8n.md +++ b/docs/n8n.md @@ -55,6 +55,7 @@ n8n [flags] * [n8n completion](n8n_completion.md) - Generate a shell completion script * [n8n config](n8n_config.md) - Inspect and edit stored CLI configuration * [n8n credential](n8n_credential.md) - Manage node credentials without exposing secrets +* [n8n credential-policy](n8n_credential-policy.md) - Manage credential type availability policies * [n8n data-table](n8n_data-table.md) - Manage data tables, their rows and their columns * [n8n discover](n8n_discover.md) - List the API capabilities available to the current credential * [n8n evaluation](n8n_evaluation.md) - Run and inspect workflow evaluations diff --git a/docs/n8n_credential-policy.md b/docs/n8n_credential-policy.md new file mode 100644 index 0000000..1131337 --- /dev/null +++ b/docs/n8n_credential-policy.md @@ -0,0 +1,33 @@ +## n8n credential-policy + +Manage credential type availability policies + +### Synopsis + +Manage instance and project credential type policies. Start with 'instance get', then inspect 'attachment get' before editing scopes with shared documents. GET returns composed rules; scope set replaces only the scope's own document and default. Documents are reusable rule lists. Floor attachments run first, then priority ascending within each group. The first matching rule wins. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy [flags] +``` + +### Examples + +``` + n8n credential-policy instance get + n8n credential-policy document list +``` + +### Options + +``` + -h, --help help for credential-policy +``` + +### SEE ALSO + +* [n8n](n8n.md) - Command-line client for the n8n API +* [n8n credential-policy attachment](n8n_credential-policy_attachment.md) - Manage attached credential type policy documents +* [n8n credential-policy document](n8n_credential-policy_document.md) - Manage reusable credential type policy documents +* [n8n credential-policy instance](n8n_credential-policy_instance.md) - Manage instance credential type policies +* [n8n credential-policy project](n8n_credential-policy_project.md) - Manage project credential type policies + diff --git a/docs/n8n_credential-policy_attachment.md b/docs/n8n_credential-policy_attachment.md new file mode 100644 index 0000000..93dab10 --- /dev/null +++ b/docs/n8n_credential-policy_attachment.md @@ -0,0 +1,31 @@ +## n8n credential-policy attachment + +Manage attached credential type policy documents + +### Synopsis + +Inspect or replace a scope's complete attachment list. Start with 'get'. Obtain SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; it is null until that scope is first written with set. Requires instance-level access even for project scopes. Floor attachments evaluate first, then priority ascending within each group. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy attachment [flags] +``` + +### Examples + +``` + n8n credential-policy instance get --output json + n8n credential-policy attachment get SCOPE_ID +``` + +### Options + +``` + -h, --help help for attachment +``` + +### SEE ALSO + +* [n8n credential-policy](n8n_credential-policy.md) - Manage credential type availability policies +* [n8n credential-policy attachment get](n8n_credential-policy_attachment_get.md) - Get credential type policy attachments +* [n8n credential-policy attachment set](n8n_credential-policy_attachment_set.md) - Replace credential type policy attachments + diff --git a/docs/n8n_credential-policy_attachment_get.md b/docs/n8n_credential-policy_attachment_get.md new file mode 100644 index 0000000..0b57226 --- /dev/null +++ b/docs/n8n_credential-policy_attachment_get.md @@ -0,0 +1,31 @@ +## n8n credential-policy attachment get + +Get credential type policy attachments + +### Synopsis + +Read a scope's attachments and version in evaluation order: floor first, then priority ascending within each group. Get SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; it is null until the scope is first written. Requires instance-level access even for project scopes. Use the returned version with 'attachment set'. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy attachment get [flags] +``` + +### Examples + +``` + n8n credential-policy attachment get SCOPE_ID +``` + +### 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 get + --output string output format: text or json (default: text; JSON contains the full response) (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-policy attachment](n8n_credential-policy_attachment.md) - Manage attached credential type policy documents + diff --git a/docs/n8n_credential-policy_attachment_set.md b/docs/n8n_credential-policy_attachment_set.md new file mode 100644 index 0000000..425191f --- /dev/null +++ b/docs/n8n_credential-policy_attachment_set.md @@ -0,0 +1,34 @@ +## n8n credential-policy attachment set + +Replace credential type policy attachments + +### Synopsis + +Fully replace all attachments using JSON {"attachments":[{"policyId":"POLICY_ID","priority":0,"isFloor":false}],"version":1}. Each policyId and (isFloor,priority) pair must be unique. Use [] to detach every document. Get SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; null means write that scope first. Requires instance-level access even for projects. Delegate documents cannot attach to projects. Use the last-read scope version: stale writes return 409. Replacing attachments changes policy evaluation and bumps the scope version. Interactive runs confirm; non-interactive runs and --input - require --yes. Returns attachments and the new version; read-only rules in GET input are dropped with a stderr diagnostic. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy attachment set [flags] +``` + +### Examples + +``` + n8n credential-policy attachment set SCOPE_ID --input policy.json + n8n credential-policy attachment set SCOPE_ID --input - --yes < policy.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 set + --input string JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes) + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n credential-policy attachment](n8n_credential-policy_attachment.md) - Manage attached credential type policy documents + diff --git a/docs/n8n_credential-policy_document.md b/docs/n8n_credential-policy_document.md new file mode 100644 index 0000000..5b7a4ad --- /dev/null +++ b/docs/n8n_credential-policy_document.md @@ -0,0 +1,34 @@ +## n8n credential-policy document + +Manage reusable credential type policy documents + +### Synopsis + +Manage reusable rule lists. Start with 'list', then 'get' before 'set'. Create produces an unattached document; attach it with 'attachment set'. Updating a document changes every attached scope and bumps their versions. A document containing delegate cannot be attached to a project scope. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy document [flags] +``` + +### Examples + +``` + n8n credential-policy document list + n8n credential-policy document get POLICY_ID --output json +``` + +### Options + +``` + -h, --help help for document +``` + +### SEE ALSO + +* [n8n credential-policy](n8n_credential-policy.md) - Manage credential type availability policies +* [n8n credential-policy document create](n8n_credential-policy_document_create.md) - Create credential type policy documents +* [n8n credential-policy document delete](n8n_credential-policy_document_delete.md) - Delete credential type policy documents +* [n8n credential-policy document get](n8n_credential-policy_document_get.md) - Get credential type policy documents +* [n8n credential-policy document list](n8n_credential-policy_document_list.md) - List credential type policy documents +* [n8n credential-policy document set](n8n_credential-policy_document_set.md) - Replace credential type policy documents + diff --git a/docs/n8n_credential-policy_document_create.md b/docs/n8n_credential-policy_document_create.md new file mode 100644 index 0000000..c1938e1 --- /dev/null +++ b/docs/n8n_credential-policy_document_create.md @@ -0,0 +1,34 @@ +## n8n credential-policy document create + +Create credential type policy documents + +### Synopsis + +Create an unattached reusable document from JSON {"rules":[]}. Rules are required; each rule has a unique id, action allow|deny|delegate, and selector {kind,value}. Creation returns {policy,warnings}; warnings do not fail the write. Attach the returned policy.id using 'attachment set'. --input - requires --yes. Selectors accept name or package. Credential policies also accept extends, matching the named type and every type extending it. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy document create [flags] +``` + +### Examples + +``` + n8n credential-policy document create --input policy.json + n8n credential-policy document create --input - --yes < policy.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 + --input string JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes) + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n credential-policy document](n8n_credential-policy_document.md) - Manage reusable credential type policy documents + diff --git a/docs/n8n_credential-policy_document_delete.md b/docs/n8n_credential-policy_document_delete.md new file mode 100644 index 0000000..a08e7a2 --- /dev/null +++ b/docs/n8n_credential-policy_document_delete.md @@ -0,0 +1,33 @@ +## n8n credential-policy document delete + +Delete credential type policy documents + +### Synopsis + +Permanently delete an unattached document found with 'document list'. Attached documents return 409: inspect 'attachment get' and use 'attachment set' to detach first. Interactive runs confirm; non-interactive runs require --yes. Success returns the deleted ID; deletion cannot be undone. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy document delete [flags] +``` + +### Examples + +``` + n8n credential-policy document delete POLICY_ID + n8n credential-policy document delete POLICY_ID --yes +``` + +### 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 delete + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n credential-policy document](n8n_credential-policy_document.md) - Manage reusable credential type policy documents + diff --git a/docs/n8n_credential-policy_document_get.md b/docs/n8n_credential-policy_document_get.md new file mode 100644 index 0000000..21463a0 --- /dev/null +++ b/docs/n8n_credential-policy_document_get.md @@ -0,0 +1,31 @@ +## n8n credential-policy document get + +Get credential type policy documents + +### Synopsis + +Read a reusable document's ID, kind, ordered rules, version, updater and timestamps. Find POLICY_ID with 'document list'. Edit rules and use the last-read version with 'document set'; read-only fields are dropped with a stderr diagnostic. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy document get [flags] +``` + +### Examples + +``` + n8n credential-policy document get POLICY_ID +``` + +### 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 get + --output string output format: text or json (default: text; JSON contains the full response) (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-policy document](n8n_credential-policy_document.md) - Manage reusable credential type policy documents + diff --git a/docs/n8n_credential-policy_document_list.md b/docs/n8n_credential-policy_document_list.md new file mode 100644 index 0000000..b0d2765 --- /dev/null +++ b/docs/n8n_credential-policy_document_list.md @@ -0,0 +1,39 @@ +## n8n credential-policy document list + +List credential type policy documents + +### Synopsis + +List reusable documents in cursor pages (default 100, maximum 250). Use --cursor for another page, or --all to collect up to 10,000 documents. Start here to find POLICY_ID for get, set, and delete. 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. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy document list [flags] +``` + +### Examples + +``` + n8n credential-policy document list +``` + +### Options + +``` + --all follow cursor pages up to 10,000 documents (default: false) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --cursor string cursor returned by a previous list (default: first page) + -h, --help help for list + --limit int documents per page, 1 to 250 (default: 100) (default 100) + --output string output format: text or json (default: text; JSON contains the full response) (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-policy document](n8n_credential-policy_document.md) - Manage reusable credential type policy documents + diff --git a/docs/n8n_credential-policy_document_set.md b/docs/n8n_credential-policy_document_set.md new file mode 100644 index 0000000..5af6082 --- /dev/null +++ b/docs/n8n_credential-policy_document_set.md @@ -0,0 +1,34 @@ +## n8n credential-policy document set + +Replace credential type policy documents + +### Synopsis + +Fully replace a document's rules using JSON {"rules":[],"version":1}. Read the document first. This changes every attached scope and bumps each scope's version; omitted rules are deleted. The server rejects delegate when any attached scope is a project. Stale versions return 409: read again before retrying. Returns {policy,warnings}. Interactive runs confirm; non-interactive runs and --input - require --yes. Selectors accept name or package. Credential policies also accept extends, matching the named type and every type extending it. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy document set [flags] +``` + +### Examples + +``` + n8n credential-policy document set POLICY_ID --input policy.json + n8n credential-policy document set POLICY_ID --input - --yes < policy.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 set + --input string JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes) + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n credential-policy document](n8n_credential-policy_document.md) - Manage reusable credential type policy documents + diff --git a/docs/n8n_credential-policy_instance.md b/docs/n8n_credential-policy_instance.md new file mode 100644 index 0000000..fbe40f2 --- /dev/null +++ b/docs/n8n_credential-policy_instance.md @@ -0,0 +1,30 @@ +## n8n credential-policy instance + +Manage instance credential type policies + +### Synopsis + +Read or replace the instance policy. Start with 'get' to obtain scopeId and version; scopeId is null until the first write. Instance scope accepts delegate; project scope accepts allow or deny. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy instance [flags] +``` + +### Examples + +``` + n8n credential-policy instance get +``` + +### Options + +``` + -h, --help help for instance +``` + +### SEE ALSO + +* [n8n credential-policy](n8n_credential-policy.md) - Manage credential type availability policies +* [n8n credential-policy instance get](n8n_credential-policy_instance_get.md) - Get the instance credential type policy +* [n8n credential-policy instance set](n8n_credential-policy_instance_set.md) - Replace the instance credential type policy + diff --git a/docs/n8n_credential-policy_instance_get.md b/docs/n8n_credential-policy_instance_get.md new file mode 100644 index 0000000..d8cdf0a --- /dev/null +++ b/docs/n8n_credential-policy_instance_get.md @@ -0,0 +1,31 @@ +## n8n credential-policy instance get + +Get the instance credential type policy + +### Synopsis + +Read the composed instance credential type policy, including every attached document in evaluation order. This does not combine project and instance evaluation. scopeId identifies attachments and is null until the scope is first written. Find project IDs with 'n8n project list'. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy instance get [flags] +``` + +### Examples + +``` + n8n credential-policy instance get +``` + +### 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 get + --output string output format: text or json (default: text; JSON contains the full response) (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-policy instance](n8n_credential-policy_instance.md) - Manage instance credential type policies + diff --git a/docs/n8n_credential-policy_instance_set.md b/docs/n8n_credential-policy_instance_set.md new file mode 100644 index 0000000..5ab443c --- /dev/null +++ b/docs/n8n_credential-policy_instance_set.md @@ -0,0 +1,34 @@ +## n8n credential-policy instance set + +Replace the instance credential type policy + +### Synopsis + +Fully replace the instance defaultAction and rules of its own document using rules, defaultAction, and version last read (0 before first write). Omitted rules are deleted. GET includes shared rules: remove those before using its response as input, or they will be copied into the own document. Selectors accept name, package, or extends; extends matches a named credential type and every type extending it. Project scope rejects delegate. Stale versions or shared project documents return 409. Blocking credential types can stop workflows using them. Interactive runs confirm; non-interactive runs and --input - require --yes. scopeId and warnings from GET are dropped and reported on stderr. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy instance set [flags] +``` + +### Examples + +``` + n8n credential-policy instance set --input policy.json + n8n credential-policy instance set --input - --yes < policy.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 set + --input string JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes) + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n credential-policy instance](n8n_credential-policy_instance.md) - Manage instance credential type policies + diff --git a/docs/n8n_credential-policy_project.md b/docs/n8n_credential-policy_project.md new file mode 100644 index 0000000..9c73d7b --- /dev/null +++ b/docs/n8n_credential-policy_project.md @@ -0,0 +1,30 @@ +## n8n credential-policy project + +Manage project credential type policies + +### Synopsis + +Read or replace the project policy. Start with 'get' to obtain scopeId and version; scopeId is null until the first write. Instance scope accepts delegate; project scope accepts allow or deny. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy project [flags] +``` + +### Examples + +``` + n8n credential-policy project get PROJECT_ID +``` + +### Options + +``` + -h, --help help for project +``` + +### SEE ALSO + +* [n8n credential-policy](n8n_credential-policy.md) - Manage credential type availability policies +* [n8n credential-policy project get](n8n_credential-policy_project_get.md) - Get the project credential type policy +* [n8n credential-policy project set](n8n_credential-policy_project_set.md) - Replace the project credential type policy + diff --git a/docs/n8n_credential-policy_project_get.md b/docs/n8n_credential-policy_project_get.md new file mode 100644 index 0000000..b8c2781 --- /dev/null +++ b/docs/n8n_credential-policy_project_get.md @@ -0,0 +1,31 @@ +## n8n credential-policy project get + +Get the project credential type policy + +### Synopsis + +Read the composed project credential type policy, including every attached document in evaluation order. This does not combine project and instance evaluation. scopeId identifies attachments and is null until the scope is first written. Find project IDs with 'n8n project list'. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy project get [flags] +``` + +### Examples + +``` + n8n credential-policy project get PROJECT_ID +``` + +### 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 get + --output string output format: text or json (default: text; JSON contains the full response) (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-policy project](n8n_credential-policy_project.md) - Manage project credential type policies + diff --git a/docs/n8n_credential-policy_project_set.md b/docs/n8n_credential-policy_project_set.md new file mode 100644 index 0000000..be89e7d --- /dev/null +++ b/docs/n8n_credential-policy_project_set.md @@ -0,0 +1,34 @@ +## n8n credential-policy project set + +Replace the project credential type policy + +### Synopsis + +Fully replace the project defaultAction and rules of its own document using rules, defaultAction, and version last read (0 before first write). Omitted rules are deleted. GET includes shared rules: remove those before using its response as input, or they will be copied into the own document. Selectors accept name, package, or extends; extends matches a named credential type and every type extending it. Project scope rejects delegate. Stale versions or shared project documents return 409. Blocking credential types can stop workflows using them. Interactive runs confirm; non-interactive runs and --input - require --yes. scopeId and warnings from GET are dropped and reported on stderr. Preview API: breaking changes may occur. Requires credentialTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n credential-policy project set [flags] +``` + +### Examples + +``` + n8n credential-policy project set PROJECT_ID --input policy.json + n8n credential-policy project set PROJECT_ID --input - --yes < policy.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 set + --input string JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes) + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n credential-policy project](n8n_credential-policy_project.md) - Manage project credential type policies + diff --git a/docs/n8n_node-policy.md b/docs/n8n_node-policy.md index 5a43313..2948f11 100644 --- a/docs/n8n_node-policy.md +++ b/docs/n8n_node-policy.md @@ -45,6 +45,8 @@ n8n node-policy [flags] ### SEE ALSO * [n8n](n8n.md) - Command-line client for the n8n API +* [n8n node-policy attachment](n8n_node-policy_attachment.md) - Manage attached node type policy documents +* [n8n node-policy document](n8n_node-policy_document.md) - Manage reusable node type policy documents * [n8n node-policy instance](n8n_node-policy_instance.md) - Manage the instance node type policy * [n8n node-policy project](n8n_node-policy_project.md) - Manage a project's node type policy diff --git a/docs/n8n_node-policy_attachment.md b/docs/n8n_node-policy_attachment.md new file mode 100644 index 0000000..2eb05ba --- /dev/null +++ b/docs/n8n_node-policy_attachment.md @@ -0,0 +1,31 @@ +## n8n node-policy attachment + +Manage attached node type policy documents + +### Synopsis + +Inspect or replace a scope's complete attachment list. Start with 'get'. Obtain SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; it is null until that scope is first written with set. Requires instance-level access even for project scopes. Floor attachments evaluate first, then priority ascending within each group. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy attachment [flags] +``` + +### Examples + +``` + n8n node-policy instance get --output json + n8n node-policy attachment get SCOPE_ID +``` + +### Options + +``` + -h, --help help for attachment +``` + +### SEE ALSO + +* [n8n node-policy](n8n_node-policy.md) - Manage node type availability policies +* [n8n node-policy attachment get](n8n_node-policy_attachment_get.md) - Get node type policy attachments +* [n8n node-policy attachment set](n8n_node-policy_attachment_set.md) - Replace node type policy attachments + diff --git a/docs/n8n_node-policy_attachment_get.md b/docs/n8n_node-policy_attachment_get.md new file mode 100644 index 0000000..b7fdc72 --- /dev/null +++ b/docs/n8n_node-policy_attachment_get.md @@ -0,0 +1,31 @@ +## n8n node-policy attachment get + +Get node type policy attachments + +### Synopsis + +Read a scope's attachments and version in evaluation order: floor first, then priority ascending within each group. Get SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; it is null until the scope is first written. Requires instance-level access even for project scopes. Use the returned version with 'attachment set'. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy attachment get [flags] +``` + +### Examples + +``` + n8n node-policy attachment get SCOPE_ID +``` + +### 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 get + --output string output format: text or json (default: text; JSON contains the full response) (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 node-policy attachment](n8n_node-policy_attachment.md) - Manage attached node type policy documents + diff --git a/docs/n8n_node-policy_attachment_set.md b/docs/n8n_node-policy_attachment_set.md new file mode 100644 index 0000000..753e822 --- /dev/null +++ b/docs/n8n_node-policy_attachment_set.md @@ -0,0 +1,34 @@ +## n8n node-policy attachment set + +Replace node type policy attachments + +### Synopsis + +Fully replace all attachments using JSON {"attachments":[{"policyId":"POLICY_ID","priority":0,"isFloor":false}],"version":1}. Each policyId and (isFloor,priority) pair must be unique. Use [] to detach every document. Get SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; null means write that scope first. Requires instance-level access even for projects. Delegate documents cannot attach to projects. Use the last-read scope version: stale writes return 409. Replacing attachments changes policy evaluation and bumps the scope version. Interactive runs confirm; non-interactive runs and --input - require --yes. Returns attachments and the new version; read-only rules in GET input are dropped with a stderr diagnostic. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy attachment set [flags] +``` + +### Examples + +``` + n8n node-policy attachment set SCOPE_ID --input policy.json + n8n node-policy attachment set SCOPE_ID --input - --yes < policy.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 set + --input string JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes) + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n node-policy attachment](n8n_node-policy_attachment.md) - Manage attached node type policy documents + diff --git a/docs/n8n_node-policy_document.md b/docs/n8n_node-policy_document.md new file mode 100644 index 0000000..4bb9a9c --- /dev/null +++ b/docs/n8n_node-policy_document.md @@ -0,0 +1,34 @@ +## n8n node-policy document + +Manage reusable node type policy documents + +### Synopsis + +Manage reusable rule lists. Start with 'list', then 'get' before 'set'. Create produces an unattached document; attach it with 'attachment set'. Updating a document changes every attached scope and bumps their versions. A document containing delegate cannot be attached to a project scope. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy document [flags] +``` + +### Examples + +``` + n8n node-policy document list + n8n node-policy document get POLICY_ID --output json +``` + +### Options + +``` + -h, --help help for document +``` + +### SEE ALSO + +* [n8n node-policy](n8n_node-policy.md) - Manage node type availability policies +* [n8n node-policy document create](n8n_node-policy_document_create.md) - Create node type policy documents +* [n8n node-policy document delete](n8n_node-policy_document_delete.md) - Delete node type policy documents +* [n8n node-policy document get](n8n_node-policy_document_get.md) - Get node type policy documents +* [n8n node-policy document list](n8n_node-policy_document_list.md) - List node type policy documents +* [n8n node-policy document set](n8n_node-policy_document_set.md) - Replace node type policy documents + diff --git a/docs/n8n_node-policy_document_create.md b/docs/n8n_node-policy_document_create.md new file mode 100644 index 0000000..66c7ca3 --- /dev/null +++ b/docs/n8n_node-policy_document_create.md @@ -0,0 +1,34 @@ +## n8n node-policy document create + +Create node type policy documents + +### Synopsis + +Create an unattached reusable document from JSON {"rules":[]}. Rules are required; each rule has a unique id, action allow|deny|delegate, and selector {kind,value}. Creation returns {policy,warnings}; warnings do not fail the write. Attach the returned policy.id using 'attachment set'. --input - requires --yes. Selectors accept name or package. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy document create [flags] +``` + +### Examples + +``` + n8n node-policy document create --input policy.json + n8n node-policy document create --input - --yes < policy.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 + --input string JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes) + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n node-policy document](n8n_node-policy_document.md) - Manage reusable node type policy documents + diff --git a/docs/n8n_node-policy_document_delete.md b/docs/n8n_node-policy_document_delete.md new file mode 100644 index 0000000..89fcbd4 --- /dev/null +++ b/docs/n8n_node-policy_document_delete.md @@ -0,0 +1,33 @@ +## n8n node-policy document delete + +Delete node type policy documents + +### Synopsis + +Permanently delete an unattached document found with 'document list'. Attached documents return 409: inspect 'attachment get' and use 'attachment set' to detach first. Interactive runs confirm; non-interactive runs require --yes. Success returns the deleted ID; deletion cannot be undone. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy document delete [flags] +``` + +### Examples + +``` + n8n node-policy document delete POLICY_ID + n8n node-policy document delete POLICY_ID --yes +``` + +### 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 delete + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n node-policy document](n8n_node-policy_document.md) - Manage reusable node type policy documents + diff --git a/docs/n8n_node-policy_document_get.md b/docs/n8n_node-policy_document_get.md new file mode 100644 index 0000000..50290f8 --- /dev/null +++ b/docs/n8n_node-policy_document_get.md @@ -0,0 +1,31 @@ +## n8n node-policy document get + +Get node type policy documents + +### Synopsis + +Read a reusable document's ID, kind, ordered rules, version, updater and timestamps. Find POLICY_ID with 'document list'. Edit rules and use the last-read version with 'document set'; read-only fields are dropped with a stderr diagnostic. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy document get [flags] +``` + +### Examples + +``` + n8n node-policy document get POLICY_ID +``` + +### 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 get + --output string output format: text or json (default: text; JSON contains the full response) (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 node-policy document](n8n_node-policy_document.md) - Manage reusable node type policy documents + diff --git a/docs/n8n_node-policy_document_list.md b/docs/n8n_node-policy_document_list.md new file mode 100644 index 0000000..31908d5 --- /dev/null +++ b/docs/n8n_node-policy_document_list.md @@ -0,0 +1,39 @@ +## n8n node-policy document list + +List node type policy documents + +### Synopsis + +List reusable documents in cursor pages (default 100, maximum 250). Use --cursor for another page, or --all to collect up to 10,000 documents. Start here to find POLICY_ID for get, set, and delete. 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. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy document list [flags] +``` + +### Examples + +``` + n8n node-policy document list +``` + +### Options + +``` + --all follow cursor pages up to 10,000 documents (default: false) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --cursor string cursor returned by a previous list (default: first page) + -h, --help help for list + --limit int documents per page, 1 to 250 (default: 100) (default 100) + --output string output format: text or json (default: text; JSON contains the full response) (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 node-policy document](n8n_node-policy_document.md) - Manage reusable node type policy documents + diff --git a/docs/n8n_node-policy_document_set.md b/docs/n8n_node-policy_document_set.md new file mode 100644 index 0000000..277b802 --- /dev/null +++ b/docs/n8n_node-policy_document_set.md @@ -0,0 +1,34 @@ +## n8n node-policy document set + +Replace node type policy documents + +### Synopsis + +Fully replace a document's rules using JSON {"rules":[],"version":1}. Read the document first. This changes every attached scope and bumps each scope's version; omitted rules are deleted. The server rejects delegate when any attached scope is a project. Stale versions return 409: read again before retrying. Returns {policy,warnings}. Interactive runs confirm; non-interactive runs and --input - require --yes. Selectors accept name or package. Preview API: breaking changes may occur. Requires nodeTypePolicy:manage and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary. + +``` +n8n node-policy document set [flags] +``` + +### Examples + +``` + n8n node-policy document set POLICY_ID --input policy.json + n8n node-policy document set POLICY_ID --input - --yes < policy.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 set + --input string JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes) + --output string output format: text or json (default: text; JSON contains the full response) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -) +``` + +### SEE ALSO + +* [n8n node-policy document](n8n_node-policy_document.md) - Manage reusable node type policy documents + diff --git a/docs/n8n_node-policy_instance_get.md b/docs/n8n_node-policy_instance_get.md index 00ae12a..24fd540 100644 --- a/docs/n8n_node-policy_instance_get.md +++ b/docs/n8n_node-policy_instance_get.md @@ -12,7 +12,7 @@ with shared documents attached the round trip copies their rules too. scopeId identifies the scope's attachments and is null until the scope is first written. A scope that was never configured reports no rules, defaultAction allow, -and version 0. Requires nodeTypePolicy:manage. +and version 0. Preview API. Requires nodeTypePolicy:manage. ``` n8n node-policy instance get [flags] diff --git a/docs/n8n_node-policy_project_get.md b/docs/n8n_node-policy_project_get.md index 099223b..e5ea536 100644 --- a/docs/n8n_node-policy_project_get.md +++ b/docs/n8n_node-policy_project_get.md @@ -12,7 +12,7 @@ applied on top at evaluation. scopeId identifies the scope's attachments and is null until the project policy is first written. A project that was never configured reports no rules, defaultAction allow, and version 0. Use --output json as the input for 'set'. -Requires nodeTypePolicy:manage. Find project IDs with 'n8n project list'. +Preview API. Requires nodeTypePolicy:manage. Find project IDs with 'n8n project list'. ``` n8n node-policy project get [flags] diff --git a/internal/cli/cli.go b/internal/cli/cli.go index aa6c042..b1907e7 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -270,6 +270,7 @@ func NewRootCommand(opts Options) *cobra.Command { newEvaluationCommand(opts), newInsightCommand(opts), newNodePolicyCommand(opts), + newCredentialPolicyCommand(opts), newSecurityPolicyCommand(opts), newOtelCommand(opts), newLogStreamCommand(opts), diff --git a/internal/cli/help_test.go b/internal/cli/help_test.go index 40013f7..5a1e1a8 100644 --- a/internal/cli/help_test.go +++ b/internal/cli/help_test.go @@ -61,6 +61,32 @@ func TestHelpIsDescriptive(t *testing.T) { func TestHelpSucceedsAtEveryLevel(t *testing.T) { paths := [][]string{ + {"node-policy", "document"}, + {"node-policy", "attachment"}, + {"node-policy", "document", "list"}, + {"node-policy", "document", "get"}, + {"node-policy", "document", "create"}, + {"node-policy", "document", "set"}, + {"node-policy", "document", "delete"}, + {"node-policy", "attachment", "get"}, + {"node-policy", "attachment", "set"}, + {"credential-policy"}, + {"credential-policy", "instance"}, + {"credential-policy", "project"}, + {"credential-policy", "instance", "get"}, + {"credential-policy", "instance", "set"}, + {"credential-policy", "project", "get"}, + {"credential-policy", "project", "set"}, + {"credential-policy", "document"}, + {"credential-policy", "attachment"}, + {"credential-policy", "document", "list"}, + {"credential-policy", "document", "get"}, + {"credential-policy", "document", "create"}, + {"credential-policy", "document", "set"}, + {"credential-policy", "document", "delete"}, + {"credential-policy", "attachment", "get"}, + {"credential-policy", "attachment", "set"}, + {}, {"auth"}, {"auth", "login"}, diff --git a/internal/cli/node_policy.go b/internal/cli/node_policy.go index 0395498..f9567b4 100644 --- a/internal/cli/node_policy.go +++ b/internal/cli/node_policy.go @@ -57,6 +57,7 @@ func newNodePolicyCommand(opts Options) *cobra.Command { newNodePolicyInstanceCommand(opts), newNodePolicyProjectCommand(opts), ) + addPolicyDocuments(cmd, opts, nodePolicyGroup()) return cmd } @@ -123,7 +124,7 @@ func newNodePolicyInstanceGetCommand(opts Options) *cobra.Command { "with shared documents attached the round trip copies their rules too.\n\n" + "scopeId identifies the scope's attachments and is null until the scope is first\n" + "written. A scope that was never configured reports no rules, defaultAction allow,\n" + - "and version 0. Requires nodeTypePolicy:manage.", + "and version 0. Preview API. Requires nodeTypePolicy:manage.", Example: " n8n node-policy instance get\n" + " n8n node-policy instance get --output json\n" + " n8n node-policy instance get --output json > policy.json", @@ -149,7 +150,7 @@ func newNodePolicyProjectGetCommand(opts Options) *cobra.Command { "scopeId identifies the scope's attachments and is null until the project policy\n" + "is first written. A project that was never configured reports no rules,\n" + "defaultAction allow, and version 0. Use --output json as the input for 'set'.\n" + - "Requires nodeTypePolicy:manage. Find project IDs with 'n8n project list'.", + "Preview API. Requires nodeTypePolicy:manage. Find project IDs with 'n8n project list'.", Example: " n8n node-policy project get L5fcpzBVjoU2PKFP\n" + " n8n node-policy project get L5fcpzBVjoU2PKFP --output json > project-policy.json", Args: cobra.ExactArgs(1), diff --git a/internal/cli/policy.go b/internal/cli/policy.go new file mode 100644 index 0000000..48fe03c --- /dev/null +++ b/internal/cli/policy.go @@ -0,0 +1,521 @@ +package cli + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "strings" + "text/tabwriter" + + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" + "github.com/spf13/cobra" +) + +type policyGroup struct { + name, resource, scope, noun string + credential bool +} + +func nodePolicyGroup() policyGroup { + return policyGroup{"node-policy", "nodetypepolicy", "nodeTypePolicy:manage", "node type", false} +} +func credentialPolicyGroup() policyGroup { + return policyGroup{"credential-policy", "credentialtypepolicy", "credentialTypePolicy:manage", "credential type", true} +} +func (g policyGroup) api(c *n8n.Client) n8n.PolicyClient { + if g.credential { + return c.CredentialTypePolicies() + } + return c.NodeTypePolicies() +} +func (g policyGroup) requirements() string { + return "Preview API: breaking changes may occur. Requires " + g.scope + " and the licensed type-availability-policies module. Use --output json for the full response; text prints a summary." +} +func policyParent(use, short, long, example string) *cobra.Command { + return &cobra.Command{Use: use, Short: short, Long: long, Example: example, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }} +} + +func newCredentialPolicyCommand(opts Options) *cobra.Command { + g := credentialPolicyGroup() + cmd := policyParent(g.name, "Manage credential type availability policies", + "Manage instance and project credential type policies. Start with 'instance get', then inspect 'attachment get' before editing scopes with shared documents. GET returns composed rules; scope set replaces only the scope's own document and default. Documents are reusable rule lists. Floor attachments run first, then priority ascending within each group. The first matching rule wins. "+g.requirements(), + " n8n credential-policy instance get\n n8n credential-policy document list") + for _, scope := range []string{"instance", "project"} { + parent := policyParent(scope, "Manage "+scope+" credential type policies", "Read or replace the "+scope+" policy. Start with 'get' to obtain scopeId and version; scopeId is null until the first write. Instance scope accepts delegate; project scope accepts allow or deny. "+g.requirements(), " n8n credential-policy "+scope+" get"+policyExampleID(scope)) + parent.AddCommand(newCredentialScopeCommand(opts, g, scope, false), newCredentialScopeCommand(opts, g, scope, true)) + cmd.AddCommand(parent) + } + addPolicyDocuments(cmd, opts, g) + return cmd +} +func policyExampleID(scope string) string { + if scope == "project" { + return " PROJECT_ID" + } + return "" +} +func newCredentialScopeCommand(opts Options, g policyGroup, scope string, set bool) *cobra.Command { + verb := "get" + if set { + verb = "set" + } + use := verb + if scope == "project" { + use += " " + } + var f policyFlags + long := "Read the composed " + scope + " credential type policy, including every attached document in evaluation order. This does not combine project and instance evaluation. scopeId identifies attachments and is null until the scope is first written. Find project IDs with 'n8n project list'." + if set { + long = "Fully replace the " + scope + " defaultAction and rules of its own document using rules, defaultAction, and version last read (0 before first write). Omitted rules are deleted. GET includes shared rules: remove those before using its response as input, or they will be copied into the own document. Selectors accept name, package, or extends; extends matches a named credential type and every type extending it. Project scope rejects delegate. Stale versions or shared project documents return 409. Blocking credential types can stop workflows using them. Interactive runs confirm; non-interactive runs and --input - require --yes. scopeId and warnings from GET are dropped and reported on stderr." + } + cmd := &cobra.Command{Use: use, Short: map[string]string{"get": "Get", "set": "Replace", "list": "List", "create": "Create", "delete": "Delete"}[verb] + " the " + scope + " credential type policy", Long: long + " " + g.requirements(), Example: " n8n " + g.name + " " + scope + " " + verb + policyExampleID(scope), Args: cobra.NoArgs} + if scope == "project" { + cmd.Args = cobra.ExactArgs(1) + } + if set { + cmd.Example += " --input policy.json\n n8n " + g.name + " " + scope + " set" + policyExampleID(scope) + " --input - --yes < policy.json" + } + cmd.RunE = func(cmd *cobra.Command, args []string) error { + if err := validateOutput(f.output); err != nil { + return err + } + id := "" + if len(args) > 0 { + id = args[0] + if strings.TrimSpace(id) == "" { + return fmt.Errorf("project ID is required") + } + } + var request n8n.ReplaceNodeTypePolicyRequest + if set { + if err := policyStdinConsent(f); err != nil { + return err + } + var d nodePolicyDocument + raw, err := readPolicyInput(opts, f.input, &d) + if err != nil { + return err + } + if d.Rules == nil { + return fmt.Errorf("rules is required: use [] for an empty policy") + } + request = n8n.ReplaceNodeTypePolicyRequest{Rules: d.Rules, DefaultAction: d.DefaultAction, Version: d.Version} + // Validation needs only the policy kind, no configured HTTP client. + if err := g.api(nil).ValidateScope(request, n8n.NodeTypePolicyScope(scope)); err != nil { + return err + } + reportPolicyDropped(opts, raw, "scopeId", "warnings") + } + client, res, err := opts.apiClient(f.instance) + if err != nil { + return err + } + api := g.api(client) + if !set { + var result *n8n.NodeTypePolicy + if scope == "project" { + result, err = api.GetProject(cmd.Context(), id) + } else { + result, err = api.GetInstance(cmd.Context()) + } + if err != nil { + return policyAPIError(err, res, g, scope, verb) + } + return writePolicyScope(opts, res, result, nil, f.output) + } + if err := opts.confirmer(f.yes).Confirm(fmt.Sprintf("Replace %s credential type policy %q on %s? Omitted rules are deleted; blocked credential types can stop workflows using them.", scope, id, res.URL)); err != nil { + return err + } + var result *n8n.NodeTypePolicyWriteResult + if scope == "project" { + result, err = api.ReplaceProject(cmd.Context(), id, request) + } else { + result, err = api.ReplaceInstance(cmd.Context(), request) + } + if err != nil { + return policyAPIError(err, res, g, scope, verb) + } + if f.output == outputJSON { + return writeJSON(opts.Streams.Out, result) + } + return writePolicyScope(opts, res, &result.NodeTypePolicy, result.Warnings, f.output) + } + f.register(cmd, set, set) + return cmd +} + +type policyFlags struct { + instance instanceFlags + input, output, cursor string + yes, all bool + limit int +} + +func (f *policyFlags) register(cmd *cobra.Command, input, confirm bool) { + f.instance.register(cmd) + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (default: text; JSON contains the full response)") + if input { + cmd.Flags().StringVar(&f.input, "input", "", "JSON file path, or - for stdin (required; maximum 1 MiB; stdin requires --yes)") + } + // Create does not prompt, but stdin still requires explicit consent. + if input || confirm { + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm mutation without prompting (default: false; required for non-interactive replacement/deletion and --input -)") + } +} +func addPolicyDocuments(cmd *cobra.Command, opts Options, g policyGroup) { + doc := policyParent("document", "Manage reusable "+g.noun+" policy documents", "Manage reusable rule lists. Start with 'list', then 'get' before 'set'. Create produces an unattached document; attach it with 'attachment set'. Updating a document changes every attached scope and bumps their versions. A document containing delegate cannot be attached to a project scope. "+g.requirements(), " n8n "+g.name+" document list\n n8n "+g.name+" document get POLICY_ID --output json") + for _, verb := range []string{"list", "get", "create", "set", "delete"} { + doc.AddCommand(newPolicyResourceCommand(opts, g, "document", verb)) + } + att := policyParent("attachment", "Manage attached "+g.noun+" policy documents", "Inspect or replace a scope's complete attachment list. Start with 'get'. Obtain SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; it is null until that scope is first written with set. Requires instance-level access even for project scopes. Floor attachments evaluate first, then priority ascending within each group. "+g.requirements(), " n8n "+g.name+" instance get --output json\n n8n "+g.name+" attachment get SCOPE_ID") + for _, verb := range []string{"get", "set"} { + att.AddCommand(newPolicyResourceCommand(opts, g, "attachment", verb)) + } + cmd.AddCommand(doc, att) +} +func newPolicyResourceCommand(opts Options, g policyGroup, resource, verb string) *cobra.Command { + var f policyFlags + use := verb + args := cobra.NoArgs + idName := "POLICY_ID" + if resource == "attachment" { + idName = "SCOPE_ID" + } + if verb != "list" && verb != "create" { + use += " <" + strings.ReplaceAll(strings.ToLower(idName), "_", "-") + ">" + args = cobra.ExactArgs(1) + } + descriptions := map[string]string{ + "document list": "List reusable documents in cursor pages (default 100, maximum 250). Use --cursor for another page, or --all to collect up to 10,000 documents. Start here to find POLICY_ID for get, set, and delete. " + cursorCollectionHelp, + "document get": "Read a reusable document's ID, kind, ordered rules, version, updater and timestamps. Find POLICY_ID with 'document list'. Edit rules and use the last-read version with 'document set'; read-only fields are dropped with a stderr diagnostic.", + "document create": "Create an unattached reusable document from JSON {\"rules\":[]}. Rules are required; each rule has a unique id, action allow|deny|delegate, and selector {kind,value}. Creation returns {policy,warnings}; warnings do not fail the write. Attach the returned policy.id using 'attachment set'. --input - requires --yes.", + "document set": "Fully replace a document's rules using JSON {\"rules\":[],\"version\":1}. Read the document first. This changes every attached scope and bumps each scope's version; omitted rules are deleted. The server rejects delegate when any attached scope is a project. Stale versions return 409: read again before retrying. Returns {policy,warnings}. Interactive runs confirm; non-interactive runs and --input - require --yes.", + "document delete": "Permanently delete an unattached document found with 'document list'. Attached documents return 409: inspect 'attachment get' and use 'attachment set' to detach first. Interactive runs confirm; non-interactive runs require --yes. Success returns the deleted ID; deletion cannot be undone.", + "attachment get": "Read a scope's attachments and version in evaluation order: floor first, then priority ascending within each group. Get SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; it is null until the scope is first written. Requires instance-level access even for project scopes. Use the returned version with 'attachment set'.", + "attachment set": "Fully replace all attachments using JSON {\"attachments\":[{\"policyId\":\"POLICY_ID\",\"priority\":0,\"isFloor\":false}],\"version\":1}. Each policyId and (isFloor,priority) pair must be unique. Use [] to detach every document. Get SCOPE_ID from 'instance get' or 'project get PROJECT_ID' -> scopeId; null means write that scope first. Requires instance-level access even for projects. Delegate documents cannot attach to projects. Use the last-read scope version: stale writes return 409. Replacing attachments changes policy evaluation and bumps the scope version. Interactive runs confirm; non-interactive runs and --input - require --yes. Returns attachments and the new version; read-only rules in GET input are dropped with a stderr diagnostic.", + } + long := descriptions[resource+" "+verb] + if resource == "document" && (verb == "create" || verb == "set") { + long += " Selectors accept name or package." + if g.credential { + long += " Credential policies also accept extends, matching the named type and every type extending it." + } + } + example := " n8n " + g.name + " " + resource + " " + verb + if verb != "list" && verb != "create" { + example += " " + idName + } + input := verb == "create" || verb == "set" + confirm := verb == "set" || verb == "delete" + if input { + example += " --input policy.json\n n8n " + g.name + " " + resource + " " + verb + if verb == "set" { + example += " " + idName + } + example += " --input - --yes < policy.json" + } else if confirm { + example += "\n n8n " + g.name + " " + resource + " " + verb + " " + idName + " --yes" + } + cmd := &cobra.Command{Use: use, Short: map[string]string{"get": "Get", "set": "Replace", "list": "List", "create": "Create", "delete": "Delete"}[verb] + " " + g.noun + " policy " + resource + "s", Long: long + " " + g.requirements(), Example: example, Args: args} + cmd.RunE = func(cmd *cobra.Command, args []string) error { + return runPolicyResource(cmd, opts, g, resource, verb, args, f) + } + f.register(cmd, input, confirm) + if verb == "list" { + cmd.Flags().IntVar(&f.limit, "limit", 100, "documents per page, 1 to 250 (default: 100)") + cmd.Flags().StringVar(&f.cursor, "cursor", "", "cursor returned by a previous list (default: first page)") + cmd.Flags().BoolVar(&f.all, "all", false, "follow cursor pages up to 10,000 documents (default: false)") + } + return cmd +} + +func policyStdinConsent(f policyFlags) error { + if f.input == "-" && !f.yes { + return fmt.Errorf("--input - consumes stdin: pass --yes after reviewing the document") + } + return nil +} +func readPolicyInput(opts Options, path string, dest any) ([]byte, error) { + if strings.TrimSpace(path) == "" { + return nil, fmt.Errorf("--input is required: pass a JSON file path or - for stdin") + } + reader := opts.Streams.In + if path != "-" { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + reader = file + } + raw, err := io.ReadAll(io.LimitReader(reader, maxNodePolicyDocument+1)) + if err != nil { + return nil, err + } + if len(raw) > maxNodePolicyDocument { + return nil, fmt.Errorf("policy JSON exceeds %d bytes", maxNodePolicyDocument) + } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(dest); err != nil { + return nil, fmt.Errorf("decode policy JSON: %w", err) + } + var extra any + if err := dec.Decode(&extra); err != io.EOF { + return nil, fmt.Errorf("decode policy JSON: expected one document") + } + return raw, nil +} +func reportPolicyDropped(opts Options, raw []byte, fields ...string) { + var m map[string]json.RawMessage + if json.Unmarshal(raw, &m) != nil { + return + } + for _, field := range fields { + if _, ok := m[field]; ok { + fmt.Fprintf(opts.Streams.Err, "Dropped read-only field %s.\n", field) + } + } +} + +type reusablePolicyInput struct { + Rules []n8n.NodeTypePolicyRule `json:"rules"` + Version *int `json:"version"` + ID json.RawMessage `json:"id"` + Kind json.RawMessage `json:"kind"` + UpdatedBy json.RawMessage `json:"updatedBy"` + CreatedAt json.RawMessage `json:"createdAt"` + UpdatedAt json.RawMessage `json:"updatedAt"` +} +type attachmentPolicyInput struct { + Attachments []struct { + PolicyID string `json:"policyId"` + Priority *int `json:"priority"` + IsFloor *bool `json:"isFloor"` + Rules json.RawMessage `json:"rules"` + } `json:"attachments"` + Version *int `json:"version"` +} + +func runPolicyResource(cmd *cobra.Command, opts Options, g policyGroup, resource, verb string, args []string, f policyFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + id := "" + if len(args) > 0 { + id = args[0] + if strings.TrimSpace(id) == "" { + return fmt.Errorf("%s ID is required", resource) + } + } + if verb == "list" && (f.limit < 1 || f.limit > 250) { + return fmt.Errorf("--limit must be between 1 and 250") + } + var doc reusablePolicyInput + var attachments n8n.ReplacePolicyAttachmentsRequest + if verb == "create" || verb == "set" { + if err := policyStdinConsent(f); err != nil { + return err + } + if resource == "document" { + if verb == "create" { + var d n8n.CreatePolicyDocumentRequest + if _, err := readPolicyInput(opts, f.input, &d); err != nil { + return err + } + doc.Rules = d.Rules + } else { + raw, err := readPolicyInput(opts, f.input, &doc) + if err != nil { + return err + } + reportPolicyDropped(opts, raw, "id", "kind", "updatedBy", "createdAt", "updatedAt") + } + if doc.Rules == nil { + return fmt.Errorf("rules is required: use [] for an empty document") + } + if err := g.api(nil).ValidateRules(doc.Rules, n8n.NodeTypePolicyScopeInstance); err != nil { + return err + } + if verb == "set" && (doc.Version == nil || *doc.Version < 0) { + return fmt.Errorf("version is required and must be 0 or greater: send the version last read") + } + } else { + var d attachmentPolicyInput + if _, err := readPolicyInput(opts, f.input, &d); err != nil { + return err + } + if d.Attachments == nil { + return fmt.Errorf("attachments is required: use [] to detach every document") + } + attachments = n8n.ReplacePolicyAttachmentsRequest{Version: d.Version, Attachments: []n8n.PolicyAttachmentInput{}} + for i, a := range d.Attachments { + attachments.Attachments = append(attachments.Attachments, n8n.PolicyAttachmentInput{PolicyID: a.PolicyID, Priority: a.Priority, IsFloor: a.IsFloor}) + if len(a.Rules) > 0 { + fmt.Fprintf(opts.Streams.Err, "Dropped read-only field attachments[%d].rules.\n", i) + } + } + if err := attachments.Validate(); err != nil { + return err + } + } + } + client, res, err := opts.apiClient(f.instance) + if err != nil { + return err + } + api := g.api(client) + if verb == "set" || verb == "delete" { + question := fmt.Sprintf("Permanently delete %s policy document %q on %s? Deletion cannot be undone.", g.noun, id, res.URL) + if verb == "set" && resource == "document" { + question = fmt.Sprintf("Replace every rule in %s policy document %q on %s? This changes every attached scope, bumps their versions, and may stop workflows using blocked types.", g.noun, id, res.URL) + } + if resource == "attachment" { + question = fmt.Sprintf("Replace all %s policy attachments of scope %q on %s? Omitted attachments are removed; changed policy evaluation may stop workflows.", g.noun, id, res.URL) + } + if err := opts.confirmer(f.yes).Confirm(question); err != nil { + return err + } + } + var result any + if resource == "attachment" { + if verb == "get" { + result, err = api.GetAttachments(cmd.Context(), id) + } else { + result, err = api.ReplaceAttachments(cmd.Context(), id, attachments) + } + } else { + switch verb { + case "list": + var page n8n.Page[n8n.PolicyDocument] + var collection *listCollection + o := n8n.ListOptions{Limit: f.limit, Cursor: f.cursor} + if f.all { + page, collection, err = collectPage(cmd.Context(), api.ListDocuments, o) + } else { + page, err = api.ListDocuments(cmd.Context(), o) + } + if err != nil { + return policyAPIError(err, res, g, resource, verb) + } + if len(page.Data) == 0 { + fmt.Fprintf(opts.Streams.Err, "No policy documents returned. Create one with 'n8n %s document create --input policy.json'.\n", g.name) + } + if f.output == outputJSON { + err = writePageJSON(opts.Streams.Out, page, collection) + } else { + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, "ID\tKIND\tVERSION\tRULES\tUPDATED") + for _, d := range page.Data { + fmt.Fprintf(tw, "%s\t%s\t%d\t%d\t%s\n", d.ID, d.Kind, d.Version, len(d.Rules), d.UpdatedAt) + } + if page.NextCursor != "" { + fmt.Fprintf(tw, "Next cursor:\t%s\n", page.NextCursor) + } + err = tw.Flush() + } + return finishCollection(opts.Streams.Err, collection, err) + case "get": + result, err = api.GetDocument(cmd.Context(), id) + case "create": + result, err = api.CreateDocument(cmd.Context(), n8n.CreatePolicyDocumentRequest{Rules: doc.Rules}) + case "set": + result, err = api.UpdateDocument(cmd.Context(), id, n8n.UpdatePolicyDocumentRequest{Rules: doc.Rules, Version: doc.Version}) + case "delete": + err = api.DeleteDocument(cmd.Context(), id) + result = struct { + ID string `json:"id"` + }{id} + } + } + if err != nil { + return policyAPIError(err, res, g, resource, verb) + } + if f.output == outputJSON { + return writeJSON(opts.Streams.Out, result) + } + return writePolicyResourceText(opts, result) +} +func writePolicyResourceText(opts Options, result any) error { + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + document := func(d n8n.PolicyDocument) { + fmt.Fprintf(tw, "ID:\t%s\nKind:\t%s\nVersion:\t%d\nUpdated by:\t%s\nCreated:\t%s\nUpdated:\t%s\n", d.ID, d.Kind, d.Version, d.UpdatedBy, d.CreatedAt, d.UpdatedAt) + writePolicyRules(tw, d.Rules) + } + switch r := result.(type) { + case *n8n.PolicyDocument: + document(*r) + case *n8n.PolicyDocumentWriteResult: + document(r.Policy) + writePolicyWarnings(opts, r.Warnings) + case *n8n.PolicyAttachments: + fmt.Fprintf(tw, "Version:\t%d\nPOLICY ID\tPRIORITY\tFLOOR\tRULES\n", r.Version) + for _, a := range r.Attachments { + fmt.Fprintf(tw, "%s\t%d\t%t\t%d\n", a.PolicyID, a.Priority, a.IsFloor, len(a.Rules)) + } + if len(r.Attachments) == 0 { + fmt.Fprintln(opts.Streams.Err, "No policy documents attached. Use attachment set to attach documents.") + } + default: + fmt.Fprintln(opts.Streams.Err, "Policy document deleted.") + return nil + } + return tw.Flush() +} +func writePolicyRules(w io.Writer, rules []n8n.NodeTypePolicyRule) { + fmt.Fprintln(w, "ORDER\tID\tACTION\tSELECTOR") + for i, r := range rules { + fmt.Fprintf(w, "%d\t%s\t%s\t%s=%s\n", i+1, r.ID, r.Action, r.Selector.Kind, r.Selector.Value) + } +} +func writePolicyWarnings(opts Options, warnings []n8n.NodeTypePolicyWarning) { + for _, w := range warnings { + fmt.Fprintf(opts.Streams.Err, "Warning: rule %s: %s", w.RuleID, w.Kind) + if w.ShadowedByRuleID != "" { + fmt.Fprintf(opts.Streams.Err, " (shadowed by %s)", w.ShadowedByRuleID) + } + fmt.Fprintln(opts.Streams.Err) + } +} +func writePolicyScope(opts Options, res config.Resolution, p *n8n.NodeTypePolicy, warnings []n8n.NodeTypePolicyWarning, output string) error { + if output == outputJSON { + return writeJSON(opts.Streams.Out, p) + } + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "Instance:\t%s\nDefault action:\t%s\nVersion:\t%d\n", res.URL, p.DefaultAction, p.Version) + if p.ScopeID == nil { + fmt.Fprintln(tw, "Scope ID:\tnone (never configured)") + } else { + fmt.Fprintf(tw, "Scope ID:\t%s\n", *p.ScopeID) + } + writePolicyRules(tw, p.Rules) + writePolicyWarnings(opts, warnings) + return tw.Flush() +} +func policyAPIError(err error, res config.Resolution, g policyGroup, resource, verb string) error { + switch { + case n8n.IsForbidden(err): + detail := "" + if resource == "attachment" { + detail = "attachment endpoints require instance-level access even for project scopes" + } + return forbiddenScopeError(err, res, g.noun+" policy "+verb, allOf(g.scope), detail, g.resource) + case n8n.IsNotFound(err), n8n.IsStatus(err, http.StatusServiceUnavailable): + return fmt.Errorf("%s: %s policies are not available to you (%d); verify the policy/scope ID and licensed type-availability-policies module; run %s", res.URL, g.noun, n8n.StatusCodeOf(err), discoverHint(g.resource)) + case n8n.IsConflict(err): + if verb == "delete" { + return fmt.Errorf("policy document is still attached (409): run 'n8n %s attachment get SCOPE_ID', then 'n8n %s attachment set SCOPE_ID' to detach it before retrying", g.name, g.name) + } + return fmt.Errorf("%s policy %s rejected (409): re-read 'n8n %s %s get' and send the current version; attachment writes and attached-document updates bump scope versions. Project scopes reject delegate, and shared project documents must be edited with document set", g.noun, verb, g.name, resource) + case n8n.IsStatus(err, http.StatusBadRequest): + return fmt.Errorf("%s policy input rejected (400): send required rules/attachments and version for replacements, use unique rule IDs, policyIds and (isFloor, priority) pairs; project scopes reject delegate; inspect 'n8n %s %s %s --help'", g.noun, g.name, resource, verb) + case n8n.IsStatus(err, http.StatusUnsupportedMediaType): + return fmt.Errorf("policy input rejected (415): send a JSON document with --input FILE or --input -") + default: + return apiError(err, res, g.resource) + } +} diff --git a/internal/cli/policy_test.go b/internal/cli/policy_test.go new file mode 100644 index 0000000..36dfcba --- /dev/null +++ b/internal/cli/policy_test.go @@ -0,0 +1,398 @@ +package cli + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +const cliPolicyDoc = `{"id":"p1","kind":"future-kind","rules":[],"version":2,"updatedBy":"u1","createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-02T00:00:00Z"}` +const cliPolicyResult = `{"policy":` + cliPolicyDoc + `,"warnings":[{"kind":"notLoaded","ruleId":"r1"}]}` +const cliAttachments = `{"attachments":[{"policyId":"p1","rules":[],"priority":0,"isFloor":false}],"version":2}` + +type policyCLIOperation struct { + resource, verb, id, method, path, input, response string + status int +} + +func policyCLIOperations() []policyCLIOperation { + return []policyCLIOperation{ + {"document", "list", "", "GET", "/policies", "", `{"data":[` + cliPolicyDoc + `],"nextCursor":""}`, 200}, + {"document", "get", "a/b c", "GET", "/policies/a%2Fb%20c", "", cliPolicyDoc, 200}, + {"document", "create", "", "POST", "/policies", `{"rules":[]}`, cliPolicyResult, 201}, + {"document", "set", "a/b c", "PUT", "/policies/a%2Fb%20c", `{"rules":[],"version":2}`, cliPolicyResult, 200}, + {"document", "delete", "a/b c", "DELETE", "/policies/a%2Fb%20c", "", "", 204}, + {"attachment", "get", "a/b c", "GET", "/scopes/a%2Fb%20c/attachments", "", cliAttachments, 200}, + {"attachment", "set", "a/b c", "PUT", "/scopes/a%2Fb%20c/attachments", `{"attachments":[{"policyId":"p1","priority":0,"isFloor":false}],"version":2}`, cliAttachments, 200}, + {"instance", "get", "", "GET", "/instance", "", cliNodePolicyUnconfigured, 200}, + {"instance", "set", "", "PUT", "/instance", `{"rules":[],"defaultAction":"allow","version":0}`, cliNodePolicyWriteResult, 200}, + {"project", "get", "a/b c", "GET", "/projects/a%2Fb%20c", "", cliNodePolicyUnconfigured, 200}, + {"project", "set", "a/b c", "PUT", "/projects/a%2Fb%20c", `{"rules":[],"defaultAction":"allow","version":0}`, cliNodePolicyWriteResult, 200}, + } +} +func policyCLIArgs(group string, op policyCLIOperation) []string { + args := []string{group, op.resource, op.verb} + if op.id != "" { + args = append(args, op.id) + } + return args +} +func TestPolicyCommands(t *testing.T) { + for _, group := range []string{"node-policy", "credential-policy"} { + for _, op := range policyCLIOperations() { + if group == "node-policy" && (op.resource == "instance" || op.resource == "project") { + continue + } + for _, output := range []string{"text", "json"} { + t.Run(group+"/"+op.resource+"/"+op.verb+"/"+output, func(t *testing.T) { + f := nodePolicyFixture(t, op.response) + f.route = func(*http.Request, int) (int, string) { return op.status, op.response } + args := policyCLIArgs(group, op) + if op.input != "" { + args = append(args, "--input", writeNodePolicyInput(t, op.input)) + } + if op.verb == "set" || op.verb == "delete" { + args = append(args, "--yes") + } + args = append(args, "--output", output) + got := f.run(args...) + if got.code != ExitSuccess { + t.Fatalf("exit %d: %s", got.code, got.stderr) + } + if output == "json" { + if !json.Valid([]byte(got.stdout)) { + t.Fatalf("invalid JSON %s", got.stdout) + } + } else if op.verb != "delete" && got.stdout == "" { + t.Error("missing text output") + } + base := "node-type-policies" + if group == "credential-policy" { + base = "credential-type-policies" + } + r := f.lastRequest() + if r.Method != op.method || r.URL.EscapedPath() != "/api/v1/"+base+op.path { + t.Errorf("request %s %s", r.Method, r.URL.EscapedPath()) + } + if op.input != "" { + assertCLIJSON(t, op.input, f.lastBody()) + } + if output == "text" && (op.verb == "create" || op.verb == "set") && op.resource != "attachment" && !strings.Contains(got.stderr, "notLoaded") { + t.Errorf("missing warning: %s", got.stderr) + } + }) + } + } + } +} +func TestPolicyMutationConsent(t *testing.T) { + for _, group := range []string{"node-policy", "credential-policy"} { + for _, op := range policyCLIOperations() { + if op.verb != "set" && op.verb != "delete" && op.verb != "create" { + continue + } + if group == "node-policy" && (op.resource == "instance" || op.resource == "project") { + continue + } + if op.verb != "create" { + for _, interactive := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/%s/%s/interactive=%t", group, op.resource, op.verb, interactive), func(t *testing.T) { + f := nodePolicyFixture(t, op.response) + f.interactive = interactive + f.stdin = "no\n" + args := policyCLIArgs(group, op) + if op.input != "" { + args = append(args, "--input", writeNodePolicyInput(t, op.input)) + } + before := f.requestCount() + got := f.run(args...) + if got.code == ExitSuccess || f.requestCount() != before || got.stdout != "" { + t.Fatalf("refusal failed: %+v requests %d", got, f.requestCount()-before) + } + }) + } + } + if op.input != "" { + t.Run(group+"/"+op.resource+"/"+op.verb+"/stdin", func(t *testing.T) { + f := nodePolicyFixture(t, op.response) + f.stdin = op.input + f.route = func(*http.Request, int) (int, string) { return op.status, op.response } + args := append(policyCLIArgs(group, op), "--input", "-") + before := f.requestCount() + got := f.run(args...) + if got.code == ExitSuccess || !strings.Contains(got.stderr, "--yes") || f.requestCount() != before { + t.Fatalf("stdin consent: %+v", got) + } + got = f.run(append(args, "--yes", "--output", "json")...) + if got.code != ExitSuccess { + t.Fatalf("stdin with consent: %+v", got) + } + }) + } + } + } +} +func TestPolicyStrictInputAndSelectors(t *testing.T) { + for _, group := range []string{"node-policy", "credential-policy"} { + for _, tt := range []struct{ name, resource, verb, input, want string }{ + {"unknown", "document", "create", `{"rules":[],"bad":true}`, "unknown field"}, + {"nested unknown", "document", "create", `{"rules":[{"id":"r","action":"deny","selector":{"kind":"name","value":"x","bad":1}}]}`, "unknown field"}, + {"read fields on create", "document", "create", cliPolicyDoc, "unknown field"}, + {"multiple docs", "document", "create", `{"rules":[]} {"rules":[]}`, "one document"}, + {"malformed", "document", "create", `{`, "decode"}, + {"too large", "document", "create", strings.Repeat(" ", (1<<20)+1), "exceeds"}, + {"null", "document", "create", `null`, "rules is required"}, + {"missing rules", "document", "create", `{}`, "rules is required"}, + {"null rules", "document", "create", `{"rules":null}`, "rules is required"}, + {"missing version", "document", "set", `{"rules":[]}`, "version"}, + {"duplicate rule", "document", "create", `{"rules":[{"id":"r","action":"allow","selector":{"kind":"name","value":"x"}},{"id":"r","action":"deny","selector":{"kind":"package","value":"x"}}]}`, "unique"}, + {"missing attachments", "attachment", "set", `{"version":1}`, "attachments is required"}, + {"null attachments", "attachment", "set", `{"attachments":null,"version":1}`, "attachments is required"}, + {"no attachment version", "attachment", "set", `{"attachments":[]}`, "version"}, + {"missing floor", "attachment", "set", `{"attachments":[{"policyId":"p","priority":0}],"version":1}`, "isFloor"}, + {"missing priority", "attachment", "set", `{"attachments":[{"policyId":"p","isFloor":false}],"version":1}`, "priority"}, + {"duplicate attachment", "attachment", "set", `{"attachments":[{"policyId":"p","priority":0,"isFloor":false},{"policyId":"p","priority":1,"isFloor":false}],"version":1}`, "unique"}, + {"duplicate ordering", "attachment", "set", `{"attachments":[{"policyId":"p","priority":0,"isFloor":false},{"policyId":"q","priority":0,"isFloor":false}],"version":1}`, "unique"}, + } { + t.Run(group+"/"+tt.name, func(t *testing.T) { + f := nodePolicyFixture(t, `{}`) + args := []string{group, tt.resource, tt.verb} + if tt.verb == "set" { + args = append(args, "p") + } + args = append(args, "--input", writeNodePolicyInput(t, tt.input), "--yes") + before := f.requestCount() + got := f.run(args...) + if got.code == ExitSuccess || !strings.Contains(got.stderr, tt.want) || f.requestCount() != before { + t.Fatalf("got %+v; want %q, zero requests", got, tt.want) + } + }) + } + for _, resource := range []string{"document", "instance", "project"} { + if group == "node-policy" && resource != "document" { + continue + } + t.Run(group+"/extends/"+resource, func(t *testing.T) { + input := `{"rules":[{"id":"r","action":"allow","selector":{"kind":"extends","value":"base"}}]}` + args := []string{group, resource, "create"} + response := cliPolicyResult + if resource != "document" { + input = strings.TrimSuffix(input, "}") + `,"defaultAction":"allow","version":0}` + args = []string{group, resource, "set"} + if resource == "project" { + args = append(args, "p") + } + response = cliNodePolicyWriteResult + } + f := nodePolicyFixture(t, response) + before := f.requestCount() + got := f.run(append(args, "--input", writeNodePolicyInput(t, input), "--yes")...) + if group == "node-policy" { + if got.code == ExitSuccess || f.requestCount() != before { + t.Fatalf("node accepted extends: %+v", got) + } + } else if got.code != ExitSuccess { + t.Fatalf("credential rejected extends: %+v", got) + } + }) + } + } +} +func TestPolicyDroppedReadFields(t *testing.T) { + for _, group := range []string{"node-policy", "credential-policy"} { + for _, resource := range []string{"document", "attachment"} { + t.Run(group+"/"+resource, func(t *testing.T) { + input := cliPolicyDoc + response := cliPolicyResult + wantBody := `{"rules":[],"version":2}` + wantDropped := "id" + if resource == "attachment" { + input = cliAttachments + response = cliAttachments + wantBody = `{"attachments":[{"policyId":"p1","priority":0,"isFloor":false}],"version":2}` + wantDropped = "attachments[0].rules" + } + f := nodePolicyFixture(t, response) + got := f.run(group, resource, "set", "p", "--input", writeNodePolicyInput(t, input), "--yes", "--output", "json") + if got.code != ExitSuccess || !strings.Contains(got.stderr, "Dropped read-only field "+wantDropped) { + t.Fatalf("got %+v", got) + } + assertCLIJSON(t, wantBody, f.lastBody()) + }) + } + } + f := nodePolicyFixture(t, cliNodePolicyWriteResult) + got := f.run("credential-policy", "instance", "set", "--input", writeNodePolicyInput(t, cliNodePolicyInput), "--yes") + if got.code != ExitSuccess || !strings.Contains(got.stderr, "Dropped read-only field scopeId") { + t.Fatalf("scope fields: %+v", got) + } +} +func TestPolicyListPagination(t *testing.T) { + for _, group := range []string{"node-policy", "credential-policy"} { + t.Run(group, func(t *testing.T) { + f := nodePolicyFixture(t, "") + calls := 0 + f.route = func(r *http.Request, _ int) (int, string) { + calls++ + if r.URL.Query().Get("limit") != "1" { + t.Error("lost limit") + } + cursor := r.URL.Query().Get("cursor") + next := "" + if calls == 1 { + if cursor != "start +" { + t.Error("lost starting cursor") + } + next = "next +" + } else if cursor != "next +" { + t.Error("lost cursor") + } + return 200, `{"data":[` + cliPolicyDoc + `],"nextCursor":"` + next + `"}` + } + got := f.run(group, "document", "list", "--all", "--limit", "1", "--cursor", "start +", "--output", "json") + if got.code != ExitSuccess { + t.Fatal(got.stderr) + } + var page struct { + Data []json.RawMessage `json:"data"` + Collection collectionInfo `json:"collection"` + } + if err := json.Unmarshal([]byte(got.stdout), &page); err != nil || len(page.Data) != 2 || calls != 2 || page.Collection.Truncated { + t.Fatalf("pagination %+v %d %v", page, calls, err) + } + }) + } +} +func TestPolicyErrorsAndArguments(t *testing.T) { + for _, group := range []string{"node-policy", "credential-policy"} { + for _, op := range policyCLIOperations() { + if group == "node-policy" && (op.resource == "instance" || op.resource == "project") { + continue + } + for _, status := range []int{401, 403, 404, 409, 503} { + t.Run(fmt.Sprintf("%s/%s/%s/%d", group, op.resource, op.verb, status), func(t *testing.T) { + f := nodePolicyFixture(t, "") + f.status = status + args := policyCLIArgs(group, op) + if op.input != "" { + args = append(args, "--input", writeNodePolicyInput(t, op.input)) + } + if op.input != "" || op.verb == "delete" { + args = append(args, "--yes") + } + got := f.run(args...) + if got.code == ExitSuccess || got.stdout != "" { + t.Fatalf("error result %+v", got) + } + want := fmt.Sprint(status) + if status == 401 { + want = "n8n auth login" + } + if !strings.Contains(got.stderr, want) { + t.Errorf("missing %q in %s", want, got.stderr) + } + if status == 403 || status == 404 || status == 503 { + resource := "nodetypepolicy" + if group == "credential-policy" { + resource = "credentialtypepolicy" + } + if !strings.Contains(got.stderr, "--resource "+resource) { + t.Errorf("bad discover key %s", got.stderr) + } + } + if status == 409 && op.verb == "delete" && !strings.Contains(got.stderr, "attachment set") { + t.Errorf("missing detach guidance %s", got.stderr) + } + }) + } + t.Run(group+"/"+op.resource+"/"+op.verb+"/arguments", func(t *testing.T) { + f := nodePolicyFixture(t, "") + before := f.requestCount() + args := policyCLIArgs(group, op) + got := f.run(append(args, "--output", "invalid")...) + if got.code == ExitSuccess || f.requestCount() != before { + t.Fatalf("output validation %+v", got) + } + if op.id != "" { + got = f.run(group, op.resource, op.verb) + if got.code == ExitSuccess || f.requestCount() != before { + t.Fatalf("arg validation %+v", got) + } + } + }) + } + } +} +func TestPolicyPreviewHelp(t *testing.T) { + root := NewRootCommand(Options{}) + for _, name := range []string{"node-policy", "credential-policy"} { + cmd, _, err := root.Find([]string{name}) + if err != nil { + t.Fatal(err) + } + var visit func(*cobra.Command) + visit = func(c *cobra.Command) { + if !strings.Contains(c.Long, "Preview API") { + t.Errorf("%s missing Preview API", c.CommandPath()) + } + for _, child := range c.Commands() { + visit(child) + } + } + visit(cmd) + } +} + +func TestPolicyListBoundAndEmpty(t *testing.T) { + for _, group := range []string{"node-policy", "credential-policy"} { + t.Run(group+"/bound", func(t *testing.T) { + f := nodePolicyFixture(t, "") + calls := 0 + data := strings.TrimSuffix(strings.Repeat(cliPolicyDoc+",", 250), ",") + f.route = func(r *http.Request, _ int) (int, string) { + calls++ + if calls > 40 { + t.Error("collection exceeded 10,000") + } + if r.URL.Query().Get("limit") != "250" { + t.Error("limit changed") + } + return 200, fmt.Sprintf(`{"data":[%s],"nextCursor":"page-%d"}`, data, calls) + } + got := f.run(group, "document", "list", "--all", "--limit", "250", "--output", "json") + var page struct { + Data []json.RawMessage `json:"data"` + Collection collectionInfo `json:"collection"` + NextCursor string `json:"nextCursor"` + } + if err := json.Unmarshal([]byte(got.stdout), &page); err != nil || got.code != ExitSuccess || len(page.Data) != 10000 || !page.Collection.Truncated || page.NextCursor != "page-40" || calls != 40 || !strings.Contains(got.stderr, "10,000") && !strings.Contains(got.stderr, "10000") { + t.Fatalf("bound: code=%d len=%d calls=%d collection=%+v stderr=%s err=%v", got.code, len(page.Data), calls, page.Collection, got.stderr, err) + } + }) + t.Run(group+"/empty", func(t *testing.T) { + f := nodePolicyFixture(t, `{"data":[],"nextCursor":""}`) + got := f.run(group, "document", "list", "--output", "json") + if got.code != ExitSuccess || !strings.Contains(got.stdout, `"data": []`) || !strings.Contains(got.stderr, "No policy documents") { + t.Fatalf("empty: %+v", got) + } + }) + } +} + +func TestCredentialProjectRejectsDelegateBeforeTransport(t *testing.T) { + for _, input := range []string{ + `{"rules":[],"defaultAction":"delegate","version":0}`, + `{"rules":[{"id":"r","action":"delegate","selector":{"kind":"extends","value":"base"}}],"defaultAction":"allow","version":0}`, + } { + f := nodePolicyFixture(t, "") + before := f.requestCount() + got := f.run("credential-policy", "project", "set", "p", "--input", writeNodePolicyInput(t, input), "--yes") + if got.code == ExitSuccess || !strings.Contains(got.stderr, "delegate") || f.requestCount() != before { + t.Fatalf("delegate rejection: %+v", got) + } + } +} diff --git a/internal/coverage/coverage_test.go b/internal/coverage/coverage_test.go index 42253e7..d3a5172 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 = 31 +const deliveredThrough = 33 // 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 db6dfaf..f8ad61f 100644 --- a/internal/coverage/manifest.json +++ b/internal/coverage/manifest.json @@ -1837,8 +1837,8 @@ "scope": "nodeTypePolicy:manage", "availability": "both", "phase": 32, - "command": "", - "status": "planned" + "command": "n8n node-policy document list", + "status": "implemented" }, { "operationId": "createNodeTypePolicyDocument", @@ -1848,8 +1848,8 @@ "scope": "nodeTypePolicy:manage", "availability": "both", "phase": 32, - "command": "", - "status": "planned" + "command": "n8n node-policy document create", + "status": "implemented" }, { "operationId": "getNodeTypePolicyDocument", @@ -1859,8 +1859,8 @@ "scope": "nodeTypePolicy:manage", "availability": "both", "phase": 32, - "command": "", - "status": "planned" + "command": "n8n node-policy document get", + "status": "implemented" }, { "operationId": "updateNodeTypePolicyDocument", @@ -1870,8 +1870,8 @@ "scope": "nodeTypePolicy:manage", "availability": "both", "phase": 32, - "command": "", - "status": "planned" + "command": "n8n node-policy document set", + "status": "implemented" }, { "operationId": "deleteNodeTypePolicyDocument", @@ -1881,8 +1881,8 @@ "scope": "nodeTypePolicy:manage", "availability": "both", "phase": 32, - "command": "", - "status": "planned" + "command": "n8n node-policy document delete", + "status": "implemented" }, { "operationId": "getNodeTypePolicyAttachments", @@ -1892,8 +1892,8 @@ "scope": "nodeTypePolicy:manage", "availability": "upstream-only", "phase": 32, - "command": "", - "status": "planned" + "command": "n8n node-policy attachment get", + "status": "implemented" }, { "operationId": "replaceNodeTypePolicyAttachments", @@ -1903,8 +1903,8 @@ "scope": "nodeTypePolicy:manage", "availability": "both", "phase": 32, - "command": "", - "status": "planned" + "command": "n8n node-policy attachment set", + "status": "implemented" }, { "operationId": "getCredentialTypeInstancePolicy", @@ -1914,8 +1914,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy instance get", + "status": "implemented" }, { "operationId": "putCredentialTypeInstancePolicy", @@ -1925,8 +1925,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy instance set", + "status": "implemented" }, { "operationId": "getCredentialTypeProjectPolicy", @@ -1936,8 +1936,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy project get", + "status": "implemented" }, { "operationId": "putCredentialTypeProjectPolicy", @@ -1947,8 +1947,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy project set", + "status": "implemented" }, { "operationId": "listCredentialTypePolicyDocuments", @@ -1958,8 +1958,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy document list", + "status": "implemented" }, { "operationId": "createCredentialTypePolicyDocument", @@ -1969,8 +1969,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy document create", + "status": "implemented" }, { "operationId": "getCredentialTypePolicyDocument", @@ -1980,8 +1980,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy document get", + "status": "implemented" }, { "operationId": "updateCredentialTypePolicyDocument", @@ -1991,8 +1991,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy document set", + "status": "implemented" }, { "operationId": "deleteCredentialTypePolicyDocument", @@ -2002,8 +2002,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy document delete", + "status": "implemented" }, { "operationId": "getCredentialTypePolicyAttachments", @@ -2013,8 +2013,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy attachment get", + "status": "implemented" }, { "operationId": "replaceCredentialTypePolicyAttachments", @@ -2024,8 +2024,8 @@ "scope": "credentialTypePolicy:manage", "availability": "upstream-only", "phase": 33, - "command": "", - "status": "planned" + "command": "n8n credential-policy attachment set", + "status": "implemented" } ] } diff --git a/internal/n8n/node_type_policy.go b/internal/n8n/node_type_policy.go index d2a06aa..c537ef3 100644 --- a/internal/n8n/node_type_policy.go +++ b/internal/n8n/node_type_policy.go @@ -3,7 +3,6 @@ package n8n import ( "context" "fmt" - "net/http" ) // NodeTypePolicyInstancePath is the instance-scope node type policy endpoint. @@ -28,6 +27,8 @@ type NodeTypePolicySelectorKind string const ( // NodeTypePolicySelectorName matches one node type by name. NodeTypePolicySelectorName NodeTypePolicySelectorKind = "name" + // NodeTypePolicySelectorExtends matches a credential type and its descendants. + NodeTypePolicySelectorExtends NodeTypePolicySelectorKind = "extends" // NodeTypePolicySelectorPackage matches every node type in a package. NodeTypePolicySelectorPackage NodeTypePolicySelectorKind = "package" ) @@ -129,8 +130,12 @@ func (r ReplaceNodeTypePolicyRequest) Validate(scope NodeTypePolicyScope) error if *r.Version < 0 { return fmt.Errorf("version must be 0 or greater, got %d", *r.Version) } - seen := make(map[string]int, len(r.Rules)) - for i, rule := range r.Rules { + return validatePolicyRules(r.Rules, scope, false) +} + +func validatePolicyRules(rules []NodeTypePolicyRule, scope NodeTypePolicyScope, credential bool) error { + seen := make(map[string]int, len(rules)) + for i, rule := range rules { if rule.ID == "" { return fmt.Errorf("rules[%d]: id is required and must not be empty", i) } @@ -143,9 +148,13 @@ func (r ReplaceNodeTypePolicyRequest) Validate(scope NodeTypePolicyScope) error } switch rule.Selector.Kind { case NodeTypePolicySelectorName, NodeTypePolicySelectorPackage: + case NodeTypePolicySelectorExtends: + if credential { + break + } + fallthrough default: - return fmt.Errorf("rules[%d] (%s): selector.kind must be %s or %s, got %q", - i, rule.ID, NodeTypePolicySelectorName, NodeTypePolicySelectorPackage, rule.Selector.Kind) + return fmt.Errorf("rules[%d] (%s): selector.kind must be %s, got %q", i, rule.ID, selectorHelp(credential), rule.Selector.Kind) } if rule.Selector.Value == "" { return fmt.Errorf("rules[%d] (%s): selector.value is required and must not be empty", i, rule.ID) @@ -186,71 +195,20 @@ func (r ReplaceNodeTypePolicyRequest) normalized() ReplaceNodeTypePolicyRequest // GetInstanceNodeTypePolicy returns the composed instance-scope policy. func (c *Client) GetInstanceNodeTypePolicy(ctx context.Context) (*NodeTypePolicy, error) { - var policy NodeTypePolicy - if _, err := c.Do(ctx, Request{Path: NodeTypePolicyInstancePath}, &policy); err != nil { - return nil, err - } - return &policy, nil + return c.NodeTypePolicies().GetInstance(ctx) } -// ReplaceInstanceNodeTypePolicy replaces the instance default action and the -// rules of its single policy document. A stale Version is rejected with 409. +// ReplaceInstanceNodeTypePolicy replaces only the instance default and own document. func (c *Client) ReplaceInstanceNodeTypePolicy(ctx context.Context, request ReplaceNodeTypePolicyRequest) (*NodeTypePolicyWriteResult, error) { - if err := request.Validate(NodeTypePolicyScopeInstance); err != nil { - return nil, err - } - var result NodeTypePolicyWriteResult - if _, err := c.Do(ctx, Request{ - Method: http.MethodPut, - Path: NodeTypePolicyInstancePath, - Body: request.normalized(), - }, &result); err != nil { - return nil, err - } - return &result, nil + return c.NodeTypePolicies().ReplaceInstance(ctx, request) } -// GetProjectNodeTypePolicy returns the project's own composed policy. It is not -// combined with the instance policy; that composition happens at evaluation. +// GetProjectNodeTypePolicy returns the project's own composed policy. func (c *Client) GetProjectNodeTypePolicy(ctx context.Context, projectID string) (*NodeTypePolicy, error) { - if err := validateNodeTypePolicyProjectID(projectID); err != nil { - return nil, err - } - var policy NodeTypePolicy - if _, err := c.Do(ctx, Request{Path: nodeTypePolicyProjectPath(projectID)}, &policy); err != nil { - return nil, err - } - return &policy, nil + return c.NodeTypePolicies().GetProject(ctx, projectID) } -// ReplaceProjectNodeTypePolicy replaces one project's default action and the -// rules of its single policy document. A stale Version is rejected with 409, as -// is a policy document shared with another scope. +// ReplaceProjectNodeTypePolicy replaces only the project's default and own document. func (c *Client) ReplaceProjectNodeTypePolicy(ctx context.Context, projectID string, request ReplaceNodeTypePolicyRequest) (*NodeTypePolicyWriteResult, error) { - if err := validateNodeTypePolicyProjectID(projectID); err != nil { - return nil, err - } - if err := request.Validate(NodeTypePolicyScopeProject); err != nil { - return nil, err - } - var result NodeTypePolicyWriteResult - if _, err := c.Do(ctx, Request{ - Method: http.MethodPut, - Path: nodeTypePolicyProjectPath(projectID), - Body: request.normalized(), - }, &result); err != nil { - return nil, err - } - return &result, nil -} - -func nodeTypePolicyProjectPath(projectID string) string { - return PathJoin("node-type-policies", "projects", projectID) -} - -func validateNodeTypePolicyProjectID(projectID string) error { - if projectID == "" { - return fmt.Errorf("project ID is required") - } - return nil + return c.NodeTypePolicies().ReplaceProject(ctx, projectID, request) } diff --git a/internal/n8n/policy.go b/internal/n8n/policy.go new file mode 100644 index 0000000..6583ad4 --- /dev/null +++ b/internal/n8n/policy.go @@ -0,0 +1,326 @@ +package n8n + +import ( + "context" + "fmt" + "net/http" + "strings" +) + +// PolicyClient implements the shared Preview API for node and credential policies. +// Obtain it from Client.NodeTypePolicies or Client.CredentialTypePolicies. +type PolicyClient struct { + client *Client + base string + credential bool +} + +// NodeTypePolicies returns the node type policy API. +func (c *Client) NodeTypePolicies() PolicyClient { + return PolicyClient{client: c, base: "node-type-policies"} +} + +// CredentialTypePolicies returns the credential type policy API, including extends selectors. +func (c *Client) CredentialTypePolicies() PolicyClient { + return PolicyClient{client: c, base: "credential-type-policies", credential: true} +} + +// PolicyDocument is a reusable rule list. Kind is server-defined, without a closed enum. +type PolicyDocument struct { + ID string `json:"id"` + Kind string `json:"kind"` + Rules []NodeTypePolicyRule `json:"rules"` + Version int `json:"version"` + UpdatedBy string `json:"updatedBy"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` +} + +// PolicyDocumentWriteResult contains the stored document and non-fatal warnings. +type PolicyDocumentWriteResult struct { + Policy PolicyDocument `json:"policy"` + Warnings []NodeTypePolicyWarning `json:"warnings"` +} + +// CreatePolicyDocumentRequest contains only writable creation fields. +type CreatePolicyDocumentRequest struct { + Rules []NodeTypePolicyRule `json:"rules"` +} + +// UpdatePolicyDocumentRequest replaces every rule using the document's last-read version. +type UpdatePolicyDocumentRequest struct { + Rules []NodeTypePolicyRule `json:"rules"` + Version *int `json:"version"` +} + +// PolicyAttachment is an attached document, in server evaluation order. +type PolicyAttachment struct { + PolicyID string `json:"policyId"` + Rules []NodeTypePolicyRule `json:"rules"` + Priority int `json:"priority"` + IsFloor bool `json:"isFloor"` +} + +// PolicyAttachments contains attachments and the scope's version. +type PolicyAttachments struct { + Attachments []PolicyAttachment `json:"attachments"` + Version int `json:"version"` +} + +// PolicyAttachmentInput distinguishes omitted required fields from false and zero. +type PolicyAttachmentInput struct { + PolicyID string `json:"policyId"` + Priority *int `json:"priority"` + IsFloor *bool `json:"isFloor"` +} + +// ReplacePolicyAttachmentsRequest fully replaces a scope's attachments. +type ReplacePolicyAttachmentsRequest struct { + Attachments []PolicyAttachmentInput `json:"attachments"` + Version *int `json:"version"` +} + +func selectorHelp(credential bool) string { + if credential { + return "name, package, or extends" + } + return "name or package" +} +func validatePolicyID(kind, id string) error { + if strings.TrimSpace(id) == "" { + return fmt.Errorf("%s ID is required", kind) + } + return nil +} +func validatePolicyVersion(v *int) error { + if v == nil { + return fmt.Errorf("version is required: send the version last read") + } + if *v < 0 { + return fmt.Errorf("version must be 0 or greater") + } + return nil +} + +// ValidateRules checks selectors, actions, and unique rule IDs for this policy kind. +func (p PolicyClient) ValidateRules(rules []NodeTypePolicyRule, scope NodeTypePolicyScope) error { + return validatePolicyRules(rules, scope, p.credential) +} + +// ValidateScope checks a scope replacement before transport. +func (p PolicyClient) ValidateScope(r ReplaceNodeTypePolicyRequest, scope NodeTypePolicyScope) error { + if !p.credential { + return r.Validate(scope) + } + if r.DefaultAction == nil { + return fmt.Errorf("defaultAction is required: %s", nodeTypePolicyActionHelp(scope)) + } + if err := validateNodeTypePolicyAction(*r.DefaultAction, scope); err != nil { + return fmt.Errorf("defaultAction: %w", err) + } + if err := validatePolicyVersion(r.Version); err != nil { + return err + } + return p.ValidateRules(r.Rules, scope) +} + +// Validate checks required fields and attachment uniqueness before transport. +func (r ReplacePolicyAttachmentsRequest) Validate() error { + if err := validatePolicyVersion(r.Version); err != nil { + return err + } + ids := map[string]bool{} + pairs := map[struct { + floor bool + priority int + }]bool{} + for i, a := range r.Attachments { + if err := validatePolicyID("policy", a.PolicyID); err != nil { + return fmt.Errorf("attachments[%d]: %w", i, err) + } + if a.Priority == nil || a.IsFloor == nil { + return fmt.Errorf("attachments[%d]: priority and isFloor are required", i) + } + if ids[a.PolicyID] { + return fmt.Errorf("attachments[%d]: policyId %q must be unique", i, a.PolicyID) + } + ids[a.PolicyID] = true + pair := struct { + floor bool + priority int + }{*a.IsFloor, *a.Priority} + if pairs[pair] { + return fmt.Errorf("attachments[%d]: (isFloor, priority) pair must be unique", i) + } + pairs[pair] = true + } + return nil +} +func (p PolicyClient) scopePath(projectID string) string { + if projectID == "" { + return PathJoin(p.base, "instance") + } + return PathJoin(p.base, "projects", projectID) +} + +// GetInstance returns the composed instance policy. +func (p PolicyClient) GetInstance(ctx context.Context) (*NodeTypePolicy, error) { + return p.getScope(ctx, "") +} + +// GetProject returns the composed project policy, without instance evaluation. +func (p PolicyClient) GetProject(ctx context.Context, id string) (*NodeTypePolicy, error) { + if err := validatePolicyID("project", id); err != nil { + return nil, err + } + return p.getScope(ctx, id) +} +func (p PolicyClient) getScope(ctx context.Context, id string) (*NodeTypePolicy, error) { + result := NodeTypePolicy{Rules: []NodeTypePolicyRule{}} + _, err := p.client.Do(ctx, Request{Path: p.scopePath(id)}, &result) + if err != nil { + return nil, err + } + return &result, nil +} + +// ReplaceInstance replaces only the instance scope's own document and default. +func (p PolicyClient) ReplaceInstance(ctx context.Context, r ReplaceNodeTypePolicyRequest) (*NodeTypePolicyWriteResult, error) { + return p.replaceScope(ctx, "", r) +} + +// ReplaceProject replaces only a project's own document and default. +func (p PolicyClient) ReplaceProject(ctx context.Context, id string, r ReplaceNodeTypePolicyRequest) (*NodeTypePolicyWriteResult, error) { + if err := validatePolicyID("project", id); err != nil { + return nil, err + } + return p.replaceScope(ctx, id, r) +} +func (p PolicyClient) replaceScope(ctx context.Context, id string, r ReplaceNodeTypePolicyRequest) (*NodeTypePolicyWriteResult, error) { + scope := NodeTypePolicyScopeInstance + if id != "" { + scope = NodeTypePolicyScopeProject + } + if err := p.ValidateScope(r, scope); err != nil { + return nil, err + } + result := NodeTypePolicyWriteResult{NodeTypePolicy: NodeTypePolicy{Rules: []NodeTypePolicyRule{}}, Warnings: []NodeTypePolicyWarning{}} + _, err := p.client.Do(ctx, Request{Method: http.MethodPut, Path: p.scopePath(id), Body: r.normalized()}, &result) + if err != nil { + return nil, err + } + return &result, nil +} + +// ListDocuments returns one cursor page, using a default page size of 100. +func (p PolicyClient) ListDocuments(ctx context.Context, o ListOptions) (Page[PolicyDocument], error) { + if err := o.Validate(); err != nil { + return Page[PolicyDocument]{}, err + } + if o.Limit > 250 { + return Page[PolicyDocument]{}, fmt.Errorf("limit must be between 1 and 250") + } + if o.Limit == 0 { + o.Limit = 100 + } + var page Page[PolicyDocument] + _, err := p.client.Do(ctx, Request{Path: PathJoin(p.base, "policies"), Query: o.Apply(nil)}, &page) + if page.Data == nil { + page.Data = []PolicyDocument{} + } + // A short page is terminal, even if a server erroneously offers another cursor. + if len(page.Data) < o.Limit { + page.NextCursor = "" + } + return page, err +} + +// GetDocument retrieves a reusable policy document. +func (p PolicyClient) GetDocument(ctx context.Context, id string) (*PolicyDocument, error) { + if err := validatePolicyID("policy", id); err != nil { + return nil, err + } + result := PolicyDocument{Rules: []NodeTypePolicyRule{}} + _, err := p.client.Do(ctx, Request{Path: PathJoin(p.base, "policies", id)}, &result) + if err != nil { + return nil, err + } + return &result, nil +} + +// CreateDocument creates an unattached reusable document. +func (p PolicyClient) CreateDocument(ctx context.Context, r CreatePolicyDocumentRequest) (*PolicyDocumentWriteResult, error) { + if err := p.ValidateRules(r.Rules, NodeTypePolicyScopeInstance); err != nil { + return nil, err + } + if r.Rules == nil { + r.Rules = []NodeTypePolicyRule{} + } + return p.writeDocument(ctx, http.MethodPost, PathJoin(p.base, "policies"), r) +} + +// UpdateDocument replaces every rule and bumps every attached scope's version. +func (p PolicyClient) UpdateDocument(ctx context.Context, id string, r UpdatePolicyDocumentRequest) (*PolicyDocumentWriteResult, error) { + if err := validatePolicyID("policy", id); err != nil { + return nil, err + } + if err := validatePolicyVersion(r.Version); err != nil { + return nil, err + } + if err := p.ValidateRules(r.Rules, NodeTypePolicyScopeInstance); err != nil { + return nil, err + } + if r.Rules == nil { + r.Rules = []NodeTypePolicyRule{} + } + return p.writeDocument(ctx, http.MethodPut, PathJoin(p.base, "policies", id), r) +} +func (p PolicyClient) writeDocument(ctx context.Context, method, path string, body any) (*PolicyDocumentWriteResult, error) { + result := PolicyDocumentWriteResult{Policy: PolicyDocument{Rules: []NodeTypePolicyRule{}}, Warnings: []NodeTypePolicyWarning{}} + _, err := p.client.Do(ctx, Request{Method: method, Path: path, Body: body}, &result) + if err != nil { + return nil, err + } + return &result, nil +} + +// DeleteDocument deletes an unattached document; attached documents return 409. +func (p PolicyClient) DeleteDocument(ctx context.Context, id string) error { + if err := validatePolicyID("policy", id); err != nil { + return err + } + _, err := p.client.Do(ctx, Request{Method: http.MethodDelete, Path: PathJoin(p.base, "policies", id)}, nil) + return err +} + +// GetAttachments returns attachments in floor-first, then ascending priority order. +func (p PolicyClient) GetAttachments(ctx context.Context, id string) (*PolicyAttachments, error) { + if err := validatePolicyID("scope", id); err != nil { + return nil, err + } + result := PolicyAttachments{Attachments: []PolicyAttachment{}} + _, err := p.client.Do(ctx, Request{Path: PathJoin(p.base, "scopes", id, "attachments")}, &result) + if err != nil { + return nil, err + } + return &result, nil +} + +// ReplaceAttachments fully replaces attachments using the scope's last-read version. +func (p PolicyClient) ReplaceAttachments(ctx context.Context, id string, r ReplacePolicyAttachmentsRequest) (*PolicyAttachments, error) { + if err := validatePolicyID("scope", id); err != nil { + return nil, err + } + if err := r.Validate(); err != nil { + return nil, err + } + if r.Attachments == nil { + r.Attachments = []PolicyAttachmentInput{} + } + result := PolicyAttachments{Attachments: []PolicyAttachment{}} + _, err := p.client.Do(ctx, Request{Method: http.MethodPut, Path: PathJoin(p.base, "scopes", id, "attachments"), Body: r}, &result) + if err != nil { + return nil, err + } + return &result, nil +} diff --git a/internal/n8n/policy_test.go b/internal/n8n/policy_test.go new file mode 100644 index 0000000..d844aa1 --- /dev/null +++ b/internal/n8n/policy_test.go @@ -0,0 +1,303 @@ +package n8n + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + "time" +) + +const policyDocumentJSON = `{"id":"p1","kind":"future-kind","rules":[],"version":2,"updatedBy":"u1","createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-02T00:00:00Z"}` +const policyDocumentResultJSON = `{"policy":` + policyDocumentJSON + `,"warnings":[{"kind":"notLoaded","ruleId":"r1"}]}` +const policyAttachmentsJSON = `{"attachments":[{"policyId":"p1","rules":[],"priority":0,"isFloor":false}],"version":2}` + +func policyTestAPIs(c *Client) map[string]PolicyClient { + return map[string]PolicyClient{"node-type-policies": c.NodeTypePolicies(), "credential-type-policies": c.CredentialTypePolicies()} +} +func policyBool(v bool) *bool { return &v } + +type policyOperation struct { + name, method, path, body, response string + status int + call func(context.Context, PolicyClient) error +} + +func policyOperations() []policyOperation { + return []policyOperation{ + {"list", "GET", "/policies", "", `{"data":[` + policyDocumentJSON + `],"nextCursor":"next"}`, 200, func(ctx context.Context, p PolicyClient) error { + r, e := p.ListDocuments(ctx, ListOptions{Limit: 1, Cursor: "a+/ b"}) + if e == nil && (len(r.Data) != 1 || r.Data[0].Kind != "future-kind" || r.NextCursor != "next") { + return errors.New("list decode lost fields") + } + return e + }}, + {"get", "GET", "/policies/a%2Fb%20c", "", policyDocumentJSON, 200, func(ctx context.Context, p PolicyClient) error { + r, e := p.GetDocument(ctx, "a/b c") + if e == nil && (r.ID != "p1" || r.Version != 2 || r.UpdatedBy != "u1") { + return errors.New("document decode lost fields") + } + return e + }}, + {"create", "POST", "/policies", `{"rules":[]}`, policyDocumentResultJSON, 201, func(ctx context.Context, p PolicyClient) error { + r, e := p.CreateDocument(ctx, CreatePolicyDocumentRequest{}) + if e == nil && r.Policy.ID != "" && (r.Policy.ID != "p1" || len(r.Warnings) != 1) { + return errors.New("write decode lost fields") + } + return e + }}, + {"update", "PUT", "/policies/a%2Fb%20c", `{"rules":[],"version":2}`, policyDocumentResultJSON, 200, func(ctx context.Context, p PolicyClient) error { + _, e := p.UpdateDocument(ctx, "a/b c", UpdatePolicyDocumentRequest{Version: version(2)}) + return e + }}, + {"delete", "DELETE", "/policies/a%2Fb%20c", "", "", 204, func(ctx context.Context, p PolicyClient) error { return p.DeleteDocument(ctx, "a/b c") }}, + {"attachments get", "GET", "/scopes/a%2Fb%20c/attachments", "", policyAttachmentsJSON, 200, func(ctx context.Context, p PolicyClient) error { + r, e := p.GetAttachments(ctx, "a/b c") + if e == nil && (len(r.Attachments) != 1 || r.Version != 2 || r.Attachments[0].IsFloor) { + return errors.New("attachment decode lost fields") + } + return e + }}, + {"attachments replace", "PUT", "/scopes/a%2Fb%20c/attachments", `{"attachments":[{"policyId":"p1","priority":0,"isFloor":false}],"version":2}`, policyAttachmentsJSON, 200, func(ctx context.Context, p PolicyClient) error { + _, e := p.ReplaceAttachments(ctx, "a/b c", ReplacePolicyAttachmentsRequest{Attachments: []PolicyAttachmentInput{{PolicyID: "p1", Priority: version(0), IsFloor: policyBool(false)}}, Version: version(2)}) + return e + }}, + {"instance get", "GET", "/instance", "", unconfiguredNodeTypePolicyResponse, 200, func(ctx context.Context, p PolicyClient) error { + r, e := p.GetInstance(ctx) + if e == nil && (r.Configured() || r.Version != 0) { + return errors.New("scope decode lost fields") + } + return e + }}, + {"project get", "GET", "/projects/a%2Fb%20c", "", unconfiguredNodeTypePolicyResponse, 200, func(ctx context.Context, p PolicyClient) error { _, e := p.GetProject(ctx, "a/b c"); return e }}, + {"instance replace", "PUT", "/instance", `{"rules":[],"defaultAction":"allow","version":0}`, nodeTypePolicyWriteResponse, 200, func(ctx context.Context, p PolicyClient) error { + _, e := p.ReplaceInstance(ctx, ReplaceNodeTypePolicyRequest{DefaultAction: action(NodeTypePolicyAllow), Version: version(0)}) + return e + }}, + {"project replace", "PUT", "/projects/a%2Fb%20c", `{"rules":[],"defaultAction":"allow","version":0}`, nodeTypePolicyWriteResponse, 200, func(ctx context.Context, p PolicyClient) error { + _, e := p.ReplaceProject(ctx, "a/b c", ReplaceNodeTypePolicyRequest{DefaultAction: action(NodeTypePolicyAllow), Version: version(0)}) + return e + }}, + } +} +func TestPolicyTransport(t *testing.T) { + for _, group := range []string{"node-type-policies", "credential-type-policies"} { + for _, op := range policyOperations() { + t.Run(group+"/"+op.name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(op.status, op.response)) + p := policyTestAPIs(server.client(t))[group] + if err := op.call(context.Background(), p); err != nil { + t.Fatal(err) + } + req, body := server.last(t) + if req.Method != op.method || req.URL.EscapedPath() != BasePath+"/"+group+op.path { + t.Errorf("request: %s %s", req.Method, req.URL.EscapedPath()) + } + if req.Header.Get(HeaderAPIKey) != "community-secret" { + t.Error("missing auth") + } + if op.body == "" { + if body != "" { + t.Errorf("unexpected body %q", body) + } + } else { + assertJSONEqual(t, op.body, body) + if req.Header.Get("Content-Type") != contentTypeJSON { + t.Error("missing JSON content type") + } + } + if op.name == "list" { + if req.URL.Query().Get("cursor") != "a+/ b" || req.URL.Query().Get("limit") != "1" || strings.Contains(req.URL.RawQuery, " ") { + t.Errorf("bad query %s", req.URL.RawQuery) + } + } else if req.URL.RawQuery != "" { + t.Errorf("unexpected query %s", req.URL.RawQuery) + } + }) + } + } +} +func TestPolicyFailuresAndCancellation(t *testing.T) { + for _, group := range []string{"node-type-policies", "credential-type-policies"} { + for _, op := range policyOperations() { + t.Run(group+"/"+op.name, func(t *testing.T) { + for _, status := range []int{400, 401, 403, 404, 409, 415, 422, 503} { + server := newCommunityPackageServer(t, packageJSONHandler(status, `{"message":"refused"}`)) + p := policyTestAPIs(server.client(t))[group] + if err := op.call(context.Background(), p); StatusCodeOf(err) != status { + t.Errorf("status %d: %v", status, err) + } + } + server := newCommunityPackageServer(t, packageJSONHandler(op.status, `{`)) + p := policyTestAPIs(server.client(t))[group] + if op.method != "DELETE" { + if err := op.call(context.Background(), p); err == nil { + t.Error("accepted malformed JSON") + } + } + before := len(server.requests) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := op.call(ctx, p); !errors.Is(err, context.Canceled) { + t.Errorf("cancellation: %v", err) + } + ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + if err := op.call(ctx, p); !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("deadline: %v", err) + } + if len(server.requests) != before { + t.Error("canceled request reached server") + } + }) + } + } + // Successful creation may have an empty body; deletion always does. + server := newCommunityPackageServer(t, packageJSONHandler(201, "")) + if _, err := server.client(t).NodeTypePolicies().CreateDocument(context.Background(), CreatePolicyDocumentRequest{}); err != nil { + t.Fatal(err) + } +} +func TestPolicyLocalValidation(t *testing.T) { + rule := NodeTypePolicyRule{ID: "r", Action: NodeTypePolicyAllow, Selector: NodeTypePolicySelector{Kind: NodeTypePolicySelectorName, Value: "x"}} + cases := []struct { + name string + call func(PolicyClient) error + }{ + {"empty policy", func(p PolicyClient) error { _, e := p.GetDocument(context.Background(), ""); return e }}, + {"empty scope", func(p PolicyClient) error { _, e := p.GetAttachments(context.Background(), " "); return e }}, + {"empty project", func(p PolicyClient) error { _, e := p.GetProject(context.Background(), ""); return e }}, + {"missing version", func(p PolicyClient) error { + _, e := p.UpdateDocument(context.Background(), "p", UpdatePolicyDocumentRequest{}) + return e + }}, + {"negative version", func(p PolicyClient) error { + _, e := p.UpdateDocument(context.Background(), "p", UpdatePolicyDocumentRequest{Version: version(-1)}) + return e + }}, + {"limit", func(p PolicyClient) error { + _, e := p.ListDocuments(context.Background(), ListOptions{Limit: 251}) + return e + }}, + {"negative limit", func(p PolicyClient) error { + _, e := p.ListDocuments(context.Background(), ListOptions{Limit: -1}) + return e + }}, + {"duplicate rule", func(p PolicyClient) error { + _, e := p.CreateDocument(context.Background(), CreatePolicyDocumentRequest{Rules: []NodeTypePolicyRule{rule, rule}}) + return e + }}, + {"invalid rule action", func(p PolicyClient) error { + r := rule + r.Action = "bad" + return p.ValidateRules([]NodeTypePolicyRule{r}, NodeTypePolicyScopeInstance) + }}, + {"empty rule id", func(p PolicyClient) error { + r := rule + r.ID = "" + return p.ValidateRules([]NodeTypePolicyRule{r}, NodeTypePolicyScopeInstance) + }}, + {"empty selector value", func(p PolicyClient) error { + r := rule + r.Selector.Value = "" + return p.ValidateRules([]NodeTypePolicyRule{r}, NodeTypePolicyScopeInstance) + }}, + {"bad selector", func(p PolicyClient) error { + r := rule + r.Selector.Kind = "unknown" + return p.ValidateRules([]NodeTypePolicyRule{r}, NodeTypePolicyScopeInstance) + }}, + {"project delegate", func(p PolicyClient) error { + r := rule + r.Action = NodeTypePolicyDelegate + _, e := p.ReplaceProject(context.Background(), "p", ReplaceNodeTypePolicyRequest{Rules: []NodeTypePolicyRule{r}, Version: version(0), DefaultAction: action(NodeTypePolicyAllow)}) + return e + }}, + } + for _, group := range []string{"node-type-policies", "credential-type-policies"} { + for _, tt := range cases { + t.Run(group+"/"+tt.name, func(t *testing.T) { + s := newCommunityPackageServer(t, packageJSONHandler(200, `{}`)) + if err := tt.call(policyTestAPIs(s.client(t))[group]); err == nil { + t.Error("expected local error") + } + if len(s.requests) != 0 { + t.Error("validation reached transport") + } + }) + } + } + rule.Selector.Kind = NodeTypePolicySelectorExtends + s := newCommunityPackageServer(t, packageJSONHandler(201, policyDocumentResultJSON)) + if _, err := s.client(t).NodeTypePolicies().CreateDocument(context.Background(), CreatePolicyDocumentRequest{Rules: []NodeTypePolicyRule{rule}}); err == nil { + t.Error("node policy accepted extends") + } + if _, err := s.client(t).CredentialTypePolicies().CreateDocument(context.Background(), CreatePolicyDocumentRequest{Rules: []NodeTypePolicyRule{rule}}); err != nil { + t.Fatal(err) + } +} +func TestPolicyAttachmentValidation(t *testing.T) { + a := PolicyAttachmentInput{PolicyID: "p", Priority: version(0), IsFloor: policyBool(false)} + for _, tt := range []struct { + name string + r ReplacePolicyAttachmentsRequest + }{ + {"no version", ReplacePolicyAttachmentsRequest{}}, + {"negative version", ReplacePolicyAttachmentsRequest{Version: version(-1)}}, + {"empty ID", ReplacePolicyAttachmentsRequest{Version: version(1), Attachments: []PolicyAttachmentInput{{Priority: version(0), IsFloor: policyBool(false)}}}}, + {"missing priority", ReplacePolicyAttachmentsRequest{Version: version(1), Attachments: []PolicyAttachmentInput{{PolicyID: "p", IsFloor: policyBool(false)}}}}, + {"missing floor", ReplacePolicyAttachmentsRequest{Version: version(1), Attachments: []PolicyAttachmentInput{{PolicyID: "p", Priority: version(0)}}}}, + {"duplicate ID", ReplacePolicyAttachmentsRequest{Version: version(1), Attachments: []PolicyAttachmentInput{a, {PolicyID: "p", Priority: version(1), IsFloor: policyBool(false)}}}}, + {"duplicate pair", ReplacePolicyAttachmentsRequest{Version: version(1), Attachments: []PolicyAttachmentInput{a, {PolicyID: "other", Priority: version(0), IsFloor: policyBool(false)}}}}, + } { + t.Run(tt.name, func(t *testing.T) { + s := newCommunityPackageServer(t, packageJSONHandler(200, policyAttachmentsJSON)) + if _, err := s.client(t).NodeTypePolicies().ReplaceAttachments(context.Background(), "s", tt.r); err == nil { + t.Error("expected local error") + } + if len(s.requests) != 0 { + t.Error("request sent") + } + }) + } + r := ReplacePolicyAttachmentsRequest{Version: version(1), Attachments: []PolicyAttachmentInput{a, {PolicyID: "other", Priority: version(0), IsFloor: policyBool(true)}}} + if err := r.Validate(); err != nil { + t.Errorf("same priority in separate floor groups: %v", err) + } +} +func TestPolicyDocumentPagination(t *testing.T) { + for _, group := range []string{"node-type-policies", "credential-type-policies"} { + t.Run(group, func(t *testing.T) { + calls := 0 + s := newCommunityPackageServer(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + calls++ + if r.URL.Query().Get("limit") != "1" { + t.Error("lost page limit") + } + cursor := r.URL.Query().Get("cursor") + next := "" + if calls == 1 { + if cursor != "start +" { + t.Error("lost starting cursor") + } + next = "next +" + } else if cursor != "next +" { + t.Error("lost cursor") + } + _ = json.NewEncoder(w).Encode(Page[PolicyDocument]{Data: []PolicyDocument{{ID: "p"}}, NextCursor: next}) + }) + result, err := Collect(context.Background(), policyTestAPIs(s.client(t))[group].ListDocuments, ListOptions{Limit: 1, Cursor: "start +"}, 0) + if err != nil || len(result) != 2 || calls != 2 { + t.Fatalf("result %v calls %d err %v", result, calls, err) + } + }) + } + s := newCommunityPackageServer(t, packageJSONHandler(200, `{"data":[`+policyDocumentJSON+`],"nextCursor":"bad"}`)) + p, err := s.client(t).NodeTypePolicies().ListDocuments(context.Background(), ListOptions{}) + if err != nil || p.NextCursor != "" { + t.Errorf("short page should stop: %+v %v", p, err) + } +} diff --git a/test/integration/policy_documents_test.go b/test/integration/policy_documents_test.go new file mode 100644 index 0000000..97fecd8 --- /dev/null +++ b/test/integration/policy_documents_test.go @@ -0,0 +1,242 @@ +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "testing" + "time" + + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" + "github.com/SomeoneWithOptions/n8n-cli/test/integration" +) + +func skipUnlessPolicyAPI(t *testing.T, err error) { + t.Helper() + if n8n.IsForbidden(err) || n8n.IsNotFound(err) || n8n.IsStatus(err, http.StatusServiceUnavailable) { + t.Skipf("policy Preview API unavailable to integration credential: %v", err) + } +} +func integrationPolicyAPIs(c *n8n.Client) map[string]n8n.PolicyClient { + return map[string]n8n.PolicyClient{"node-policy": c.NodeTypePolicies(), "credential-policy": c.CredentialTypePolicies()} +} + +// Reads never change instance/project attachments or existing documents. +func TestPolicyDocumentsReadOnly(t *testing.T) { + instance := integration.Require(t) + ctx := context.Background() + for group, api := range integrationPolicyAPIs(instance.Client(t)) { + t.Run(group, func(t *testing.T) { + page, err := api.ListDocuments(ctx, n8n.ListOptions{Limit: 10}) + skipUnlessPolicyAPI(t, err) + if err != nil { + t.Fatal(err) + } + for _, doc := range page.Data { + got, err := api.GetDocument(ctx, doc.ID) + if err != nil { + t.Fatal(err) + } + if got.ID != doc.ID || got.Version < 1 { + t.Errorf("invalid policy document: %+v", got) + } + } + scope, err := api.GetInstance(ctx) + skipUnlessPolicyAPI(t, err) + if err != nil { + t.Fatal(err) + } + if scope.ScopeID != nil { + attachments, err := api.GetAttachments(ctx, *scope.ScopeID) + skipUnlessPolicyAPI(t, err) + if err != nil { + t.Fatal(err) + } + if attachments.Version < 1 { + t.Errorf("invalid attachments version %d", attachments.Version) + } + } + out := runNodePolicyCLI(t, instance, group, "document", "list", "--limit", "10", "--output", "json") + var fromCLI n8n.Page[n8n.PolicyDocument] + if err := json.Unmarshal([]byte(out), &fromCLI); err != nil { + t.Fatalf("CLI JSON: %v", err) + } + if group == "credential-policy" { + out = runNodePolicyCLI(t, instance, group, "instance", "get", "--output", "json") + var policy n8n.NodeTypePolicy + if err := json.Unmarshal([]byte(out), &policy); err != nil { + t.Fatal(err) + } + } + }) + } +} + +// Documents have no name field; use the required prefix on their unique rule IDs. +// They stay unattached, so this lifecycle never changes existing scope evaluation. +func TestPolicyDocumentLifecycle(t *testing.T) { + instance := integration.RequireDestructive(t) + ctx := context.Background() + for group, api := range integrationPolicyAPIs(instance.Client(t)) { + t.Run(group, func(t *testing.T) { + ruleID := fmt.Sprintf("%spolicy-%d", integration.ResourcePrefix, time.Now().UnixNano()) + rules := []n8n.NodeTypePolicyRule{{ID: ruleID, Action: n8n.NodeTypePolicyAllow, Selector: n8n.NodeTypePolicySelector{Kind: n8n.NodeTypePolicySelectorPackage, Value: integration.ResourcePrefix + "uninstalled"}}} + created, err := api.CreateDocument(ctx, n8n.CreatePolicyDocumentRequest{Rules: rules}) + skipUnlessPolicyAPI(t, err) + if err != nil { + t.Fatal(err) + } + id := created.Policy.ID + deleted := false + t.Cleanup(func() { + if !deleted && id != "" { + if err := api.DeleteDocument(context.Background(), id); err != nil { + t.Errorf("cleanup document %q: %v", id, err) + } + } + }) + if id == "" || created.Policy.Version < 1 { + t.Fatalf("invalid created document: %+v", created.Policy) + } + got, err := api.GetDocument(ctx, id) + if err != nil { + t.Fatal(err) + } + updated, err := api.UpdateDocument(ctx, id, n8n.UpdatePolicyDocumentRequest{Rules: []n8n.NodeTypePolicyRule{}, Version: &got.Version}) + if err != nil { + t.Fatal(err) + } + if updated.Policy.Version <= got.Version || len(updated.Policy.Rules) != 0 { + t.Errorf("replacement failed: %+v", updated.Policy) + } + if err := api.DeleteDocument(ctx, id); err != nil { + t.Fatal(err) + } + deleted = true + }) + } +} + +// Attachment writes target only a newly-created test project. Cleanup detaches +// first, deletes the reusable document, then deletes the project. Existing +// instance scopes and integration-supplied projects are never mutated. +func TestPolicyAttachmentsOwnedProject(t *testing.T) { + instance := integration.RequireDestructive(t) + client := instance.Client(t) + ctx := context.Background() + for group, api := range integrationPolicyAPIs(client) { + t.Run(group, func(t *testing.T) { + if _, err := api.ListDocuments(ctx, n8n.ListOptions{Limit: 1}); err != nil { + skipUnlessPolicyAPI(t, err) + t.Fatal(err) + } + name := fmt.Sprintf("%spolicy-%d", integration.ResourcePrefix, time.Now().UnixNano()) + project, err := client.CreateProject(ctx, n8n.CreateProjectRequest{Name: name}) + skipUnlessPolicyAPI(t, err) + if err != nil { + t.Fatal(err) + } + projectID := project.ID + var scopeID, documentID string + t.Cleanup(func() { + cleanupCtx := context.Background() + if scopeID != "" { + current, err := api.GetAttachments(cleanupCtx, scopeID) + if err != nil { + t.Errorf("cleanup get attachments: %v", err) + } else if _, err := api.ReplaceAttachments(cleanupCtx, scopeID, n8n.ReplacePolicyAttachmentsRequest{Version: ¤t.Version}); err != nil { + t.Errorf("cleanup detach: %v", err) + } + } + if documentID != "" { + if err := api.DeleteDocument(cleanupCtx, documentID); err != nil { + t.Errorf("cleanup delete policy: %v", err) + } + } + if projectID == "" { + projects, err := n8n.Collect(cleanupCtx, client.ListProjects, n8n.ListOptions{Limit: 100}, 0) + if err != nil { + t.Errorf("cleanup find project %q: %v", name, err) + } else { + for _, p := range projects { + if p.Name == name { + projectID = p.ID + break + } + } + } + } + if projectID != "" { + if err := client.DeleteProject(cleanupCtx, projectID); err != nil { + t.Errorf("cleanup delete project: %v", err) + } + } + }) + if projectID == "" { + projects, err := n8n.Collect(ctx, client.ListProjects, n8n.ListOptions{Limit: 100}, 0) + if err != nil { + t.Fatal(err) + } + for _, p := range projects { + if p.Name == name { + projectID = p.ID + break + } + } + } + if projectID == "" { + t.Fatal("created test project could not be found") + } + initial, err := api.GetProject(ctx, projectID) + skipUnlessPolicyAPI(t, err) + if err != nil { + t.Fatal(err) + } + allow := n8n.NodeTypePolicyAllow + scope, err := api.ReplaceProject(ctx, projectID, n8n.ReplaceNodeTypePolicyRequest{Rules: []n8n.NodeTypePolicyRule{}, DefaultAction: &allow, Version: &initial.Version}) + skipUnlessPolicyAPI(t, err) + if err != nil { + t.Fatal(err) + } + if scope.ScopeID != nil { + scopeID = *scope.ScopeID + } + if scopeID == "" { + t.Fatal("scope write did not return scopeId") + } + doc, err := api.CreateDocument(ctx, n8n.CreatePolicyDocumentRequest{Rules: []n8n.NodeTypePolicyRule{{ID: name, Action: n8n.NodeTypePolicyAllow, Selector: n8n.NodeTypePolicySelector{Kind: n8n.NodeTypePolicySelectorPackage, Value: integration.ResourcePrefix + "uninstalled"}}}}) + if err != nil { + t.Fatal(err) + } + documentID = doc.Policy.ID + if documentID == "" { + t.Fatal("missing policy ID") + } + current, err := api.GetAttachments(ctx, scopeID) + if err != nil { + t.Fatal(err) + } + priority := 0 + floor := false + updated, err := api.ReplaceAttachments(ctx, scopeID, n8n.ReplacePolicyAttachmentsRequest{Attachments: []n8n.PolicyAttachmentInput{{PolicyID: documentID, Priority: &priority, IsFloor: &floor}}, Version: ¤t.Version}) + if err != nil { + t.Fatal(err) + } + if len(updated.Attachments) != 1 || updated.Attachments[0].PolicyID != documentID || updated.Version <= current.Version { + t.Fatalf("attachment write: %+v", updated) + } + // A document update must advance the attached scope's version too. + if _, err := api.UpdateDocument(ctx, documentID, n8n.UpdatePolicyDocumentRequest{Rules: []n8n.NodeTypePolicyRule{}, Version: &doc.Policy.Version}); err != nil { + t.Fatal(err) + } + after, err := api.GetAttachments(ctx, scopeID) + if err != nil { + t.Fatal(err) + } + if after.Version <= updated.Version { + t.Error("attached document update did not bump scope version") + } + }) + } +}