Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/n8n_ldap_get.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 4 additions & 1 deletion docs/n8n_ldap_set.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 15 additions & 3 deletions internal/cli/ldap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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" +
Expand Down Expand Up @@ -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" +
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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):
Expand Down
74 changes: 72 additions & 2 deletions internal/cli/ldap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ const cliLDAPConfiguration = `{
"synchronizationInterval":60,
"searchPageSize":1000,
"searchTimeout":30,
"enforceEmailUniqueness":true
"enforceEmailUniqueness":true,
"linkExistingAccountsByEmail":false
}`

const cliLDAPDisabledInput = `{
Expand Down Expand Up @@ -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)
Expand All @@ -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())
Expand All @@ -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))
Expand Down Expand Up @@ -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"}},
Expand Down
45 changes: 25 additions & 20 deletions internal/n8n/ldap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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.
Expand Down
49 changes: 48 additions & 1 deletion internal/n8n/ldap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ const ldapConfigurationResponse = `{
"synchronizationInterval":60,
"searchPageSize":1000,
"searchTimeout":30,
"enforceEmailUniqueness":true
"enforceEmailUniqueness":true,
"linkExistingAccountsByEmail":true
}`

const ldapHistoryResponse = `{
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
Expand Down
Loading