From da44ea4c40a5e44885740e193b2413f6cc55be49 Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 23:10:22 -0500 Subject: [PATCH] feat(node-policy): add notloaded warnings and shared document scope docs --- docs/n8n_node-policy.md | 21 +++-- docs/n8n_node-policy_instance.md | 3 +- docs/n8n_node-policy_instance_get.md | 8 +- docs/n8n_node-policy_instance_set.md | 19 ++-- docs/n8n_node-policy_project.md | 1 + docs/n8n_node-policy_project_get.md | 14 +-- docs/n8n_node-policy_project_set.md | 27 ++++-- internal/cli/node_policy.go | 122 +++++++++++++++++--------- internal/cli/node_policy_test.go | 94 ++++++++++++++++++-- internal/n8n/node_type_policy.go | 24 +++-- internal/n8n/node_type_policy_test.go | 44 +++++++++- 11 files changed, 292 insertions(+), 85 deletions(-) diff --git a/docs/n8n_node-policy.md b/docs/n8n_node-policy.md index 4607343..5a43313 100644 --- a/docs/n8n_node-policy.md +++ b/docs/n8n_node-policy.md @@ -5,13 +5,20 @@ Manage node type availability policies ### Synopsis Read and replace the policies that decide which node types may be used, at -instance scope and per project. A policy is a default action plus an ordered -rule list; the first matching rule wins and the default applies to the rest. - -Every action is a full replacement, so the workflow is get, edit, set: start -from 'get --output json', change the rules, and pass the whole document back. -The version field carries that round trip and a stale value is rejected with -409, which means someone else changed the policy first. +instance scope and per project. Preview API: n8n may change it without notice. + +A scope has a default action and one or more attached policy documents, each an +ordered rule list; the first matching rule wins and the default applies to the +rest. 'get' reports the composed view: the rules of every attached document in +evaluation order. 'set' replaces only the scope's own document. + +Start with 'instance get'. Writes are full replacements, so the workflow is get, +edit, set: start from 'get --output json', change the rules, and pass the whole +document back. The version field carries that round trip and a stale value is +rejected with 409, which means the policy or one of its attachments changed +first. Once a scope has more than its own document attached, a get-edit-set +round trip copies the rules of the shared documents into the scope's own +document; check the scope's attachments before editing one that has them. Requires nodeTypePolicy:manage, n8n 2.40.0 or later, and the licensed type-availability-policies module. Instances without it answer 404 or 503. diff --git a/docs/n8n_node-policy_instance.md b/docs/n8n_node-policy_instance.md index 6ee4ff8..b7a076e 100644 --- a/docs/n8n_node-policy_instance.md +++ b/docs/n8n_node-policy_instance.md @@ -9,7 +9,8 @@ only scope that accepts the delegate action, which hands a decision down to the project policy instead of settling it. An instance that was never configured reports no rules, an allow default, and -version 0; writing to it creates the policy document. +version 0; writing to it creates the policy document. Preview API: n8n may +change it without notice. ``` n8n node-policy instance [flags] diff --git a/docs/n8n_node-policy_instance_get.md b/docs/n8n_node-policy_instance_get.md index 5b16212..00ae12a 100644 --- a/docs/n8n_node-policy_instance_get.md +++ b/docs/n8n_node-policy_instance_get.md @@ -7,10 +7,12 @@ Get the instance node type policy Get the composed instance node type policy: its default action and the rules of every attached policy document, in evaluation order. Use --output json as the starting point for a get-edit-set workflow; the version it reports is what 'set' -must send back. +must send back. 'set' writes those rules into the instance's own document, so +with shared documents attached the round trip copies their rules too. -A scope that was never configured reports no rules, defaultAction allow, and -version 0. Requires nodeTypePolicy:manage. +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. ``` n8n node-policy instance get [flags] diff --git a/docs/n8n_node-policy_instance_set.md b/docs/n8n_node-policy_instance_set.md index ca90f9a..0ca7294 100644 --- a/docs/n8n_node-policy_instance_set.md +++ b/docs/n8n_node-policy_instance_set.md @@ -4,11 +4,16 @@ Fully replace the instance node type policy ### Synopsis -Replace the instance default action and every rule of its policy document from -strict JSON. This is a PUT, not a patch: rules, defaultAction, and version are -all required, and any rule left out is deleted. Start from +Replace the instance default action and every rule of its own policy document +from strict JSON. This is a PUT, not a patch: rules, defaultAction, and version +are all required, and any rule left out is deleted. Start from 'n8n node-policy instance get --output json'. +'get' reports the rules of every attached document, but 'set' writes only the +instance's own document. When shared documents are attached, remove their +rules from the input or they are copied into the own document; the attached +documents themselves are not changed. + Actions are allow, deny, or delegate. Selectors are {"kind":"name"} for one node type or {"kind":"package"} for every node type in a package. Rule ids must be unique and rules are evaluated in list order. @@ -17,7 +22,11 @@ version must equal the version last read; a stale value is rejected with 409 and nothing changes. Blocking a node type stops workflows that use it, so interactive runs ask for confirmation and non-interactive runs require --yes. scopeId and warnings from a previous response are accepted and ignored. -Requires nodeTypePolicy:manage. + +The response lists warnings that do not fail the write: kind shadowed means an +earlier rule already decides the rule's node types, and kind notLoaded means the +rule selects node types this instance has not loaded. Preview API: n8n may +change it without notice. Requires nodeTypePolicy:manage. ``` n8n node-policy instance set [flags] @@ -38,7 +47,7 @@ n8n node-policy instance set [flags] --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') -h, --help help for set --input string full node type policy JSON file path, or - for stdin (required; maximum 1 MiB) - --output string output format: text or json (JSON is the stored policy plus shadowed-rule warnings) (default "text") + --output string output format: text or json (JSON is the stored policy plus warnings, each with a kind) (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 the full replacement without prompting (required when stdin is not interactive) ``` diff --git a/docs/n8n_node-policy_project.md b/docs/n8n_node-policy_project.md index a86903f..650b6df 100644 --- a/docs/n8n_node-policy_project.md +++ b/docs/n8n_node-policy_project.md @@ -10,6 +10,7 @@ policy, so a node type can still be blocked by instance scope. Project scope accepts allow and deny only; delegate is instance-scope. A project that was never configured reports no rules, an allow default, and version 0. +Preview API: n8n may change it without notice. ``` n8n node-policy project [flags] diff --git a/docs/n8n_node-policy_project_get.md b/docs/n8n_node-policy_project_get.md index 773a61a..099223b 100644 --- a/docs/n8n_node-policy_project_get.md +++ b/docs/n8n_node-policy_project_get.md @@ -5,12 +5,14 @@ Get a project's node type policy ### Synopsis Get one project's own composed node type policy: its default action and the rules -of its policy document, in evaluation order. This is not the effective decision -for the project, because the instance policy is applied on top at evaluation. - -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'. +of every policy document attached to the project, in evaluation order. This is +not the effective decision for the project, because the instance policy is +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'. ``` n8n node-policy project get [flags] diff --git a/docs/n8n_node-policy_project_set.md b/docs/n8n_node-policy_project_set.md index d1b3129..8c32b44 100644 --- a/docs/n8n_node-policy_project_set.md +++ b/docs/n8n_node-policy_project_set.md @@ -4,21 +4,30 @@ Fully replace a project's node type policy ### Synopsis -Replace one project's default action and every rule of its policy document from -strict JSON. This is a PUT, not a patch: rules, defaultAction, and version are -all required, and any rule left out is deleted. Start from +Replace one project's default action and every rule of its own policy document +from strict JSON. This is a PUT, not a patch: rules, defaultAction, and version +are all required, and any rule left out is deleted. Start from 'n8n node-policy project get --output json'. +'get' reports the rules of every attached document, but 'set' writes only the +project's own document. When shared documents are attached, remove their rules +from the input or they are copied into the own document. + Project scope accepts allow and deny only; delegate belongs to the instance policy and is rejected before the request is sent. Selectors are {"kind":"name"} or {"kind":"package"}, rule ids must be unique, and rules are evaluated in list order. -version must equal the version last read; a stale value, or a policy document -shared with another scope, is rejected with 409 and nothing changes. Blocking a -node type stops workflows in the project that use it, so interactive runs ask -for confirmation and non-interactive runs require --yes. Requires -nodeTypePolicy:manage. +version must equal the version last read; a stale value, or a project document +that is shared with another scope, is rejected with 409 and nothing changes. +Blocking a node type stops workflows in the project that use it, so interactive +runs ask for confirmation and non-interactive runs require --yes. scopeId and +warnings from a previous response are accepted and ignored. + +The response lists warnings that do not fail the write: kind shadowed means an +earlier rule already decides the rule's node types, and kind notLoaded means the +rule selects node types this instance has not loaded. Preview API: n8n may +change it without notice. Requires nodeTypePolicy:manage. ``` n8n node-policy project set [flags] @@ -38,7 +47,7 @@ n8n node-policy project set [flags] --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') -h, --help help for set --input string full node type policy JSON file path, or - for stdin (required; maximum 1 MiB) - --output string output format: text or json (JSON is the stored policy plus shadowed-rule warnings) (default "text") + --output string output format: text or json (JSON is the stored policy plus warnings, each with a kind) (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 the full replacement without prompting (required when stdin is not interactive) ``` diff --git a/internal/cli/node_policy.go b/internal/cli/node_policy.go index c356c62..0395498 100644 --- a/internal/cli/node_policy.go +++ b/internal/cli/node_policy.go @@ -32,12 +32,18 @@ func newNodePolicyCommand(opts Options) *cobra.Command { Use: "node-policy", Short: "Manage node type availability policies", Long: "Read and replace the policies that decide which node types may be used, at\n" + - "instance scope and per project. A policy is a default action plus an ordered\n" + - "rule list; the first matching rule wins and the default applies to the rest.\n\n" + - "Every action is a full replacement, so the workflow is get, edit, set: start\n" + - "from 'get --output json', change the rules, and pass the whole document back.\n" + - "The version field carries that round trip and a stale value is rejected with\n" + - "409, which means someone else changed the policy first.\n\n" + + "instance scope and per project. Preview API: n8n may change it without notice.\n\n" + + "A scope has a default action and one or more attached policy documents, each an\n" + + "ordered rule list; the first matching rule wins and the default applies to the\n" + + "rest. 'get' reports the composed view: the rules of every attached document in\n" + + "evaluation order. 'set' replaces only the scope's own document.\n\n" + + "Start with 'instance get'. Writes are full replacements, so the workflow is get,\n" + + "edit, set: start from 'get --output json', change the rules, and pass the whole\n" + + "document back. The version field carries that round trip and a stale value is\n" + + "rejected with 409, which means the policy or one of its attachments changed\n" + + "first. Once a scope has more than its own document attached, a get-edit-set\n" + + "round trip copies the rules of the shared documents into the scope's own\n" + + "document; check the scope's attachments before editing one that has them.\n\n" + "Requires nodeTypePolicy:manage, n8n 2.40.0 or later, and the licensed\n" + "type-availability-policies module. Instances without it answer 404 or 503.", Example: " n8n node-policy instance get\n" + @@ -62,7 +68,8 @@ func newNodePolicyInstanceCommand(opts Options) *cobra.Command { "only scope that accepts the delegate action, which hands a decision down to the\n" + "project policy instead of settling it.\n\n" + "An instance that was never configured reports no rules, an allow default, and\n" + - "version 0; writing to it creates the policy document.", + "version 0; writing to it creates the policy document. Preview API: n8n may\n" + + "change it without notice.", Example: " n8n node-policy instance get\n" + " n8n node-policy instance get --output json > policy.json\n" + " n8n node-policy instance set --input policy.json", @@ -84,7 +91,8 @@ func newNodePolicyProjectCommand(opts Options) *cobra.Command { "the project's own document, not the result of combining it with the instance\n" + "policy, so a node type can still be blocked by instance scope.\n\n" + "Project scope accepts allow and deny only; delegate is instance-scope. A project\n" + - "that was never configured reports no rules, an allow default, and version 0.", + "that was never configured reports no rules, an allow default, and version 0.\n" + + "Preview API: n8n may change it without notice.", Example: " n8n node-policy project get L5fcpzBVjoU2PKFP\n" + " n8n node-policy project get L5fcpzBVjoU2PKFP --output json > project-policy.json\n" + " n8n node-policy project set L5fcpzBVjoU2PKFP --input project-policy.json", @@ -111,9 +119,11 @@ func newNodePolicyInstanceGetCommand(opts Options) *cobra.Command { Long: "Get the composed instance node type policy: its default action and the rules of\n" + "every attached policy document, in evaluation order. Use --output json as the\n" + "starting point for a get-edit-set workflow; the version it reports is what 'set'\n" + - "must send back.\n\n" + - "A scope that was never configured reports no rules, defaultAction allow, and\n" + - "version 0. Requires nodeTypePolicy:manage.", + "must send back. 'set' writes those rules into the instance's own document, so\n" + + "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.", Example: " n8n node-policy instance get\n" + " n8n node-policy instance get --output json\n" + " n8n node-policy instance get --output json > policy.json", @@ -133,11 +143,13 @@ func newNodePolicyProjectGetCommand(opts Options) *cobra.Command { Use: "get ", Short: "Get a project's node type policy", Long: "Get one project's own composed node type policy: its default action and the rules\n" + - "of its policy document, in evaluation order. This is not the effective decision\n" + - "for the project, because the instance policy is applied on top at evaluation.\n\n" + - "A project that was never configured reports no rules, defaultAction allow, and\n" + - "version 0. Use --output json as the input for 'set'. Requires\n" + - "nodeTypePolicy:manage. Find project IDs with 'n8n project list'.", + "of every policy document attached to the project, in evaluation order. This is\n" + + "not the effective decision for the project, because the instance policy is\n" + + "applied on top at evaluation.\n\n" + + "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'.", Example: " n8n node-policy project get L5fcpzBVjoU2PKFP\n" + " n8n node-policy project get L5fcpzBVjoU2PKFP --output json > project-policy.json", Args: cobra.ExactArgs(1), @@ -186,18 +198,25 @@ func newNodePolicyInstanceSetCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "set", Short: "Fully replace the instance node type policy", - Long: "Replace the instance default action and every rule of its policy document from\n" + - "strict JSON. This is a PUT, not a patch: rules, defaultAction, and version are\n" + - "all required, and any rule left out is deleted. Start from\n" + + Long: "Replace the instance default action and every rule of its own policy document\n" + + "from strict JSON. This is a PUT, not a patch: rules, defaultAction, and version\n" + + "are all required, and any rule left out is deleted. Start from\n" + "'n8n node-policy instance get --output json'.\n\n" + + "'get' reports the rules of every attached document, but 'set' writes only the\n" + + "instance's own document. When shared documents are attached, remove their\n" + + "rules from the input or they are copied into the own document; the attached\n" + + "documents themselves are not changed.\n\n" + "Actions are allow, deny, or delegate. Selectors are {\"kind\":\"name\"} for one node\n" + "type or {\"kind\":\"package\"} for every node type in a package. Rule ids must be\n" + "unique and rules are evaluated in list order.\n\n" + "version must equal the version last read; a stale value is rejected with 409 and\n" + "nothing changes. Blocking a node type stops workflows that use it, so\n" + "interactive runs ask for confirmation and non-interactive runs require --yes.\n" + - "scopeId and warnings from a previous response are accepted and ignored.\n" + - "Requires nodeTypePolicy:manage.", + "scopeId and warnings from a previous response are accepted and ignored.\n\n" + + "The response lists warnings that do not fail the write: kind shadowed means an\n" + + "earlier rule already decides the rule's node types, and kind notLoaded means the\n" + + "rule selects node types this instance has not loaded. Preview API: n8n may\n" + + "change it without notice. Requires nodeTypePolicy:manage.", Example: " n8n node-policy instance get --output json > policy.json\n" + " n8n node-policy instance set --input policy.json\n" + " n8n node-policy instance set --input policy.json --yes --output json\n" + @@ -216,19 +235,26 @@ func newNodePolicyProjectSetCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "set ", Short: "Fully replace a project's node type policy", - Long: "Replace one project's default action and every rule of its policy document from\n" + - "strict JSON. This is a PUT, not a patch: rules, defaultAction, and version are\n" + - "all required, and any rule left out is deleted. Start from\n" + + Long: "Replace one project's default action and every rule of its own policy document\n" + + "from strict JSON. This is a PUT, not a patch: rules, defaultAction, and version\n" + + "are all required, and any rule left out is deleted. Start from\n" + "'n8n node-policy project get --output json'.\n\n" + + "'get' reports the rules of every attached document, but 'set' writes only the\n" + + "project's own document. When shared documents are attached, remove their rules\n" + + "from the input or they are copied into the own document.\n\n" + "Project scope accepts allow and deny only; delegate belongs to the instance\n" + "policy and is rejected before the request is sent. Selectors are\n" + "{\"kind\":\"name\"} or {\"kind\":\"package\"}, rule ids must be unique, and rules are\n" + "evaluated in list order.\n\n" + - "version must equal the version last read; a stale value, or a policy document\n" + - "shared with another scope, is rejected with 409 and nothing changes. Blocking a\n" + - "node type stops workflows in the project that use it, so interactive runs ask\n" + - "for confirmation and non-interactive runs require --yes. Requires\n" + - "nodeTypePolicy:manage.", + "version must equal the version last read; a stale value, or a project document\n" + + "that is shared with another scope, is rejected with 409 and nothing changes.\n" + + "Blocking a node type stops workflows in the project that use it, so interactive\n" + + "runs ask for confirmation and non-interactive runs require --yes. scopeId and\n" + + "warnings from a previous response are accepted and ignored.\n\n" + + "The response lists warnings that do not fail the write: kind shadowed means an\n" + + "earlier rule already decides the rule's node types, and kind notLoaded means the\n" + + "rule selects node types this instance has not loaded. Preview API: n8n may\n" + + "change it without notice. Requires nodeTypePolicy:manage.", Example: " n8n node-policy project get L5fcpzBVjoU2PKFP --output json > project-policy.json\n" + " n8n node-policy project set L5fcpzBVjoU2PKFP --input project-policy.json\n" + " n8n node-policy project set L5fcpzBVjoU2PKFP --input - --yes < project-policy.json", @@ -245,7 +271,7 @@ func registerNodePolicySetFlags(cmd *cobra.Command, f *nodePolicySetFlags) { f.instance.register(cmd) cmd.Flags().StringVar(&f.input, "input", "", "full node type policy JSON file path, or - for stdin (required; maximum 1 MiB)") cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm the full replacement without prompting (required when stdin is not interactive)") - cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the stored policy plus shadowed-rule warnings)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the stored policy plus warnings, each with a kind)") } func runNodePolicySet(ctx context.Context, opts Options, f nodePolicySetFlags, projectID string, scope n8n.NodeTypePolicyScope) error { @@ -296,13 +322,14 @@ func runNodePolicySet(ctx context.Context, opts Options, f nodePolicySetFlags, p // nodePolicyDocument is the input shape of 'set'. It accepts the document 'get' // and a previous 'set' print, so scopeId and warnings round trip without being -// sent: both are server-owned. +// sent: both are server-owned. Warnings stay raw so a warning shape this CLI +// does not know yet cannot make a previous response unreadable. type nodePolicyDocument struct { - ScopeID *string `json:"scopeId"` - Rules []n8n.NodeTypePolicyRule `json:"rules"` - DefaultAction *n8n.NodeTypePolicyAction `json:"defaultAction"` - Version *int `json:"version"` - Warnings []n8n.NodeTypePolicyWarning `json:"warnings"` + ScopeID *string `json:"scopeId"` + Rules []n8n.NodeTypePolicyRule `json:"rules"` + DefaultAction *n8n.NodeTypePolicyAction `json:"defaultAction"` + Version *int `json:"version"` + Warnings json.RawMessage `json:"warnings"` } func readNodePolicyDocument(opts Options, path string) (n8n.ReplaceNodeTypePolicyRequest, error) { @@ -353,9 +380,9 @@ func writeNodePolicy(opts Options, resolution config.Resolution, heading string, tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) fmt.Fprintf(tw, "%s:\t%s\n", heading, resolution.URL) if policy.Configured() { - fmt.Fprintf(tw, "Scope document:\t%s\n", *policy.ScopeID) + fmt.Fprintf(tw, "Scope ID:\t%s\n", *policy.ScopeID) } else { - fmt.Fprintf(tw, "Scope document:\tnone (never configured; every node type is allowed)\n") + fmt.Fprintf(tw, "Scope ID:\tnone (never configured; every node type is allowed)\n") } fmt.Fprintf(tw, "Default action:\t%s\n", policy.DefaultAction) fmt.Fprintf(tw, "Version:\t%d\n", policy.Version) @@ -367,11 +394,24 @@ func writeNodePolicy(opts Options, resolution config.Resolution, heading string, } } for _, warning := range warnings { - fmt.Fprintf(tw, "\nWarning: rule %s never matches; rule %s already decides those node types.\n", warning.RuleID, warning.ShadowedByRuleID) + fmt.Fprintf(tw, "\nWarning: %s\n", nodePolicyWarningText(warning)) } return tw.Flush() } +// nodePolicyWarningText renders one write warning by kind. An unknown kind is +// still shown, so a newer server's warning is never silently dropped. +func nodePolicyWarningText(warning n8n.NodeTypePolicyWarning) string { + switch warning.Kind { + case n8n.NodeTypePolicyWarningShadowed: + return fmt.Sprintf("rule %s never matches; rule %s already decides those node types.", warning.RuleID, warning.ShadowedByRuleID) + case n8n.NodeTypePolicyWarningNotLoaded: + return fmt.Sprintf("rule %s selects node types this instance has not loaded; it has no effect until they are installed.", warning.RuleID) + default: + return fmt.Sprintf("rule %s: %s.", warning.RuleID, warning.Kind) + } +} + func nodePolicyRuleCount(rules int) string { if rules == 1 { return "1 rule" @@ -387,10 +427,10 @@ func nodePolicyAPIError(err error, resolution config.Resolution, action string, case n8n.IsForbidden(err): return forbiddenScopeError(err, resolution, "node type policy "+action, allOf("nodeTypePolicy:manage"), "", nodePolicyResource) case n8n.IsConflict(err) && scope == n8n.NodeTypePolicyScopeProject: - return fmt.Errorf("%s refused the node type policy replacement (409): the version was changed by someone else since it was read, or the policy document is shared with another scope, so nothing changed; run 'n8n node-policy project get' again and re-apply the edit", + return fmt.Errorf("%s refused the node type policy replacement (409): the version changed since it was read (an edit, an attachment change, or an update to an attached shared document), or the project document is shared with another scope, so nothing changed; run 'n8n node-policy project get' again and re-apply the edit, or edit the shared document instead", resolution.URL) case n8n.IsConflict(err): - return fmt.Errorf("%s refused the node type policy replacement (409): the version was changed by someone else since it was read, so nothing changed; run 'n8n node-policy instance get' again and re-apply the edit", + return fmt.Errorf("%s refused the node type policy replacement (409): the version changed since it was read (an edit, an attachment change, or an update to an attached shared document), so nothing changed; run 'n8n node-policy instance get' again and re-apply the edit", resolution.URL) case n8n.IsStatus(err, http.StatusBadRequest): return fmt.Errorf("%s rejected the node type policy replacement (400): send rules, defaultAction, and version together, use unique rule ids, and select node types with {\"kind\":\"name\"} or {\"kind\":\"package\"}", diff --git a/internal/cli/node_policy_test.go b/internal/cli/node_policy_test.go index c96dcd9..0aa702e 100644 --- a/internal/cli/node_policy_test.go +++ b/internal/cli/node_policy_test.go @@ -28,7 +28,10 @@ const cliNodePolicyWriteResult = `{ "rules":[{"id":"deny-http","action":"deny","selector":{"kind":"name","value":"n8n-nodes-base.httpRequest"}}], "defaultAction":"deny", "version":8, - "warnings":[{"ruleId":"deny-http-copy","shadowedByRuleId":"deny-http"}] + "warnings":[ + {"kind":"shadowed","ruleId":"deny-http-copy","shadowedByRuleId":"deny-http"}, + {"kind":"notLoaded","ruleId":"deny-weather"} + ] }` const cliNodePolicyInput = `{ @@ -63,7 +66,7 @@ func TestNodePolicyInstanceGetTextShowsRulesInEvaluationOrder(t *testing.T) { t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) } for _, want := range []string{ - "Instance node type policy:", f.server.URL, "Scope document:", "instance-1", + "Instance node type policy:", f.server.URL, "Scope ID:", "instance-1", "Default action:", "allow", "Version:", "7", "Rules:", "2", "ORDER", "deny-http", "name=n8n-nodes-base.httpRequest", "delegate", "package=n8n-nodes-weather", @@ -170,11 +173,92 @@ func TestNodePolicySetSendsReplacementWithoutServerOwnedFields(t *testing.T) { if rules, ok := sent["rules"].([]any); !ok || len(rules) != 1 { t.Errorf("rules = %#v, want the one edited rule", sent["rules"]) } - for _, want := range []string{"Replaced instance node type policy:", "Version:", "8", "never matches", "deny-http-copy", "deny-http"} { + for _, want := range []string{ + "Replaced instance node type policy:", "Version:", "8", + "Warning: rule deny-http-copy never matches; rule deny-http already decides those node types.", + "Warning: rule deny-weather selects node types this instance has not loaded; it has no effect until they are installed.", + } { if !strings.Contains(got.stdout, want) { t.Errorf("stdout missing %q:\n%s", want, got.stdout) } } + if strings.Contains(got.stdout, "rule deny-weather never matches") || strings.Contains(got.stdout, "rule already") { + t.Errorf("notLoaded warning rendered as shadowed:\n%s", got.stdout) + } +} + +func TestNodePolicySetJSONKeepsWarningKind(t *testing.T) { + f := nodePolicyFixture(t, cliNodePolicyWriteResult) + path := writeNodePolicyInput(t, cliNodePolicyInput) + got := f.run("node-policy", "instance", "set", "--input", path, "--yes", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + var result struct { + Warnings []map[string]any `json:"warnings"` + } + if err := json.Unmarshal([]byte(got.stdout), &result); err != nil { + t.Fatalf("stdout is not JSON: %v\n%s", err, got.stdout) + } + if len(result.Warnings) != 2 { + t.Fatalf("warnings = %#v, want both", result.Warnings) + } + if result.Warnings[0]["kind"] != "shadowed" || result.Warnings[0]["shadowedByRuleId"] != "deny-http" { + t.Errorf("warnings[0] = %#v, want kind shadowed with its shadowing rule", result.Warnings[0]) + } + if result.Warnings[1]["kind"] != "notLoaded" || result.Warnings[1]["ruleId"] != "deny-weather" { + t.Errorf("warnings[1] = %#v, want kind notLoaded", result.Warnings[1]) + } + if _, ok := result.Warnings[1]["shadowedByRuleId"]; ok { + t.Errorf("notLoaded warning carries shadowedByRuleId: %#v", result.Warnings[1]) + } +} + +func TestNodePolicySetRendersUnknownWarningKind(t *testing.T) { + f := nodePolicyFixture(t, `{"scopeId":"instance-1","rules":[],"defaultAction":"allow","version":2, + "warnings":[{"kind":"futureKind","ruleId":"deny-http"}]}`) + path := writeNodePolicyInput(t, cliNodePolicyInput) + got := f.run("node-policy", "instance", "set", "--input", path, "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if !strings.Contains(got.stdout, "Warning: rule deny-http: futureKind.") { + t.Errorf("stdout lacks the generic warning:\n%s", got.stdout) + } +} + +func TestNodePolicySetAcceptsPreviousResponseAsInput(t *testing.T) { + f := nodePolicyFixture(t, cliNodePolicyWriteResult) + first := f.run("node-policy", "instance", "set", "--input", writeNodePolicyInput(t, cliNodePolicyInput), "--yes", "--output", "json") + if first.code != ExitSuccess { + t.Fatalf("first set exit = %d, stderr: %s", first.code, first.stderr) + } + for name, input := range map[string]string{ + "previous set output": first.stdout, + "raw API response": cliNodePolicyWriteResult, + "unknown warning shape": `{"scopeId":"instance-1","rules":[],"defaultAction":"allow","version":8, + "warnings":[{"kind":"futureKind","ruleId":"a","detail":{"x":1}}]}`, + } { + t.Run(name, func(t *testing.T) { + got := f.run("node-policy", "instance", "set", "--input", writeNodePolicyInput(t, input), "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + var sent map[string]any + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("request body is not JSON: %v\n%s", err, f.lastBody()) + } + if _, ok := sent["warnings"]; ok { + t.Errorf("server-owned warnings were sent back: %#v", sent) + } + if _, ok := sent["scopeId"]; ok { + t.Errorf("server-owned scopeId was sent back: %#v", sent) + } + if sent["version"] != float64(8) { + t.Errorf("version = %v, want the version the response reported", sent["version"]) + } + }) + } } func TestNodePolicySetRequiresConfirmation(t *testing.T) { @@ -297,13 +381,13 @@ func TestNodePolicyAPIErrorsExplainAvailabilityAndConflict(t *testing.T) { name: "stale version", status: http.StatusConflict, args: []string{"node-policy", "instance", "set", "--yes"}, - want: []string{"(409)", "changed by someone else", "n8n node-policy instance get"}, + want: []string{"(409)", "version changed since it was read", "attachment change", "n8n node-policy instance get"}, }, { name: "project conflict names shared documents", status: http.StatusConflict, args: []string{"node-policy", "project", "set", "proj-1", "--yes"}, - want: []string{"(409)", "shared with another scope", "n8n node-policy project get"}, + want: []string{"(409)", "shared with another scope", "attached shared document", "n8n node-policy project get"}, }, { name: "bad request", diff --git a/internal/n8n/node_type_policy.go b/internal/n8n/node_type_policy.go index ebf3a13..d2a06aa 100644 --- a/internal/n8n/node_type_policy.go +++ b/internal/n8n/node_type_policy.go @@ -73,15 +73,29 @@ type NodeTypePolicy struct { // scope allows every node type. func (p NodeTypePolicy) Configured() bool { return p.ScopeID != nil } -// NodeTypePolicyWarning reports a rule that can never match because an earlier -// rule already decides the same node types. +// NodeTypePolicyWarningKind is why the server flagged a rule after a write. +type NodeTypePolicyWarningKind string + +const ( + // NodeTypePolicyWarningShadowed marks a rule that can never match because + // an earlier rule already decides the same node types. + NodeTypePolicyWarningShadowed NodeTypePolicyWarningKind = "shadowed" + // NodeTypePolicyWarningNotLoaded marks a rule whose selector names node + // types this instance has not loaded, so it decides nothing yet. + NodeTypePolicyWarningNotLoaded NodeTypePolicyWarningKind = "notLoaded" +) + +// NodeTypePolicyWarning flags one rule of a stored policy. Kind decides which +// other fields are set: ShadowedByRuleID only accompanies a shadowed warning. +// Kind is kept as sent, so a kind added by a newer server still round trips. type NodeTypePolicyWarning struct { - RuleID string `json:"ruleId"` - ShadowedByRuleID string `json:"shadowedByRuleId"` + Kind NodeTypePolicyWarningKind `json:"kind"` + RuleID string `json:"ruleId"` + ShadowedByRuleID string `json:"shadowedByRuleId,omitempty"` } // NodeTypePolicyWriteResult is the policy as stored after a replacement, plus -// the shadowing warnings the server found. Warnings do not fail the write. +// the warnings the server found. Warnings do not fail the write. type NodeTypePolicyWriteResult struct { NodeTypePolicy Warnings []NodeTypePolicyWarning `json:"warnings"` diff --git a/internal/n8n/node_type_policy_test.go b/internal/n8n/node_type_policy_test.go index 19a69d2..954eb64 100644 --- a/internal/n8n/node_type_policy_test.go +++ b/internal/n8n/node_type_policy_test.go @@ -30,7 +30,10 @@ const nodeTypePolicyWriteResponse = `{ "rules":[{"id":"deny-http","action":"deny","selector":{"kind":"name","value":"n8n-nodes-base.httpRequest"}}], "defaultAction":"deny", "version":8, - "warnings":[{"ruleId":"deny-http-again","shadowedByRuleId":"deny-http"}] + "warnings":[ + {"kind":"shadowed","ruleId":"deny-http-again","shadowedByRuleId":"deny-http"}, + {"kind":"notLoaded","ruleId":"deny-weather"} + ] }` func action(a NodeTypePolicyAction) *NodeTypePolicyAction { return &a } @@ -141,8 +144,43 @@ func TestReplaceInstanceNodeTypePolicy(t *testing.T) { if result.Version != 8 || result.DefaultAction != NodeTypePolicyDeny { t.Errorf("result = %+v, want the stored version and default action", result) } - if len(result.Warnings) != 1 || result.Warnings[0].RuleID != "deny-http-again" || result.Warnings[0].ShadowedByRuleID != "deny-http" { - t.Errorf("warnings = %+v", result.Warnings) + want := []NodeTypePolicyWarning{ + {Kind: NodeTypePolicyWarningShadowed, RuleID: "deny-http-again", ShadowedByRuleID: "deny-http"}, + {Kind: NodeTypePolicyWarningNotLoaded, RuleID: "deny-weather"}, + } + if len(result.Warnings) != len(want) { + t.Fatalf("warnings = %+v, want %+v", result.Warnings, want) + } + for i := range want { + if result.Warnings[i] != want[i] { + t.Errorf("warnings[%d] = %+v, want %+v", i, result.Warnings[i], want[i]) + } + } +} + +func TestNodeTypePolicyWarningKeepsKindOnEncode(t *testing.T) { + tests := []struct { + name string + warning string + }{ + {name: "shadowed", warning: `{"kind":"shadowed","ruleId":"b","shadowedByRuleId":"a"}`}, + {name: "not loaded omits shadowing rule", warning: `{"kind":"notLoaded","ruleId":"b"}`}, + {name: "unknown kind survives", warning: `{"kind":"futureKind","ruleId":"b"}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var warning NodeTypePolicyWarning + if err := json.Unmarshal([]byte(tt.warning), &warning); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + encoded, err := json.Marshal(warning) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if string(encoded) != tt.warning { + t.Errorf("encoded = %s, want %s", encoded, tt.warning) + } + }) } }