diff --git a/docs/n8n_ldap_get.md b/docs/n8n_ldap_get.md index 473f89b..8076bf1 100644 --- a/docs/n8n_ldap_get.md +++ b/docs/n8n_ldap_get.md @@ -8,6 +8,7 @@ Get every LDAP setting exposed by n8n. The binding admin password is never returned: bindingAdminPassword is empty when unset or n8n's blanking placeholder when configured. Keep that placeholder unchanged in a GET-edit-PUT workflow to preserve the stored password. Text output only reports password status. +linkExistingAccountsByEmail appears only on instances that support it. Requires ldap:manage and the LDAP license. diff --git a/docs/n8n_ldap_set.md b/docs/n8n_ldap_set.md index f148aac..5483829 100644 --- a/docs/n8n_ldap_set.md +++ b/docs/n8n_ldap_set.md @@ -5,7 +5,10 @@ Fully replace LDAP configuration ### Synopsis Fully replace the instance LDAP configuration from strict JSON. This is a PUT, -not a patch: all 20 fields are required, including false, zero, and empty values. +not a patch: the 20 core fields are required, including false, zero, and empty +values. linkExistingAccountsByEmail is optional and keeps its stored value when +omitted; when false, login and synchronization skip LDAP users whose email matches +an existing n8n account. Omit it on instances whose 'get' output does not include it. Start from 'n8n ldap get --output json'. Leave the returned password placeholder unchanged to preserve the stored bind password, replace it to set a new password, or use an empty string to clear it. Input files therefore require secret-safe diff --git a/internal/cli/ldap.go b/internal/cli/ldap.go index a47a74f..ab3bc0c 100644 --- a/internal/cli/ldap.go +++ b/internal/cli/ldap.go @@ -60,7 +60,8 @@ func newLDAPGetCommand(opts Options) *cobra.Command { Long: "Get every LDAP setting exposed by n8n. The binding admin password is never\n" + "returned: bindingAdminPassword is empty when unset or n8n's blanking placeholder\n" + "when configured. Keep that placeholder unchanged in a GET-edit-PUT workflow to\n" + - "preserve the stored password. Text output only reports password status.\n\n" + + "preserve the stored password. Text output only reports password status.\n" + + "linkExistingAccountsByEmail appears only on instances that support it.\n\n" + "Requires ldap:manage and the LDAP license.", Example: " n8n ldap get\n" + " n8n ldap get --output json\n" + @@ -101,7 +102,10 @@ func newLDAPSetCommand(opts Options) *cobra.Command { Use: "set", Short: "Fully replace LDAP configuration", Long: "Fully replace the instance LDAP configuration from strict JSON. This is a PUT,\n" + - "not a patch: all 20 fields are required, including false, zero, and empty values.\n" + + "not a patch: the 20 core fields are required, including false, zero, and empty\n" + + "values. linkExistingAccountsByEmail is optional and keeps its stored value when\n" + + "omitted; when false, login and synchronization skip LDAP users whose email matches\n" + + "an existing n8n account. Omit it on instances whose 'get' output does not include it.\n" + "Start from 'n8n ldap get --output json'. Leave the returned password placeholder\n" + "unchanged to preserve the stored bind password, replace it to set a new password,\n" + "or use an empty string to clear it. Input files therefore require secret-safe\n" + @@ -216,9 +220,17 @@ func writeLDAPConfiguration(opts Options, resolution config.Resolution, heading fmt.Fprintf(tw, "Search page size:\t%d\n", configuration.SearchPageSize) fmt.Fprintf(tw, "Search timeout:\t%d seconds\n", configuration.SearchTimeout) fmt.Fprintf(tw, "Enforce email uniqueness:\t%s\n", yesNo(configuration.EnforceEmailUniqueness)) + fmt.Fprintf(tw, "Link existing accounts by email:\t%s\n", ldapOptionalYesNo(configuration.LinkExistingAccountsByEmail)) return tw.Flush() } +func ldapOptionalYesNo(value *bool) string { + if value == nil { + return "not reported (instance does not support it)" + } + return yesNo(*value) +} + func ldapPasswordStatus(password string) string { if password == "" { return "not configured" @@ -420,7 +432,7 @@ func ldapAPIError(err error, resolution config.Resolution, action string) error return forbiddenScopeError(err, resolution, "LDAP "+action, allOf(scope), "the instance also needs the LDAP license.", ldapResource) case n8n.IsStatus(err, http.StatusBadRequest) && action == "update configuration": - return fmt.Errorf("%s rejected the full LDAP replacement (400): include all 20 fields and use connectionSecurity none, tls, or startTls; response details redacted", resolution.URL) + return fmt.Errorf("%s rejected the full LDAP replacement (400): include all 20 core fields, use connectionSecurity none, tls, or startTls, and omit linkExistingAccountsByEmail if 'n8n ldap get --output json' does not return it; response details redacted", resolution.URL) case n8n.IsStatus(err, http.StatusBadRequest) && action == "run sync": return fmt.Errorf("%s rejected the LDAP synchronization (400): check LDAP configuration and choose --type dry or live", resolution.URL) case n8n.IsNotFound(err): diff --git a/internal/cli/ldap_test.go b/internal/cli/ldap_test.go index a858834..43b31e7 100644 --- a/internal/cli/ldap_test.go +++ b/internal/cli/ldap_test.go @@ -31,7 +31,8 @@ const cliLDAPConfiguration = `{ "synchronizationInterval":60, "searchPageSize":1000, "searchTimeout":30, - "enforceEmailUniqueness":true + "enforceEmailUniqueness":true, + "linkExistingAccountsByEmail":false }` const cliLDAPDisabledInput = `{ @@ -99,6 +100,7 @@ func TestLDAPGetTextHidesPasswordAndShowsEverySetting(t *testing.T) { "dc=example,dc=com", "cn=admin,dc=example,dc=com", "Binding admin password:", "configured (value hidden)", "givenName", "sn", "mail", "uid", "(objectClass=inetOrgPerson)", "Synchronization enabled:", "60 minutes", "1000", "30 seconds", "Enforce email uniqueness:", + "Link existing accounts by email:", } { if !strings.Contains(got.stdout, want) { t.Errorf("stdout missing %q:\n%s", want, got.stdout) @@ -107,6 +109,9 @@ func TestLDAPGetTextHidesPasswordAndShowsEverySetting(t *testing.T) { if strings.Contains(got.stdout, n8n.CredentialBlankingValue) { t.Error("text output printed password placeholder") } + if !strings.Contains(got.stdout, "Link existing accounts by email: no") { + t.Errorf("link setting not shown as no:\n%s", got.stdout) + } req := f.lastRequest() if req.Method != http.MethodGet || req.URL.EscapedPath() != n8n.BasePath+n8n.LDAPSettingsPath || f.lastBody() != "" { t.Errorf("request = %s %s body %q", req.Method, req.URL.EscapedPath(), f.lastBody()) @@ -131,6 +136,71 @@ func TestLDAPGetJSONSupportsSafeRoundTrip(t *testing.T) { } } +func TestLDAPGetOlderInstanceOmitsLinkExistingAccounts(t *testing.T) { + body := strings.Replace(cliLDAPConfiguration, `, + "linkExistingAccountsByEmail":false`, "", 1) + f := ldapFixture(t, body) + got := f.run("ldap", "get") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if !strings.Contains(got.stdout, "not reported (instance does not support it)") { + t.Errorf("stdout missing not-reported marker:\n%s", got.stdout) + } + got = f.run("ldap", "get", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("json exit = %d, stderr: %s", got.code, got.stderr) + } + if strings.Contains(got.stdout, "linkExistingAccountsByEmail") { + t.Errorf("JSON reported unsupported setting:\n%s", got.stdout) + } + + path := writeLDAPInput(t, got.stdout) + got = f.run("ldap", "set", "--input", path, "--yes") + if got.code != ExitSuccess { + t.Fatalf("set exit = %d, stderr: %s", got.code, got.stderr) + } + if strings.Contains(f.lastBody(), "linkExistingAccountsByEmail") { + t.Errorf("replacement sent unsupported setting: %s", f.lastBody()) + } +} + +func TestLDAPGetSetRoundTripKeepsLinkExistingAccounts(t *testing.T) { + f := ldapFixture(t, cliLDAPConfiguration) + got := f.run("ldap", "get", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("get exit = %d, stderr: %s", got.code, got.stderr) + } + path := writeLDAPInput(t, got.stdout) + got = f.run("ldap", "set", "--input", path, "--yes") + if got.code != ExitSuccess { + t.Fatalf("set 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", err) + } + if len(sent) != 21 || sent["linkExistingAccountsByEmail"] != false { + t.Errorf("round trip lost setting: %#v", sent) + } +} + +func TestLDAPSetAcceptsLinkExistingAccounts(t *testing.T) { + f := ldapFixture(t, cliLDAPConfiguration) + f.stdin = strings.TrimSuffix(cliLDAPDisabledInput, "}") + `,"linkExistingAccountsByEmail":true}` + got := f.run("ldap", "set", "--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", err) + } + if sent["linkExistingAccountsByEmail"] != true { + t.Errorf("setting not sent: %#v", sent) + } +} + func TestLDAPGetSanitizesNonconformingPlaintextResponse(t *testing.T) { const secret = "plaintext-bind-secret" f := ldapFixture(t, strings.Replace(cliLDAPConfiguration, n8n.CredentialBlankingValue, secret, 1)) @@ -380,7 +450,7 @@ func TestLDAPAPIErrorsExplainLicenseScopesAndAvailability(t *testing.T) { }{ {name: "manage forbidden", status: http.StatusForbidden, args: []string{"ldap", "get"}, want: []string{"ldap:manage", "LDAP license", "discover --resource settingsldap"}}, {name: "sync forbidden", status: http.StatusForbidden, args: []string{"ldap", "sync", "history"}, want: []string{"ldap:sync", "LDAP license", "discover --resource settingsldap"}}, - {name: "invalid replacement", status: http.StatusBadRequest, args: []string{"ldap", "set", "--input", "-", "--yes"}, input: cliLDAPDisabledInput, want: []string{"full LDAP replacement", "all 20 fields", "response details redacted"}}, + {name: "invalid replacement", status: http.StatusBadRequest, args: []string{"ldap", "set", "--input", "-", "--yes"}, input: cliLDAPDisabledInput, want: []string{"full LDAP replacement", "all 20 core fields", "omit linkExistingAccountsByEmail", "response details redacted"}}, {name: "invalid sync", status: http.StatusBadRequest, args: []string{"ldap", "sync", "run", "--type", "dry"}, want: []string{"rejected the LDAP synchronization", "configuration"}}, {name: "not found", status: http.StatusNotFound, args: []string{"ldap", "get"}, want: []string{"LDAP endpoint", "discover --resource settingsldap"}}, {name: "unavailable", status: http.StatusServiceUnavailable, args: []string{"ldap", "sync", "history"}, want: []string{"LDAP service", "discover --resource settingsldap"}}, diff --git a/internal/n8n/ldap.go b/internal/n8n/ldap.go index 8cb8e75..f030e02 100644 --- a/internal/n8n/ldap.go +++ b/internal/n8n/ldap.go @@ -51,6 +51,8 @@ type LDAPConfiguration struct { SearchPageSize int `json:"searchPageSize"` SearchTimeout int `json:"searchTimeout"` EnforceEmailUniqueness bool `json:"enforceEmailUniqueness"` + // LinkExistingAccountsByEmail is nil when the instance predates the setting. + LinkExistingAccountsByEmail *bool `json:"linkExistingAccountsByEmail,omitempty"` } func (c *LDAPConfiguration) redactPassword() { @@ -61,27 +63,30 @@ func (c *LDAPConfiguration) redactPassword() { // UpdateLDAPConfigurationRequest is a full replacement document. Pointers // distinguish omitted required fields from valid false, zero, and empty values. +// LinkExistingAccountsByEmail is optional: when nil it is not sent and n8n keeps +// the stored value, and instances that predate the setting reject it. type UpdateLDAPConfigurationRequest struct { - LoginEnabled *bool `json:"loginEnabled"` - LoginLabel *string `json:"loginLabel"` - ConnectionURL *string `json:"connectionUrl"` - AllowUnauthorizedCerts *bool `json:"allowUnauthorizedCerts"` - ConnectionSecurity *LDAPConnectionSecurity `json:"connectionSecurity"` - ConnectionPort *int `json:"connectionPort"` - BaseDN *string `json:"baseDn"` - BindingAdminDN *string `json:"bindingAdminDn"` - BindingAdminPassword *string `json:"bindingAdminPassword"` - FirstNameAttribute *string `json:"firstNameAttribute"` - LastNameAttribute *string `json:"lastNameAttribute"` - EmailAttribute *string `json:"emailAttribute"` - LoginIDAttribute *string `json:"loginIdAttribute"` - LDAPIDAttribute *string `json:"ldapIdAttribute"` - UserFilter *string `json:"userFilter"` - SynchronizationEnabled *bool `json:"synchronizationEnabled"` - SynchronizationInterval *int `json:"synchronizationInterval"` - SearchPageSize *int `json:"searchPageSize"` - SearchTimeout *int `json:"searchTimeout"` - EnforceEmailUniqueness *bool `json:"enforceEmailUniqueness"` + LoginEnabled *bool `json:"loginEnabled"` + LoginLabel *string `json:"loginLabel"` + ConnectionURL *string `json:"connectionUrl"` + AllowUnauthorizedCerts *bool `json:"allowUnauthorizedCerts"` + ConnectionSecurity *LDAPConnectionSecurity `json:"connectionSecurity"` + ConnectionPort *int `json:"connectionPort"` + BaseDN *string `json:"baseDn"` + BindingAdminDN *string `json:"bindingAdminDn"` + BindingAdminPassword *string `json:"bindingAdminPassword"` + FirstNameAttribute *string `json:"firstNameAttribute"` + LastNameAttribute *string `json:"lastNameAttribute"` + EmailAttribute *string `json:"emailAttribute"` + LoginIDAttribute *string `json:"loginIdAttribute"` + LDAPIDAttribute *string `json:"ldapIdAttribute"` + UserFilter *string `json:"userFilter"` + SynchronizationEnabled *bool `json:"synchronizationEnabled"` + SynchronizationInterval *int `json:"synchronizationInterval"` + SearchPageSize *int `json:"searchPageSize"` + SearchTimeout *int `json:"searchTimeout"` + EnforceEmailUniqueness *bool `json:"enforceEmailUniqueness"` + LinkExistingAccountsByEmail *bool `json:"linkExistingAccountsByEmail,omitempty"` } // Validate enforces every field required by full-replacement PUT semantics. diff --git a/internal/n8n/ldap_test.go b/internal/n8n/ldap_test.go index 8784d2f..41ed422 100644 --- a/internal/n8n/ldap_test.go +++ b/internal/n8n/ldap_test.go @@ -28,7 +28,8 @@ const ldapConfigurationResponse = `{ "synchronizationInterval":60, "searchPageSize":1000, "searchTimeout":30, - "enforceEmailUniqueness":true + "enforceEmailUniqueness":true, + "linkExistingAccountsByEmail":true }` const ldapHistoryResponse = `{ @@ -85,6 +86,29 @@ func TestGetLDAPConfiguration(t *testing.T) { if !configuration.LoginEnabled || configuration.ConnectionSecurity != LDAPSecurityStartTLS || configuration.ConnectionPort != 389 || configuration.BindingAdminPassword != CredentialBlankingValue { t.Errorf("configuration = %+v", configuration) } + if configuration.LinkExistingAccountsByEmail == nil || !*configuration.LinkExistingAccountsByEmail { + t.Errorf("linkExistingAccountsByEmail = %v, want true", configuration.LinkExistingAccountsByEmail) + } +} + +func TestGetLDAPConfigurationWithoutLinkExistingAccounts(t *testing.T) { + body := strings.Replace(ldapConfigurationResponse, `, + "linkExistingAccountsByEmail":true`, "", 1) + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + configuration, err := server.client(t).GetLDAPConfiguration(context.Background()) + if err != nil { + t.Fatalf("GetLDAPConfiguration: %v", err) + } + if configuration.LinkExistingAccountsByEmail != nil { + t.Errorf("linkExistingAccountsByEmail = %v, want nil for older instance", *configuration.LinkExistingAccountsByEmail) + } + encoded, err := json.Marshal(configuration) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if strings.Contains(string(encoded), "linkExistingAccountsByEmail") { + t.Errorf("unsupported setting was re-encoded: %s", encoded) + } } func TestGetLDAPConfigurationNeverRetainsPlaintextPassword(t *testing.T) { @@ -121,6 +145,9 @@ func TestUpdateLDAPConfigurationFullReplacementAndSentinel(t *testing.T) { if len(sent) != 20 { t.Errorf("replacement has %d fields, want 20: %#v", len(sent), sent) } + if _, ok := sent["linkExistingAccountsByEmail"]; ok { + t.Errorf("omitted optional setting was sent: %#v", sent) + } if sent["loginEnabled"] != false || sent["allowUnauthorizedCerts"] != false || sent["connectionPort"] != float64(0) || sent["bindingAdminPassword"] != CredentialBlankingValue { t.Errorf("false, zero, or sentinel values were not preserved: %#v", sent) } @@ -150,6 +177,26 @@ func TestUpdateLDAPConfigurationCanClearOrReplacePassword(t *testing.T) { } } +func TestUpdateLDAPConfigurationSendsLinkExistingAccounts(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, ldapConfigurationResponse)) + request := validLDAPUpdateRequest() + request.LinkExistingAccountsByEmail = ptr(false) + if err := request.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + if _, err := server.client(t).UpdateLDAPConfiguration(context.Background(), request); err != nil { + t.Fatalf("UpdateLDAPConfiguration: %v", err) + } + _, body := server.last(t) + var sent map[string]any + if err := json.Unmarshal([]byte(body), &sent); err != nil { + t.Fatalf("body is not JSON: %v", err) + } + if len(sent) != 21 || sent["linkExistingAccountsByEmail"] != false { + t.Errorf("explicit false was not sent: %#v", sent) + } +} + func TestUpdateLDAPConfigurationValidationBeforeTransport(t *testing.T) { tests := []struct { name string