From afb3c783ee40d96fbefe0c5b09ce0b33240b2315 Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 20:02:18 -0500 Subject: [PATCH] feat(otel,saml): add start-span and email-verification settings to set --- docs/n8n_otel_set.md | 31 ++++++--- docs/n8n_saml_set.md | 35 ++++++---- internal/cli/otel.go | 62 ++++++++++++++---- internal/cli/otel_test.go | 125 +++++++++++++++++++++++++++++++++++- internal/cli/saml.go | 65 +++++++++++++++---- internal/cli/saml_test.go | 122 +++++++++++++++++++++++++++++++++-- internal/n8n/otel.go | 22 +++++++ internal/n8n/otel_test.go | 51 +++++++++++++++ internal/n8n/saml.go | 131 +++++++++++++++++++++++--------------- internal/n8n/saml_test.go | 61 ++++++++++++++++-- 10 files changed, 594 insertions(+), 111 deletions(-) diff --git a/docs/n8n_otel_set.md b/docs/n8n_otel_set.md index d2e6a41..2919af7 100644 --- a/docs/n8n_otel_set.md +++ b/docs/n8n_otel_set.md @@ -5,8 +5,14 @@ Fully replace OpenTelemetry settings ### Synopsis Fully replace the instance OpenTelemetry configuration from strict JSON. This -is a PUT, not a patch: every field is required except exporterProtocol. Omitting -that field selects http/protobuf. Start from 'n8n otel get --output json'. +is a PUT, not a patch: every field is required except exporterProtocol, +emitWorkflowStartSpan, and emitNodeStartSpan. Omitting exporterProtocol selects +http/protobuf. The two start-span fields are omitted = false on the server: a +document without them turns both spans off, so pass the current values or use +--input from 'n8n otel get --output json', which round-trips them losslessly. +--emit-workflow-start-span and --emit-node-start-span set or override them in +the --input document. Instances older than these settings do not report them; +leave them out there. A successful update is applied to the running instance immediately and can change or stop exported traces, so interactive runs ask for confirmation and @@ -14,8 +20,10 @@ non-interactive runs require --yes. --input - also requires --yes because stdin cannot hold both JSON and a confirmation answer. Environment-managed fields are read-only. Re-submit their effective GET values -unchanged, or change the environment configuration. Exporter headers may be -credentials; response details are redacted on errors. Requires otel:manage. +unchanged, or change the environment configuration. Omitting a start-span field +that the environment pins to true is a change and answers 409. Exporter headers +may be credentials; response details are redacted on errors. Requires +otel:manage. ``` n8n otel set [flags] @@ -27,18 +35,21 @@ n8n otel set [flags] umask 077 && n8n otel get --output json > otel.json n8n otel set --input otel.json n8n otel set --input otel.json --yes --output json + n8n otel set --input otel.json --emit-workflow-start-span --emit-node-start-span=false n8n otel set --input - --yes < otel.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 full OpenTelemetry settings JSON file path, or - for stdin (required; maximum 1 MiB) - --output string output format: text or json (JSON includes possibly sensitive exporter headers) (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 full replacement and immediate runtime application without prompting (required when stdin is not interactive) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --emit-node-start-span emit a 0 ms node.execute.started span when each node span starts, doubling node spans; true or false, overrides emitNodeStartSpan in --input (default: the --input value, and false on the server when both omit it) + --emit-workflow-start-span emit a 0 ms workflow.execute.started span when each execution starts; true or false, overrides emitWorkflowStartSpan in --input (default: the --input value, and false on the server when both omit it) + -h, --help help for set + --input string full OpenTelemetry settings JSON file path, or - for stdin (required; maximum 1 MiB) + --output string output format: text or json (JSON includes possibly sensitive exporter headers) (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 full replacement and immediate runtime application without prompting (required when stdin is not interactive) ``` ### SEE ALSO diff --git a/docs/n8n_saml_set.md b/docs/n8n_saml_set.md index 9283c02..408ddd1 100644 --- a/docs/n8n_saml_set.md +++ b/docs/n8n_saml_set.md @@ -5,12 +5,20 @@ Fully replace SAML SSO configuration ### Synopsis Fully replace the instance SAML SSO configuration from strict JSON. This is -a PUT, not a patch: all 15 writable top-level fields and every nested mapping -and signature field are required, including false, empty-string, and empty-array -values. Start from 'n8n saml get --output json'. Read-only entityID and returnUrl -are accepted for that round trip but ignored on set. Leave returned redaction -placeholders unchanged to preserve metadata, private key, and certificate; use -empty strings to clear supported values or plaintext to replace them. +a PUT, not a patch: every writable top-level field (16 on current n8n) and every +nested mapping and signature field is required, including false, empty-string, +and empty-array values. Start from 'n8n saml get --output json': that document +round-trips losslessly, including emailVerifiedRequired and mapping.emailVerified. +Read-only entityID and returnUrl are accepted for that round trip but ignored on +set. Leave returned redaction placeholders unchanged to preserve metadata, +private key, and certificate; use empty strings to clear supported values or +plaintext to replace them. + +Current n8n requires emailVerifiedRequired and mapping.emailVerified and answers +400 without them; older instances do not know them, so a document without them +is sent as is with a warning. --email-verified-required and +--email-verified-attribute set or override those two fields in the --input +document, e.g. when it came from an older instance. Every replacement asks for confirmation because changing SAML settings can alter the login flow immediately. Non-interactive use and --input - require --yes. @@ -28,18 +36,21 @@ n8n saml set [flags] umask 077 && n8n saml get --output json > saml.json n8n saml set --input saml.json n8n saml set --input saml.json --yes --output json + n8n saml set --input saml.json --email-verified-required --email-verified-attribute email_verified n8n saml set --input - --yes < saml.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 full SAML configuration JSON file path, or - for stdin (required; maximum 1 MiB; may contain private material) - --output string output format: text or json (secret-bearing values are returned only as n8n placeholders) (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 full replacement and possible login-flow changes without prompting (required for non-interactive use) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --email-verified-attribute string SAML attribute whose true/false value states the email is verified, empty string when unused; overrides mapping.emailVerified in --input (default: the --input value) + --email-verified-required require the identity provider to assert a verified email before a login links to an existing user by email; true or false, overrides emailVerifiedRequired in --input (default: the --input value) + -h, --help help for set + --input string full SAML configuration JSON file path, or - for stdin (required; maximum 1 MiB; may contain private material) + --output string output format: text or json (secret-bearing values are returned only as n8n placeholders) (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 full replacement and possible login-flow changes without prompting (required for non-interactive use) ``` ### SEE ALSO diff --git a/internal/cli/otel.go b/internal/cli/otel.go index 417b687..f867e37 100644 --- a/internal/cli/otel.go +++ b/internal/cli/otel.go @@ -93,10 +93,12 @@ func runOtelGet(ctx context.Context, opts Options, f otelGetFlags) error { } type otelSetFlags struct { - instance instanceFlags - input string - yes bool - output string + instance instanceFlags + input string + emitWorkflowStartSpan bool + emitNodeStartSpan bool + yes bool + output string } func newOtelSetCommand(opts Options) *cobra.Command { @@ -105,32 +107,53 @@ func newOtelSetCommand(opts Options) *cobra.Command { Use: "set", Short: "Fully replace OpenTelemetry settings", Long: "Fully replace the instance OpenTelemetry configuration from strict JSON. This\n" + - "is a PUT, not a patch: every field is required except exporterProtocol. Omitting\n" + - "that field selects http/protobuf. Start from 'n8n otel get --output json'.\n\n" + + "is a PUT, not a patch: every field is required except exporterProtocol,\n" + + "emitWorkflowStartSpan, and emitNodeStartSpan. Omitting exporterProtocol selects\n" + + "http/protobuf. The two start-span fields are omitted = false on the server: a\n" + + "document without them turns both spans off, so pass the current values or use\n" + + "--input from 'n8n otel get --output json', which round-trips them losslessly.\n" + + "--emit-workflow-start-span and --emit-node-start-span set or override them in\n" + + "the --input document. Instances older than these settings do not report them;\n" + + "leave them out there.\n\n" + "A successful update is applied to the running instance immediately and can\n" + "change or stop exported traces, so interactive runs ask for confirmation and\n" + "non-interactive runs require --yes. --input - also requires --yes because stdin\n" + "cannot hold both JSON and a confirmation answer.\n\n" + "Environment-managed fields are read-only. Re-submit their effective GET values\n" + - "unchanged, or change the environment configuration. Exporter headers may be\n" + - "credentials; response details are redacted on errors. Requires otel:manage.", + "unchanged, or change the environment configuration. Omitting a start-span field\n" + + "that the environment pins to true is a change and answers 409. Exporter headers\n" + + "may be credentials; response details are redacted on errors. Requires\n" + + "otel:manage.", Example: " umask 077 && n8n otel get --output json > otel.json\n" + " n8n otel set --input otel.json\n" + " n8n otel set --input otel.json --yes --output json\n" + + " n8n otel set --input otel.json --emit-workflow-start-span --emit-node-start-span=false\n" + " n8n otel set --input - --yes < otel.json", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - return runOtelSet(cmd.Context(), opts, f) + return runOtelSet(cmd.Context(), opts, f, otelSetOverrides{ + emitWorkflowStartSpan: cmd.Flags().Changed("emit-workflow-start-span"), + emitNodeStartSpan: cmd.Flags().Changed("emit-node-start-span"), + }) }, } f.instance.register(cmd) cmd.Flags().StringVar(&f.input, "input", "", "full OpenTelemetry settings JSON file path, or - for stdin (required; maximum 1 MiB)") + cmd.Flags().BoolVar(&f.emitWorkflowStartSpan, "emit-workflow-start-span", false, "emit a 0 ms workflow.execute.started span when each execution starts; true or false, overrides emitWorkflowStartSpan in --input (default: the --input value, and false on the server when both omit it)") + cmd.Flags().BoolVar(&f.emitNodeStartSpan, "emit-node-start-span", false, "emit a 0 ms node.execute.started span when each node span starts, doubling node spans; true or false, overrides emitNodeStartSpan in --input (default: the --input value, and false on the server when both omit it)") cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm full replacement and immediate runtime application without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON includes possibly sensitive exporter headers)") return cmd } -func runOtelSet(ctx context.Context, opts Options, f otelSetFlags) error { +// otelSetOverrides records which field flags were passed, so an explicit false +// still overrides the --input document. +type otelSetOverrides struct { + emitWorkflowStartSpan bool + emitNodeStartSpan bool +} + +func runOtelSet(ctx context.Context, opts Options, f otelSetFlags, overrides otelSetOverrides) error { if err := validateOutput(f.output); err != nil { return err } @@ -141,9 +164,18 @@ func runOtelSet(ctx context.Context, opts Options, f otelSetFlags) error { if err := readOtelDocument(opts, f.input, &request, "settings"); err != nil { return err } + if overrides.emitWorkflowStartSpan { + request.EmitWorkflowStartSpan = &f.emitWorkflowStartSpan + } + if overrides.emitNodeStartSpan { + request.EmitNodeStartSpan = &f.emitNodeStartSpan + } if err := request.Validate(); err != nil { return err } + if missing := request.MissingStartSpans(); len(missing) > 0 { + fmt.Fprintf(opts.Streams.Err, "Warning: --input omits %s. Instances that support them set them to false (409 if pinned to true by environment); older instances do not know them. Add them from 'n8n otel get --output json' or pass --emit-workflow-start-span and --emit-node-start-span.\n", strings.Join(missing, " and ")) + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err @@ -276,6 +308,12 @@ func writeOtelSettings(opts Options, resolution config.Resolution, heading strin fmt.Fprintf(tw, "Trace sample rate:\t%g\n", settings.TracesSampleRate) fmt.Fprintf(tw, "Startup connectivity timeout:\t%d ms\n", settings.StartupConnectivityTimeoutMs) fmt.Fprintf(tw, "Include node spans:\t%s\n", yesNo(settings.IncludeNodeSpans)) + if settings.EmitWorkflowStartSpan != nil { + fmt.Fprintf(tw, "Emit workflow start span:\t%s\n", yesNo(*settings.EmitWorkflowStartSpan)) + } + if settings.EmitNodeStartSpan != nil { + fmt.Fprintf(tw, "Emit node start span:\t%s\n", yesNo(*settings.EmitNodeStartSpan)) + } fmt.Fprintf(tw, "Inject outbound trace context:\t%s\n", yesNo(settings.InjectOutbound)) fmt.Fprintf(tw, "Production executions only:\t%s\n", yesNo(settings.ProductionExecutionsOnly)) if applied { @@ -294,13 +332,13 @@ func otelHeadersStatus(headers string) string { func otelAPIError(err error, resolution config.Resolution, action string) error { switch { case n8n.IsStatus(err, http.StatusBadRequest) && action == "update": - return fmt.Errorf("%s rejected the full OpenTelemetry replacement (400): include every field except optional exporterProtocol, which defaults to http/protobuf; collector response details were redacted", resolution.URL) + return fmt.Errorf("%s rejected the full OpenTelemetry replacement (400): include every field except optional exporterProtocol, which defaults to http/protobuf, and the start-span fields, which default to false and which older instances may not accept; collector response details were redacted", resolution.URL) case n8n.IsStatus(err, http.StatusBadRequest) && action == "test": return fmt.Errorf("%s rejected the OpenTelemetry test connection details (400): check the endpoint, protocol, service name, headers, and timeout; collector response details were redacted", resolution.URL) case n8n.IsForbidden(err): return forbiddenScopeError(err, resolution, "OpenTelemetry settings "+action, allOf("otel:manage"), "", otelResource) case n8n.IsConflict(err) && action == "update": - return fmt.Errorf("%s refused the OpenTelemetry replacement (409): one or more changed fields are managed by environment variables, so no changes were made; run 'n8n otel get', re-submit environment-managed values unchanged, or change the environment configuration and restart n8n", resolution.URL) + return fmt.Errorf("%s refused the OpenTelemetry replacement (409): one or more changed fields are managed by environment variables, so no changes were made; omitting emitWorkflowStartSpan or emitNodeStartSpan counts as a change when the environment pins it to true; run 'n8n otel get', re-submit environment-managed values unchanged (or pass --emit-workflow-start-span / --emit-node-start-span), or change the environment configuration and restart n8n", resolution.URL) default: return apiError(err, resolution, otelResource) } diff --git a/internal/cli/otel_test.go b/internal/cli/otel_test.go index c6edac2..47a800b 100644 --- a/internal/cli/otel_test.go +++ b/internal/cli/otel_test.go @@ -8,6 +8,8 @@ import ( "strings" "testing" + "github.com/google/go-cmp/cmp" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" ) @@ -23,9 +25,12 @@ const ( "tracesSampleRate":0.25, "startupConnectivityTimeoutMs":2500, "includeNodeSpans":false, + "emitWorkflowStartSpan":true, + "emitNodeStartSpan":false, "injectOutbound":true, "productionExecutionsOnly":true }` + // cliOtelDefaultInput has the shape of an older instance: no start spans. cliOtelDefaultInput = `{ "enabled":false, "exporterEndpoint":"http://collector.example.com:4318", @@ -75,7 +80,8 @@ func TestOtelGetTextRedactsHeadersAndShowsEverySetting(t *testing.T) { "Exporter endpoint:", "https://collector.example.com:4317", "Exporter tracing path:", "/v1/traces", "Exporter service name:", "n8n-production", "Exporter headers:", "configured (value hidden)", "Trace sample rate:", "0.25", "Startup connectivity timeout:", "2500 ms", - "Include node spans:", "no", "Inject outbound trace context:", "yes", "Production executions only:", "yes", + "Include node spans:", "no", "Emit workflow start span:", "Emit node start span:", + "Inject outbound trace context:", "yes", "Production executions only:", "yes", } { if !strings.Contains(got.stdout, want) { t.Errorf("stdout missing %q:\n%s", want, got.stdout) @@ -109,6 +115,8 @@ func TestOtelGetJSONIsStableAndIncludesEditDocument(t *testing.T) { "tracesSampleRate": 0.25, "startupConnectivityTimeoutMs": 2500, "includeNodeSpans": false, + "emitWorkflowStartSpan": true, + "emitNodeStartSpan": false, "injectOutbound": true, "productionExecutionsOnly": true } @@ -118,6 +126,117 @@ func TestOtelGetJSONIsStableAndIncludesEditDocument(t *testing.T) { } } +func TestOtelGetTextAndJSONOmitStartSpansFromOlderInstance(t *testing.T) { + f := otelFixture(t) + f.body = strings.Replace(cliOtelSettings, `"emitWorkflowStartSpan":true,`, "", 1) + f.body = strings.Replace(f.body, `"emitNodeStartSpan":false,`, "", 1) + for _, output := range []string{outputText, outputJSON} { + got := f.run("otel", "get", "--output", output) + if got.code != ExitSuccess { + t.Fatalf("%s exit = %d, stderr: %s", output, got.code, got.stderr) + } + if strings.Contains(got.stdout, "start span") || strings.Contains(got.stdout, "StartSpan") { + t.Errorf("%s output invented start spans:\n%s", output, got.stdout) + } + } +} + +func TestOtelGetJSONRoundTripsThroughSetLosslessly(t *testing.T) { + f := otelFixture(t) + got := f.run("otel", "get", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("get exit = %d, stderr: %s", got.code, got.stderr) + } + f.stdin = got.stdout + set := f.run("otel", "set", "--input", "-", "--yes") + if set.code != ExitSuccess { + t.Fatalf("set exit = %d, stderr: %s", set.code, set.stderr) + } + if strings.Contains(set.stderr, "Warning") { + t.Errorf("complete document warned: %s", set.stderr) + } + var want, sent map[string]any + if err := json.Unmarshal([]byte(cliOtelSettings), &want); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("request body is not JSON: %v", err) + } + if diff := cmp.Diff(want, sent); diff != "" { + t.Errorf("round trip changed the document (-get +set):\n%s", diff) + } +} + +func TestOtelSetWithoutStartSpansWarnsAndOmitsThem(t *testing.T) { + f := otelFixture(t) + f.stdin = cliOtelDefaultInput + got := f.run("otel", "set", "--input", "-", "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"Warning", "emitWorkflowStartSpan and emitNodeStartSpan", "set them to false", "409", "--emit-workflow-start-span"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("stderr missing %q: %s", want, got.stderr) + } + } + if strings.Contains(f.lastBody(), "StartSpan") { + t.Errorf("absent start spans were invented: %s", f.lastBody()) + } +} + +func TestOtelSetStartSpanFlagsOverrideInput(t *testing.T) { + tests := []struct { + name string + input string + args []string + wantWorkflow bool + wantNode bool + }{ + {name: "fill older document", input: cliOtelDefaultInput, args: []string{"--emit-workflow-start-span", "--emit-node-start-span"}, wantWorkflow: true, wantNode: true}, + {name: "explicit false overrides true", input: cliOtelSettings, args: []string{"--emit-workflow-start-span=false"}, wantWorkflow: false, wantNode: false}, + {name: "unset flags keep input", input: cliOtelSettings, wantWorkflow: true, wantNode: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := otelFixture(t) + f.stdin = tt.input + got := f.run(append([]string{"otel", "set", "--input", "-", "--yes"}, tt.args...)...) + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if strings.Contains(got.stderr, "Warning") { + t.Errorf("complete request warned: %s", got.stderr) + } + var sent struct { + EmitWorkflowStartSpan *bool `json:"emitWorkflowStartSpan"` + EmitNodeStartSpan *bool `json:"emitNodeStartSpan"` + } + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("request body is not JSON: %v", err) + } + if sent.EmitWorkflowStartSpan == nil || *sent.EmitWorkflowStartSpan != tt.wantWorkflow { + t.Errorf("emitWorkflowStartSpan = %v, want %t", sent.EmitWorkflowStartSpan, tt.wantWorkflow) + } + if sent.EmitNodeStartSpan == nil || *sent.EmitNodeStartSpan != tt.wantNode { + t.Errorf("emitNodeStartSpan = %v, want %t", sent.EmitNodeStartSpan, tt.wantNode) + } + }) + } +} + +func TestOtelSetHelpDocumentsStartSpanDefaults(t *testing.T) { + f := otelFixture(t) + got := f.run("otel", "set", "--help") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"--emit-workflow-start-span", "--emit-node-start-span", "omitted = false on the server", "otel get --output json", "409"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("help missing %q:\n%s", want, got.stdout) + } + } +} + func TestOtelSetRequiresReplacementConfirmationAndWarnsAboutRuntime(t *testing.T) { f := otelFixture(t) path := writeOtelInput(t, cliOtelDefaultInput) @@ -309,9 +428,9 @@ func TestOtelAPIErrorsExplainScopeReplacementAndEnvironmentOwnership(t *testing. {name: "get scope failure", status: http.StatusForbidden, args: []string{"otel", "get"}, want: []string{"otel:manage", "discover --resource settingsotel"}}, {name: "set scope failure", status: http.StatusForbidden, args: []string{"otel", "set", "--input", "-", "--yes"}, input: cliOtelDefaultInput, want: []string{"otel:manage", "discover --resource settingsotel"}}, {name: "test scope failure", status: http.StatusForbidden, args: []string{"otel", "test-trace", "--input", "-"}, input: cliOtelTraceInput, want: []string{"otel:manage", "discover --resource settingsotel"}}, - {name: "invalid replacement", status: http.StatusBadRequest, args: []string{"otel", "set", "--input", "-", "--yes"}, input: cliOtelDefaultInput, want: []string{"full OpenTelemetry replacement", "every field", "http/protobuf", "redacted"}}, + {name: "invalid replacement", status: http.StatusBadRequest, args: []string{"otel", "set", "--input", "-", "--yes"}, input: cliOtelDefaultInput, want: []string{"full OpenTelemetry replacement", "every field", "http/protobuf", "start-span", "redacted"}}, {name: "invalid test", status: http.StatusBadRequest, args: []string{"otel", "test-trace", "--input", "-"}, input: cliOtelTraceInput, want: []string{"test connection details", "endpoint", "redacted"}}, - {name: "environment conflict", status: http.StatusConflict, args: []string{"otel", "set", "--input", "-", "--yes"}, input: cliOtelDefaultInput, want: []string{"409", "managed by environment variables", "no changes were made", "otel get", "restart n8n"}}, + {name: "environment conflict", status: http.StatusConflict, args: []string{"otel", "set", "--input", "-", "--yes"}, input: cliOtelDefaultInput, want: []string{"409", "managed by environment variables", "no changes were made", "emitWorkflowStartSpan", "pins it to true", "--emit-node-start-span", "otel get", "restart n8n"}}, {name: "unauthorized", status: http.StatusUnauthorized, args: []string{"otel", "get"}, want: []string{"rejected the credential", "auth login"}}, } for _, tt := range tests { diff --git a/internal/cli/saml.go b/internal/cli/saml.go index 3af079a..929aec9 100644 --- a/internal/cli/saml.go +++ b/internal/cli/saml.go @@ -88,10 +88,12 @@ func runSAMLGet(ctx context.Context, opts Options, f samlGetFlags) error { } type samlSetFlags struct { - instance instanceFlags - input string - yes bool - output string + instance instanceFlags + input string + emailVerifiedRequired bool + emailVerifiedAttribute string + yes bool + output string } func newSAMLSetCommand(opts Options) *cobra.Command { @@ -100,12 +102,19 @@ func newSAMLSetCommand(opts Options) *cobra.Command { Use: "set", Short: "Fully replace SAML SSO configuration", Long: "Fully replace the instance SAML SSO configuration from strict JSON. This is\n" + - "a PUT, not a patch: all 15 writable top-level fields and every nested mapping\n" + - "and signature field are required, including false, empty-string, and empty-array\n" + - "values. Start from 'n8n saml get --output json'. Read-only entityID and returnUrl\n" + - "are accepted for that round trip but ignored on set. Leave returned redaction\n" + - "placeholders unchanged to preserve metadata, private key, and certificate; use\n" + - "empty strings to clear supported values or plaintext to replace them.\n\n" + + "a PUT, not a patch: every writable top-level field (16 on current n8n) and every\n" + + "nested mapping and signature field is required, including false, empty-string,\n" + + "and empty-array values. Start from 'n8n saml get --output json': that document\n" + + "round-trips losslessly, including emailVerifiedRequired and mapping.emailVerified.\n" + + "Read-only entityID and returnUrl are accepted for that round trip but ignored on\n" + + "set. Leave returned redaction placeholders unchanged to preserve metadata,\n" + + "private key, and certificate; use empty strings to clear supported values or\n" + + "plaintext to replace them.\n\n" + + "Current n8n requires emailVerifiedRequired and mapping.emailVerified and answers\n" + + "400 without them; older instances do not know them, so a document without them\n" + + "is sent as is with a warning. --email-verified-required and\n" + + "--email-verified-attribute set or override those two fields in the --input\n" + + "document, e.g. when it came from an older instance.\n\n" + "Every replacement asks for confirmation because changing SAML settings can alter\n" + "the login flow immediately. Non-interactive use and --input - require --yes.\n" + "Protect files containing replacement metadata, keys, or certificates. Server\n" + @@ -114,18 +123,33 @@ func newSAMLSetCommand(opts Options) *cobra.Command { Example: " umask 077 && n8n saml get --output json > saml.json\n" + " n8n saml set --input saml.json\n" + " n8n saml set --input saml.json --yes --output json\n" + + " n8n saml set --input saml.json --email-verified-required --email-verified-attribute email_verified\n" + " n8n saml set --input - --yes < saml.json", Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, _ []string) error { return runSAMLSet(cmd.Context(), opts, f) }, + RunE: func(cmd *cobra.Command, _ []string) error { + return runSAMLSet(cmd.Context(), opts, f, samlSetOverrides{ + emailVerifiedRequired: cmd.Flags().Changed("email-verified-required"), + emailVerifiedAttribute: cmd.Flags().Changed("email-verified-attribute"), + }) + }, } f.instance.register(cmd) cmd.Flags().StringVar(&f.input, "input", "", "full SAML configuration JSON file path, or - for stdin (required; maximum 1 MiB; may contain private material)") + cmd.Flags().BoolVar(&f.emailVerifiedRequired, "email-verified-required", false, "require the identity provider to assert a verified email before a login links to an existing user by email; true or false, overrides emailVerifiedRequired in --input (default: the --input value)") + cmd.Flags().StringVar(&f.emailVerifiedAttribute, "email-verified-attribute", "", "SAML attribute whose true/false value states the email is verified, empty string when unused; overrides mapping.emailVerified in --input (default: the --input value)") cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm full replacement and possible login-flow changes without prompting (required for non-interactive use)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (secret-bearing values are returned only as n8n placeholders)") return cmd } -func runSAMLSet(ctx context.Context, opts Options, f samlSetFlags) error { +// samlSetOverrides records which field flags were passed, so an explicit false +// or empty value still overrides the --input document. +type samlSetOverrides struct { + emailVerifiedRequired bool + emailVerifiedAttribute bool +} + +func runSAMLSet(ctx context.Context, opts Options, f samlSetFlags, overrides samlSetOverrides) error { if err := validateOutput(f.output); err != nil { return err } @@ -139,6 +163,15 @@ func runSAMLSet(ctx context.Context, opts Options, f samlSetFlags) error { if err := request.Validate(); err != nil { return err } + if overrides.emailVerifiedRequired { + request.EmailVerifiedRequired = &f.emailVerifiedRequired + } + if overrides.emailVerifiedAttribute { + request.Mapping.EmailVerified = &f.emailVerifiedAttribute + } + if missing := request.MissingEmailVerification(); len(missing) > 0 { + fmt.Fprintf(opts.Streams.Err, "Warning: --input omits %s. Current n8n requires them and answers 400; older instances do not know them. Add them from 'n8n saml get --output json' or pass --email-verified-required and --email-verified-attribute.\n", strings.Join(missing, " and ")) + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err @@ -199,6 +232,9 @@ func writeSAMLConfiguration(opts Options, resolution config.Resolution, heading fmt.Fprintf(tw, "Mapping first name:\t%s\n", emptyDash(configuration.Mapping.FirstName)) fmt.Fprintf(tw, "Mapping last name:\t%s\n", emptyDash(configuration.Mapping.LastName)) fmt.Fprintf(tw, "Mapping user principal name:\t%s\n", emptyDash(configuration.Mapping.UserPrincipalName)) + if configuration.Mapping.EmailVerified != nil { + fmt.Fprintf(tw, "Mapping email verified:\t%s\n", emptyDash(*configuration.Mapping.EmailVerified)) + } fmt.Fprintf(tw, "Mapping instance role:\t%s\n", emptyDash(configuration.Mapping.N8nInstanceRole)) fmt.Fprintf(tw, "Mapping project roles:\t%s\n", emptyDash(strings.Join(configuration.Mapping.N8nProjectRoles, ", "))) fmt.Fprintf(tw, "Identity provider metadata:\t%s\n", samlSecretStatus(configuration.Metadata)) @@ -210,6 +246,9 @@ func writeSAMLConfiguration(opts Options, resolution config.Resolution, heading fmt.Fprintf(tw, "Authentication requests signed:\t%s\n", yesNo(configuration.AuthnRequestsSigned)) fmt.Fprintf(tw, "Signed assertions required:\t%s\n", yesNo(configuration.WantAssertionsSigned)) fmt.Fprintf(tw, "Signed messages required:\t%s\n", yesNo(configuration.WantMessageSigned)) + if configuration.EmailVerifiedRequired != nil { + fmt.Fprintf(tw, "Verified email required:\t%s\n", yesNo(*configuration.EmailVerifiedRequired)) + } fmt.Fprintf(tw, "Signing private key:\t%s\n", samlSecretStatus(configuration.SigningPrivateKey)) fmt.Fprintf(tw, "Signing certificate:\t%s\n", samlSecretStatus(configuration.SigningCertificate)) fmt.Fprintf(tw, "ACS binding:\t%s\n", configuration.ACSBinding) @@ -233,7 +272,7 @@ func samlAPIError(err error, resolution config.Resolution, action string) error return forbiddenScopeError(err, resolution, "SAML configuration "+action, allOf("saml:manage"), "the instance also needs the SAML license.", samlResource) case n8n.IsStatus(err, http.StatusBadRequest) && action == "update": - return fmt.Errorf("%s rejected the full SAML replacement (400): include all 15 writable fields and every mapping and signature field, valid redirect/post bindings, and a supported signature action; response details redacted", resolution.URL) + return fmt.Errorf("%s rejected the full SAML replacement (400): include all 16 writable fields and every mapping and signature field (current n8n requires emailVerifiedRequired and mapping.emailVerified, older instances may not accept them; see --email-verified-required and --email-verified-attribute), valid redirect/post bindings, and a supported signature action; response details redacted", resolution.URL) case n8n.IsConflict(err) && action == "update": return fmt.Errorf("%s refused the SAML replacement (409): SAML SSO configuration is managed by environment variables, so no changes were made; change the environment configuration and restart n8n, then run 'n8n saml get'", resolution.URL) case n8n.IsNotFound(err): diff --git a/internal/cli/saml_test.go b/internal/cli/saml_test.go index 2f75cd0..ed31ac2 100644 --- a/internal/cli/saml_test.go +++ b/internal/cli/saml_test.go @@ -8,13 +8,15 @@ import ( "strings" "testing" + "github.com/google/go-cmp/cmp" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" ) const cliSAMLConfiguration = `{ "entityID":"https://n8n.example.com/rest/sso/saml/metadata", "returnUrl":"https://n8n.example.com/rest/sso/saml/acs", - "mapping":{"email":"email","firstName":"first","lastName":"last","userPrincipalName":"upn","n8nInstanceRole":"role","n8nProjectRoles":["project:role"]}, + "mapping":{"email":"email","firstName":"first","lastName":"last","userPrincipalName":"upn","emailVerified":"email_verified","n8nInstanceRole":"role","n8nProjectRoles":["project:role"]}, "metadata":"` + n8n.SAMLRedactedValue + `", "metadataUrl":"https://idp.example.com/metadata", "ignoreSSL":false, @@ -24,6 +26,7 @@ const cliSAMLConfiguration = `{ "authnRequestsSigned":true, "wantAssertionsSigned":true, "wantMessageSigned":false, + "emailVerifiedRequired":false, "signingPrivateKey":"` + n8n.SAMLRedactedValue + `", "signingCertificate":"` + n8n.SAMLRedactedValue + `", "acsBinding":"post", @@ -34,7 +37,7 @@ const cliSAMLConfiguration = `{ const cliSAMLDisabledInput = `{ "entityID":"https://n8n.example.com/rest/sso/saml/metadata", "returnUrl":"https://n8n.example.com/rest/sso/saml/acs", - "mapping":{"email":"email","firstName":"","lastName":"","userPrincipalName":"","n8nInstanceRole":"","n8nProjectRoles":[]}, + "mapping":{"email":"email","firstName":"","lastName":"","userPrincipalName":"","emailVerified":"","n8nInstanceRole":"","n8nProjectRoles":[]}, "metadata":"` + n8n.SAMLRedactedValue + `", "metadataUrl":"", "ignoreSSL":false, @@ -44,6 +47,7 @@ const cliSAMLDisabledInput = `{ "authnRequestsSigned":false, "wantAssertionsSigned":false, "wantMessageSigned":false, + "emailVerifiedRequired":false, "signingPrivateKey":"` + n8n.SAMLRedactedValue + `", "signingCertificate":"` + n8n.SAMLRedactedValue + `", "acsBinding":"post", @@ -81,6 +85,7 @@ func TestSAMLGetTextHidesSecretsAndShowsEverySetting(t *testing.T) { "configured (value hidden)", "Metadata URL:", "idp.example.com", "Ignore metadata URL SSL errors:", "no", "Login binding:", "redirect", "Login enabled:", "yes", "Login label:", "Company SSO", "Authentication requests signed:", "Signed assertions required:", "Signed messages required:", + "Mapping email verified:", "email_verified", "Verified email required:", "Signing private key:", "Signing certificate:", "ACS binding:", "post", "Signature prefix:", "Signature location reference:", "Signature location action:", "after", "Relay state:", } { @@ -156,7 +161,7 @@ func TestSAMLSetRequiresConfirmationAndPreservesFullReplacement(t *testing.T) { if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { t.Fatalf("request body is not JSON: %v", err) } - if len(sent) != 15 || sent["loginEnabled"] != false || sent["metadataUrl"] != "" || sent["relayState"] != "" || sent["signingPrivateKey"] != n8n.SAMLRedactedValue { + if len(sent) != 16 || sent["emailVerifiedRequired"] != false || sent["loginEnabled"] != false || sent["metadataUrl"] != "" || sent["relayState"] != "" || sent["signingPrivateKey"] != n8n.SAMLRedactedValue { t.Errorf("full replacement not preserved: %#v", sent) } if _, ok := sent["entityID"]; ok { @@ -169,6 +174,115 @@ func TestSAMLSetRequiresConfirmationAndPreservesFullReplacement(t *testing.T) { if roles, ok := mapping["n8nProjectRoles"].([]any); !ok || len(roles) != 0 { t.Errorf("empty project roles not preserved: %#v", mapping["n8nProjectRoles"]) } + if value, ok := mapping["emailVerified"]; !ok || value != "" { + t.Errorf("mapping.emailVerified = %#v (present %t), want explicit empty string", value, ok) + } + if strings.Contains(got.stderr, "Warning") { + t.Errorf("complete document warned: %s", got.stderr) + } +} + +func TestSAMLGetJSONRoundTripsThroughSetLosslessly(t *testing.T) { + f := samlFixture(t, cliSAMLConfiguration) + got := f.run("saml", "get", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("get exit = %d, stderr: %s", got.code, got.stderr) + } + f.stdin = got.stdout + set := f.run("saml", "set", "--input", "-", "--yes") + if set.code != ExitSuccess { + t.Fatalf("set exit = %d, stderr: %s", set.code, set.stderr) + } + var want, sent map[string]any + if err := json.Unmarshal([]byte(cliSAMLConfiguration), &want); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("request body is not JSON: %v", err) + } + delete(want, "entityID") + delete(want, "returnUrl") + if diff := cmp.Diff(want, sent); diff != "" { + t.Errorf("round trip changed the document (-get +set):\n%s", diff) + } +} + +func TestSAMLSetFromOlderInstanceDocumentWarnsAndOmitsEmailVerification(t *testing.T) { + f := samlFixture(t, cliSAMLConfiguration) + input := strings.Replace(cliSAMLDisabledInput, `"emailVerifiedRequired":false,`, "", 1) + input = strings.Replace(input, `"emailVerified":"",`, "", 1) + f.stdin = input + got := f.run("saml", "set", "--input", "-", "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"Warning", "emailVerifiedRequired and mapping.emailVerified", "--email-verified-required", "--email-verified-attribute"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("stderr missing %q: %s", want, got.stderr) + } + } + if strings.Contains(f.lastBody(), "emailVerified") { + t.Errorf("absent fields were invented: %s", f.lastBody()) + } +} + +func TestSAMLSetEmailVerificationFlagsOverrideInput(t *testing.T) { + older := strings.Replace(cliSAMLDisabledInput, `"emailVerifiedRequired":false,`, "", 1) + older = strings.Replace(older, `"emailVerified":"",`, "", 1) + current := strings.Replace(cliSAMLDisabledInput, `"emailVerifiedRequired":false`, `"emailVerifiedRequired":true`, 1) + current = strings.Replace(current, `"emailVerified":""`, `"emailVerified":"verified"`, 1) + tests := []struct { + name string + input string + args []string + wantRequired bool + wantAttribute string + }{ + {name: "fill older document", input: older, args: []string{"--email-verified-required", "--email-verified-attribute", "email_verified"}, wantRequired: true, wantAttribute: "email_verified"}, + {name: "explicit false and empty override", input: current, args: []string{"--email-verified-required=false", "--email-verified-attribute", ""}, wantRequired: false, wantAttribute: ""}, + {name: "unset flags keep input", input: current, wantRequired: true, wantAttribute: "verified"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := samlFixture(t, cliSAMLConfiguration) + f.stdin = tt.input + got := f.run(append([]string{"saml", "set", "--input", "-", "--yes"}, tt.args...)...) + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if strings.Contains(got.stderr, "Warning") { + t.Errorf("complete request warned: %s", got.stderr) + } + var sent struct { + EmailVerifiedRequired *bool `json:"emailVerifiedRequired"` + Mapping struct { + EmailVerified *string `json:"emailVerified"` + } `json:"mapping"` + } + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("request body is not JSON: %v", err) + } + if sent.EmailVerifiedRequired == nil || *sent.EmailVerifiedRequired != tt.wantRequired { + t.Errorf("emailVerifiedRequired = %v, want %t", sent.EmailVerifiedRequired, tt.wantRequired) + } + if sent.Mapping.EmailVerified == nil || *sent.Mapping.EmailVerified != tt.wantAttribute { + t.Errorf("mapping.emailVerified = %v, want %q", sent.Mapping.EmailVerified, tt.wantAttribute) + } + }) + } +} + +func TestSAMLSetHelpDocumentsEmailVerificationFields(t *testing.T) { + f := samlFixture(t, cliSAMLConfiguration) + got := f.run("saml", "set", "--help") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"--email-verified-required", "--email-verified-attribute", "emailVerifiedRequired", "mapping.emailVerified", "round-trips"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("help missing %q:\n%s", want, got.stdout) + } + } } func TestSAMLSetFromStdinRequiresYesAndPreservesSentinels(t *testing.T) { @@ -258,7 +372,7 @@ func TestSAMLAPIErrorsExplainLicenseConflictAndAvailability(t *testing.T) { want []string }{ {name: "forbidden", status: http.StatusForbidden, args: []string{"saml", "get"}, want: []string{"saml:manage", "SAML license", "discover --resource settingsssosaml"}}, - {name: "invalid replacement", status: http.StatusBadRequest, args: []string{"saml", "set", "--input", "-", "--yes"}, input: cliSAMLDisabledInput, want: []string{"full SAML replacement", "15 writable fields", "response details redacted"}}, + {name: "invalid replacement", status: http.StatusBadRequest, args: []string{"saml", "set", "--input", "-", "--yes"}, input: cliSAMLDisabledInput, want: []string{"full SAML replacement", "16 writable fields", "emailVerifiedRequired", "--email-verified-attribute", "response details redacted"}}, {name: "environment managed", status: http.StatusConflict, args: []string{"saml", "set", "--input", "-", "--yes"}, input: cliSAMLDisabledInput, want: []string{"managed by environment variables", "no changes were made", "saml get"}}, {name: "not found", status: http.StatusNotFound, args: []string{"saml", "get"}, want: []string{"SAML endpoint", "discover --resource settingsssosaml"}}, {name: "unavailable", status: http.StatusServiceUnavailable, args: []string{"saml", "get"}, want: []string{"SAML service", "discover --resource settingsssosaml"}}, diff --git a/internal/n8n/otel.go b/internal/n8n/otel.go index b30d3bd..2ccb781 100644 --- a/internal/n8n/otel.go +++ b/internal/n8n/otel.go @@ -26,6 +26,8 @@ const ( ) // OtelSettings is the effective instance-wide OpenTelemetry configuration. +// EmitWorkflowStartSpan and EmitNodeStartSpan are nil when the instance +// predates them, so a GET document replays to that instance without them. type OtelSettings struct { Enabled bool `json:"enabled"` ExporterProtocol OtelExporterProtocol `json:"exporterProtocol"` @@ -36,6 +38,8 @@ type OtelSettings struct { TracesSampleRate float64 `json:"tracesSampleRate"` StartupConnectivityTimeoutMs int `json:"startupConnectivityTimeoutMs"` IncludeNodeSpans bool `json:"includeNodeSpans"` + EmitWorkflowStartSpan *bool `json:"emitWorkflowStartSpan,omitempty"` + EmitNodeStartSpan *bool `json:"emitNodeStartSpan,omitempty"` InjectOutbound bool `json:"injectOutbound"` ProductionExecutionsOnly bool `json:"productionExecutionsOnly"` } @@ -49,6 +53,9 @@ func (s *OtelSettings) applyDefaults() { // UpdateOtelSettingsRequest is a full replacement document. Pointers preserve // omitted required fields separately from valid false, zero, and empty values. // ExporterProtocol is optional; omission selects http/protobuf on the server. +// EmitWorkflowStartSpan and EmitNodeStartSpan are optional too, but omission +// selects false: a replacement without them turns both spans off, and an +// instance that pins either to true by environment answers 409. type UpdateOtelSettingsRequest struct { Enabled *bool `json:"enabled"` ExporterProtocol OtelExporterProtocol `json:"exporterProtocol,omitempty"` @@ -59,6 +66,8 @@ type UpdateOtelSettingsRequest struct { TracesSampleRate *float64 `json:"tracesSampleRate"` StartupConnectivityTimeoutMs *int `json:"startupConnectivityTimeoutMs"` IncludeNodeSpans *bool `json:"includeNodeSpans"` + EmitWorkflowStartSpan *bool `json:"emitWorkflowStartSpan,omitempty"` + EmitNodeStartSpan *bool `json:"emitNodeStartSpan,omitempty"` InjectOutbound *bool `json:"injectOutbound"` ProductionExecutionsOnly *bool `json:"productionExecutionsOnly"` } @@ -93,6 +102,19 @@ func (r UpdateOtelSettingsRequest) Validate() error { return nil } +// MissingStartSpans names the optional start-span fields the request omits, +// which the server then sets to false. +func (r UpdateOtelSettingsRequest) MissingStartSpans() []string { + var missing []string + if r.EmitWorkflowStartSpan == nil { + missing = append(missing, "emitWorkflowStartSpan") + } + if r.EmitNodeStartSpan == nil { + missing = append(missing, "emitNodeStartSpan") + } + return missing +} + // OtelTestTraceRequest contains collector details for one test span. It does // not modify stored settings. ExporterProtocol defaults to http/protobuf. type OtelTestTraceRequest struct { diff --git a/internal/n8n/otel_test.go b/internal/n8n/otel_test.go index 9d30c2f..d28c884 100644 --- a/internal/n8n/otel_test.go +++ b/internal/n8n/otel_test.go @@ -19,6 +19,8 @@ const otelSettingsResponse = `{ "tracesSampleRate":0.25, "startupConnectivityTimeoutMs":2500, "includeNodeSpans":false, + "emitWorkflowStartSpan":true, + "emitNodeStartSpan":false, "injectOutbound":true, "productionExecutionsOnly":true }` @@ -36,6 +38,8 @@ func validOtelUpdateRequest() UpdateOtelSettingsRequest { TracesSampleRate: ptr(0.0), StartupConnectivityTimeoutMs: ptr(0), IncludeNodeSpans: ptr(false), + EmitWorkflowStartSpan: ptr(false), + EmitNodeStartSpan: ptr(false), InjectOutbound: ptr(false), ProductionExecutionsOnly: ptr(false), } @@ -70,6 +74,26 @@ func TestGetOtelSettings(t *testing.T) { !settings.InjectOutbound || !settings.ProductionExecutionsOnly { t.Errorf("settings = %+v", settings) } + if settings.EmitWorkflowStartSpan == nil || !*settings.EmitWorkflowStartSpan || settings.EmitNodeStartSpan == nil || *settings.EmitNodeStartSpan { + t.Errorf("start spans = %v, %v; want true, false", settings.EmitWorkflowStartSpan, settings.EmitNodeStartSpan) + } +} + +func TestGetOtelSettingsFromOlderInstanceOmitsStartSpans(t *testing.T) { + body := strings.Replace(otelSettingsResponse, `"emitWorkflowStartSpan":true,`, "", 1) + body = strings.Replace(body, `"emitNodeStartSpan":false,`, "", 1) + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + settings, err := server.client(t).GetOtelSettings(context.Background()) + if err != nil { + t.Fatalf("GetOtelSettings: %v", err) + } + if settings.EmitWorkflowStartSpan != nil || settings.EmitNodeStartSpan != nil { + t.Errorf("absent start spans decoded as %v, %v; want nil", settings.EmitWorkflowStartSpan, settings.EmitNodeStartSpan) + } + encoded, _ := json.Marshal(settings) + if strings.Contains(string(encoded), "StartSpan") { + t.Errorf("absent start spans were invented on re-encode: %s", encoded) + } } func TestGetOtelSettingsAppliesDefaultProtocol(t *testing.T) { @@ -103,6 +127,17 @@ func TestUpdateOtelSettingsFullReplacement(t *testing.T) { sent["includeNodeSpans"] != false || sent["injectOutbound"] != false || sent["productionExecutionsOnly"] != false { t.Errorf("false and zero replacement values not preserved: %#v", sent) } + for _, field := range []string{"emitWorkflowStartSpan", "emitNodeStartSpan"} { + if value, ok := sent[field]; !ok || value != false { + t.Errorf("%s = %#v (present %t), want explicit false", field, value, ok) + } + } + if len(sent) != 13 { + t.Errorf("replacement has %d fields, want 13: %#v", len(sent), sent) + } + if got := request.MissingStartSpans(); len(got) != 0 { + t.Errorf("complete request reports missing %v", got) + } if settings.ExporterProtocol != OtelProtocolGRPC || settings.TracesSampleRate != 0.25 { t.Errorf("decoded settings = %+v", settings) } @@ -129,6 +164,22 @@ func TestUpdateOtelSettingsOmitsProtocolForServerDefault(t *testing.T) { } } +func TestUpdateOtelSettingsOmitsUnsetStartSpans(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, otelSettingsResponse)) + request := validOtelUpdateRequest() + request.EmitWorkflowStartSpan = nil + request.EmitNodeStartSpan = nil + if got := request.MissingStartSpans(); len(got) != 2 || got[0] != "emitWorkflowStartSpan" || got[1] != "emitNodeStartSpan" { + t.Errorf("MissingStartSpans = %v", got) + } + if _, err := server.client(t).UpdateOtelSettings(context.Background(), request); err != nil { + t.Fatalf("UpdateOtelSettings: %v", err) + } + if _, body := server.last(t); strings.Contains(body, "StartSpan") { + t.Errorf("unset start spans were sent: %s", body) + } +} + func TestOtelTraceResult(t *testing.T) { for _, tt := range []struct { name string diff --git a/internal/n8n/saml.go b/internal/n8n/saml.go index 9abfbbe..b364fd2 100644 --- a/internal/n8n/saml.go +++ b/internal/n8n/saml.go @@ -36,11 +36,13 @@ const ( ) // SAMLMapping maps identity-provider attributes to n8n user fields. +// EmailVerified is nil when the instance predates the field. type SAMLMapping struct { Email string `json:"email"` FirstName string `json:"firstName"` LastName string `json:"lastName"` UserPrincipalName string `json:"userPrincipalName"` + EmailVerified *string `json:"emailVerified,omitempty"` N8nInstanceRole string `json:"n8nInstanceRole"` N8nProjectRoles []string `json:"n8nProjectRoles"` } @@ -59,25 +61,28 @@ type SAMLSignatureConfig struct { // SAMLConfiguration is the effective instance-wide SAML SSO configuration. // Secret-bearing fields are always empty or SAMLRedactedValue after decoding, -// even if a non-conforming server returns plaintext. +// even if a non-conforming server returns plaintext. EmailVerifiedRequired is +// nil when the instance predates the field, so a GET document replays to that +// instance without it. type SAMLConfiguration struct { - EntityID string `json:"entityID"` - ReturnURL string `json:"returnUrl"` - Mapping SAMLMapping `json:"mapping"` - Metadata string `json:"metadata"` - MetadataURL string `json:"metadataUrl"` - IgnoreSSL bool `json:"ignoreSSL"` - LoginBinding SAMLBinding `json:"loginBinding"` - LoginEnabled bool `json:"loginEnabled"` - LoginLabel string `json:"loginLabel"` - AuthnRequestsSigned bool `json:"authnRequestsSigned"` - WantAssertionsSigned bool `json:"wantAssertionsSigned"` - WantMessageSigned bool `json:"wantMessageSigned"` - SigningPrivateKey string `json:"signingPrivateKey"` - SigningCertificate string `json:"signingCertificate"` - ACSBinding SAMLBinding `json:"acsBinding"` - SignatureConfig SAMLSignatureConfig `json:"signatureConfig"` - RelayState string `json:"relayState"` + EntityID string `json:"entityID"` + ReturnURL string `json:"returnUrl"` + Mapping SAMLMapping `json:"mapping"` + Metadata string `json:"metadata"` + MetadataURL string `json:"metadataUrl"` + IgnoreSSL bool `json:"ignoreSSL"` + LoginBinding SAMLBinding `json:"loginBinding"` + LoginEnabled bool `json:"loginEnabled"` + LoginLabel string `json:"loginLabel"` + AuthnRequestsSigned bool `json:"authnRequestsSigned"` + WantAssertionsSigned bool `json:"wantAssertionsSigned"` + WantMessageSigned bool `json:"wantMessageSigned"` + EmailVerifiedRequired *bool `json:"emailVerifiedRequired,omitempty"` + SigningPrivateKey string `json:"signingPrivateKey"` + SigningCertificate string `json:"signingCertificate"` + ACSBinding SAMLBinding `json:"acsBinding"` + SignatureConfig SAMLSignatureConfig `json:"signatureConfig"` + RelayState string `json:"relayState"` } func (c *SAMLConfiguration) redactSecrets() { @@ -89,12 +94,14 @@ func (c *SAMLConfiguration) redactSecrets() { } // SetSAMLMapping is a full replacement mapping. Pointers distinguish omitted -// required fields from valid empty strings and arrays. +// required fields from valid empty strings and arrays. EmailVerified is required +// by current n8n but unknown to older instances, so it is sent only when set. type SetSAMLMapping struct { Email *string `json:"email"` FirstName *string `json:"firstName"` LastName *string `json:"lastName"` UserPrincipalName *string `json:"userPrincipalName"` + EmailVerified *string `json:"emailVerified,omitempty"` N8nInstanceRole *string `json:"n8nInstanceRole"` N8nProjectRoles *[]string `json:"n8nProjectRoles"` } @@ -114,24 +121,28 @@ type SetSAMLSignatureConfig struct { // SetSAMLConfigurationRequest is a full replacement document. EntityID and // ReturnURL are accepted so a GET document can be read directly, but are never // sent because they are server-computed, read-only values. +// EmailVerifiedRequired and Mapping.EmailVerified are required by current n8n +// but unknown to older instances, so they are sent only when set; see +// MissingEmailVerification. type SetSAMLConfigurationRequest struct { - EntityID *string `json:"entityID,omitempty"` - ReturnURL *string `json:"returnUrl,omitempty"` - Mapping *SetSAMLMapping `json:"mapping"` - Metadata *string `json:"metadata"` - MetadataURL *string `json:"metadataUrl"` - IgnoreSSL *bool `json:"ignoreSSL"` - LoginBinding *SAMLBinding `json:"loginBinding"` - LoginEnabled *bool `json:"loginEnabled"` - LoginLabel *string `json:"loginLabel"` - AuthnRequestsSigned *bool `json:"authnRequestsSigned"` - WantAssertionsSigned *bool `json:"wantAssertionsSigned"` - WantMessageSigned *bool `json:"wantMessageSigned"` - SigningPrivateKey *string `json:"signingPrivateKey"` - SigningCertificate *string `json:"signingCertificate"` - ACSBinding *SAMLBinding `json:"acsBinding"` - SignatureConfig *SetSAMLSignatureConfig `json:"signatureConfig"` - RelayState *string `json:"relayState"` + EntityID *string `json:"entityID,omitempty"` + ReturnURL *string `json:"returnUrl,omitempty"` + Mapping *SetSAMLMapping `json:"mapping"` + Metadata *string `json:"metadata"` + MetadataURL *string `json:"metadataUrl"` + IgnoreSSL *bool `json:"ignoreSSL"` + LoginBinding *SAMLBinding `json:"loginBinding"` + LoginEnabled *bool `json:"loginEnabled"` + LoginLabel *string `json:"loginLabel"` + AuthnRequestsSigned *bool `json:"authnRequestsSigned"` + WantAssertionsSigned *bool `json:"wantAssertionsSigned"` + WantMessageSigned *bool `json:"wantMessageSigned"` + EmailVerifiedRequired *bool `json:"emailVerifiedRequired,omitempty"` + SigningPrivateKey *string `json:"signingPrivateKey"` + SigningCertificate *string `json:"signingCertificate"` + ACSBinding *SAMLBinding `json:"acsBinding"` + SignatureConfig *SetSAMLSignatureConfig `json:"signatureConfig"` + RelayState *string `json:"relayState"` } // Validate enforces every writable full-replacement field and documented enum. @@ -173,6 +184,20 @@ func (r SetSAMLConfigurationRequest) Validate() error { return r.SignatureConfig.validate() } +// MissingEmailVerification names the email-verification fields current n8n +// requires that the request omits. Older instances do not know them, so +// omission is not a local validation error. +func (r SetSAMLConfigurationRequest) MissingEmailVerification() []string { + var missing []string + if r.EmailVerifiedRequired == nil { + missing = append(missing, "emailVerifiedRequired") + } + if r.Mapping == nil || r.Mapping.EmailVerified == nil { + missing = append(missing, "mapping.emailVerified") + } + return missing +} + func (m *SetSAMLMapping) validate() error { required := []struct { name string @@ -227,21 +252,22 @@ func validateSAMLBinding(name string, binding SAMLBinding) error { } type samlConfigurationUpdate struct { - Mapping *SetSAMLMapping `json:"mapping"` - Metadata *string `json:"metadata"` - MetadataURL *string `json:"metadataUrl"` - IgnoreSSL *bool `json:"ignoreSSL"` - LoginBinding *SAMLBinding `json:"loginBinding"` - LoginEnabled *bool `json:"loginEnabled"` - LoginLabel *string `json:"loginLabel"` - AuthnRequestsSigned *bool `json:"authnRequestsSigned"` - WantAssertionsSigned *bool `json:"wantAssertionsSigned"` - WantMessageSigned *bool `json:"wantMessageSigned"` - SigningPrivateKey *string `json:"signingPrivateKey"` - SigningCertificate *string `json:"signingCertificate"` - ACSBinding *SAMLBinding `json:"acsBinding"` - SignatureConfig *SetSAMLSignatureConfig `json:"signatureConfig"` - RelayState *string `json:"relayState"` + Mapping *SetSAMLMapping `json:"mapping"` + Metadata *string `json:"metadata"` + MetadataURL *string `json:"metadataUrl"` + IgnoreSSL *bool `json:"ignoreSSL"` + LoginBinding *SAMLBinding `json:"loginBinding"` + LoginEnabled *bool `json:"loginEnabled"` + LoginLabel *string `json:"loginLabel"` + AuthnRequestsSigned *bool `json:"authnRequestsSigned"` + WantAssertionsSigned *bool `json:"wantAssertionsSigned"` + WantMessageSigned *bool `json:"wantMessageSigned"` + EmailVerifiedRequired *bool `json:"emailVerifiedRequired,omitempty"` + SigningPrivateKey *string `json:"signingPrivateKey"` + SigningCertificate *string `json:"signingCertificate"` + ACSBinding *SAMLBinding `json:"acsBinding"` + SignatureConfig *SetSAMLSignatureConfig `json:"signatureConfig"` + RelayState *string `json:"relayState"` } func (r SetSAMLConfigurationRequest) update() samlConfigurationUpdate { @@ -250,7 +276,8 @@ func (r SetSAMLConfigurationRequest) update() samlConfigurationUpdate { IgnoreSSL: r.IgnoreSSL, LoginBinding: r.LoginBinding, LoginEnabled: r.LoginEnabled, LoginLabel: r.LoginLabel, AuthnRequestsSigned: r.AuthnRequestsSigned, WantAssertionsSigned: r.WantAssertionsSigned, WantMessageSigned: r.WantMessageSigned, - SigningPrivateKey: r.SigningPrivateKey, SigningCertificate: r.SigningCertificate, + EmailVerifiedRequired: r.EmailVerifiedRequired, + SigningPrivateKey: r.SigningPrivateKey, SigningCertificate: r.SigningCertificate, ACSBinding: r.ACSBinding, SignatureConfig: r.SignatureConfig, RelayState: r.RelayState, } } diff --git a/internal/n8n/saml_test.go b/internal/n8n/saml_test.go index 90e74af..a2828ec 100644 --- a/internal/n8n/saml_test.go +++ b/internal/n8n/saml_test.go @@ -11,7 +11,7 @@ import ( const samlConfigurationResponse = `{ "entityID":"https://n8n.example.com/rest/sso/saml/metadata", "returnUrl":"https://n8n.example.com/rest/sso/saml/acs", - "mapping":{"email":"email","firstName":"first","lastName":"last","userPrincipalName":"upn","n8nInstanceRole":"role","n8nProjectRoles":["project:role"]}, + "mapping":{"email":"email","firstName":"first","lastName":"last","userPrincipalName":"upn","emailVerified":"email_verified","n8nInstanceRole":"role","n8nProjectRoles":["project:role"]}, "metadata":"` + SAMLRedactedValue + `", "metadataUrl":"https://idp.example.com/metadata", "ignoreSSL":false, @@ -21,6 +21,7 @@ const samlConfigurationResponse = `{ "authnRequestsSigned":true, "wantAssertionsSigned":true, "wantMessageSigned":false, + "emailVerifiedRequired":true, "signingPrivateKey":"` + SAMLRedactedValue + `", "signingCertificate":"` + SAMLRedactedValue + `", "acsBinding":"post", @@ -34,12 +35,13 @@ func validSAMLSetRequest() SetSAMLConfigurationRequest { ReturnURL: ptr("https://ignored.example.com/acs"), Mapping: &SetSAMLMapping{ Email: ptr("email"), FirstName: ptr("first"), LastName: ptr("last"), - UserPrincipalName: ptr("upn"), N8nInstanceRole: ptr(""), N8nProjectRoles: ptr([]string{}), + UserPrincipalName: ptr("upn"), EmailVerified: ptr(""), N8nInstanceRole: ptr(""), N8nProjectRoles: ptr([]string{}), }, Metadata: ptr(SAMLRedactedValue), MetadataURL: ptr(""), IgnoreSSL: ptr(false), LoginBinding: ptr(SAMLBindingRedirect), LoginEnabled: ptr(false), LoginLabel: ptr(""), AuthnRequestsSigned: ptr(false), WantAssertionsSigned: ptr(false), WantMessageSigned: ptr(false), - SigningPrivateKey: ptr(SAMLRedactedValue), SigningCertificate: ptr(SAMLRedactedValue), + EmailVerifiedRequired: ptr(false), + SigningPrivateKey: ptr(SAMLRedactedValue), SigningCertificate: ptr(SAMLRedactedValue), ACSBinding: ptr(SAMLBindingPost), SignatureConfig: &SetSAMLSignatureConfig{Prefix: ptr("ds"), Location: &SetSAMLSignatureLocation{ Reference: ptr("/samlp:Response/saml:Issuer"), Action: ptr(SAMLSignatureAfter), @@ -64,6 +66,9 @@ func TestGetSAMLConfiguration(t *testing.T) { if !configuration.LoginEnabled || configuration.LoginBinding != SAMLBindingRedirect || configuration.ACSBinding != SAMLBindingPost || configuration.Mapping.Email != "email" || len(configuration.Mapping.N8nProjectRoles) != 1 { t.Errorf("configuration = %+v", configuration) } + if configuration.EmailVerifiedRequired == nil || !*configuration.EmailVerifiedRequired || configuration.Mapping.EmailVerified == nil || *configuration.Mapping.EmailVerified != "email_verified" { + t.Errorf("email verification fields = %v, %v", configuration.EmailVerifiedRequired, configuration.Mapping.EmailVerified) + } if configuration.Metadata != SAMLRedactedValue || configuration.SigningPrivateKey != SAMLRedactedValue || configuration.SigningCertificate != SAMLRedactedValue { t.Errorf("secret placeholders = %q, %q, %q", configuration.Metadata, configuration.SigningPrivateKey, configuration.SigningCertificate) } @@ -112,8 +117,11 @@ func TestSetSAMLConfigurationFullReplacementAndIgnoresReadOnlyFields(t *testing. if err := json.Unmarshal([]byte(body), &sent); err != nil { t.Fatalf("body is not JSON: %v", err) } - if len(sent) != 15 { - t.Errorf("replacement has %d fields, want 15: %#v", len(sent), sent) + if len(sent) != 16 { + t.Errorf("replacement has %d fields, want 16: %#v", len(sent), sent) + } + if value, ok := sent["emailVerifiedRequired"]; !ok || value != false { + t.Errorf("emailVerifiedRequired = %#v (present %t), want explicit false", value, ok) } if _, ok := sent["entityID"]; ok { t.Error("read-only entityID was sent") @@ -125,6 +133,12 @@ func TestSetSAMLConfigurationFullReplacementAndIgnoresReadOnlyFields(t *testing. t.Errorf("false, empty, or sentinel values were not preserved: %#v", sent) } mapping := sent["mapping"].(map[string]any) + if len(mapping) != 7 { + t.Errorf("mapping has %d fields, want 7: %#v", len(mapping), mapping) + } + if value, ok := mapping["emailVerified"]; !ok || value != "" { + t.Errorf("mapping.emailVerified = %#v (present %t), want explicit empty string", value, ok) + } if roles, ok := mapping["n8nProjectRoles"].([]any); !ok || len(roles) != 0 { t.Errorf("empty project role array not preserved: %#v", mapping["n8nProjectRoles"]) } @@ -133,6 +147,43 @@ func TestSetSAMLConfigurationFullReplacementAndIgnoresReadOnlyFields(t *testing. } } +func TestGetSAMLConfigurationFromOlderInstanceOmitsEmailVerification(t *testing.T) { + body := strings.Replace(samlConfigurationResponse, `"emailVerifiedRequired":true,`, "", 1) + body = strings.Replace(body, `"emailVerified":"email_verified",`, "", 1) + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + configuration, err := server.client(t).GetSAMLConfiguration(context.Background()) + if err != nil { + t.Fatalf("GetSAMLConfiguration: %v", err) + } + if configuration.EmailVerifiedRequired != nil || configuration.Mapping.EmailVerified != nil { + t.Errorf("absent fields decoded as %v, %v; want nil", configuration.EmailVerifiedRequired, configuration.Mapping.EmailVerified) + } + encoded, _ := json.Marshal(configuration) + if strings.Contains(string(encoded), "emailVerified") { + t.Errorf("absent fields were invented on re-encode: %s", encoded) + } +} + +func TestSetSAMLConfigurationOmitsUnsetEmailVerificationForOlderInstances(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, samlConfigurationResponse)) + request := validSAMLSetRequest() + request.EmailVerifiedRequired = nil + request.Mapping.EmailVerified = nil + if got := request.MissingEmailVerification(); len(got) != 2 || got[0] != "emailVerifiedRequired" || got[1] != "mapping.emailVerified" { + t.Errorf("MissingEmailVerification = %v", got) + } + if _, err := server.client(t).SetSAMLConfiguration(context.Background(), request); err != nil { + t.Fatalf("SetSAMLConfiguration: %v", err) + } + _, body := server.last(t) + if strings.Contains(body, "emailVerified") { + t.Errorf("unset email-verification fields were sent: %s", body) + } + if got := validSAMLSetRequest().MissingEmailVerification(); len(got) != 0 { + t.Errorf("complete request reports missing %v", got) + } +} + func TestSetSAMLConfigurationCanReplaceSecretsWithoutReturningThem(t *testing.T) { const secret = "new-private-material" server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, strings.ReplaceAll(samlConfigurationResponse, SAMLRedactedValue, secret)))