github.com/mattermosttest/mattermost-server/v5@v5.0.0-20200917143240-9dfa12e121f9/model/config_test.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package model
     5  
     6  import (
     7  	"fmt"
     8  	"reflect"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  func TestConfigDefaults(t *testing.T) {
    16  	t.Parallel()
    17  
    18  	t.Run("somewhere nil when uninitialized", func(t *testing.T) {
    19  		c := Config{}
    20  		require.False(t, checkNowhereNil(t, "config", c))
    21  	})
    22  
    23  	t.Run("nowhere nil when initialized", func(t *testing.T) {
    24  		c := Config{}
    25  		c.SetDefaults()
    26  		require.True(t, checkNowhereNil(t, "config", c))
    27  	})
    28  
    29  	t.Run("nowhere nil when partially initialized", func(t *testing.T) {
    30  		var recursivelyUninitialize func(*Config, string, reflect.Value)
    31  		recursivelyUninitialize = func(config *Config, name string, v reflect.Value) {
    32  			if v.Type().Kind() == reflect.Ptr {
    33  				// Set every pointer we find in the tree to nil
    34  				v.Set(reflect.Zero(v.Type()))
    35  				require.True(t, v.IsNil())
    36  
    37  				// SetDefaults on the root config should make it non-nil, otherwise
    38  				// it means that SetDefaults isn't being called recursively in
    39  				// all cases.
    40  				config.SetDefaults()
    41  				if assert.False(t, v.IsNil(), "%s should be non-nil after SetDefaults()", name) {
    42  					recursivelyUninitialize(config, fmt.Sprintf("(*%s)", name), v.Elem())
    43  				}
    44  
    45  			} else if v.Type().Kind() == reflect.Struct {
    46  				for i := 0; i < v.NumField(); i++ {
    47  					recursivelyUninitialize(config, fmt.Sprintf("%s.%s", name, v.Type().Field(i).Name), v.Field(i))
    48  				}
    49  			}
    50  		}
    51  
    52  		c := Config{}
    53  		c.SetDefaults()
    54  		recursivelyUninitialize(&c, "config", reflect.ValueOf(&c).Elem())
    55  	})
    56  }
    57  
    58  func TestConfigEmptySiteName(t *testing.T) {
    59  	c1 := Config{
    60  		TeamSettings: TeamSettings{
    61  			SiteName: NewString(""),
    62  		},
    63  	}
    64  	c1.SetDefaults()
    65  
    66  	require.Equal(t, *c1.TeamSettings.SiteName, TEAM_SETTINGS_DEFAULT_SITE_NAME)
    67  }
    68  
    69  func TestConfigEnableDeveloper(t *testing.T) {
    70  	testCases := []struct {
    71  		Description     string
    72  		EnableDeveloper *bool
    73  		ExpectedSiteURL string
    74  	}{
    75  		{"enable developer is true", NewBool(true), SERVICE_SETTINGS_DEFAULT_SITE_URL},
    76  		{"enable developer is false", NewBool(false), ""},
    77  		{"enable developer is nil", nil, ""},
    78  	}
    79  
    80  	for _, testCase := range testCases {
    81  		t.Run(testCase.Description, func(t *testing.T) {
    82  			c1 := Config{
    83  				ServiceSettings: ServiceSettings{
    84  					EnableDeveloper: testCase.EnableDeveloper,
    85  				},
    86  			}
    87  			c1.SetDefaults()
    88  
    89  			require.Equal(t, testCase.ExpectedSiteURL, *c1.ServiceSettings.SiteURL)
    90  		})
    91  	}
    92  }
    93  
    94  func TestConfigDefaultFileSettingsDirectory(t *testing.T) {
    95  	c1 := Config{}
    96  	c1.SetDefaults()
    97  
    98  	require.Equal(t, *c1.FileSettings.Directory, "./data/")
    99  }
   100  
   101  func TestConfigDefaultEmailNotificationContentsType(t *testing.T) {
   102  	c1 := Config{}
   103  	c1.SetDefaults()
   104  
   105  	require.Equal(t, *c1.EmailSettings.EmailNotificationContentsType, EMAIL_NOTIFICATION_CONTENTS_FULL)
   106  }
   107  
   108  func TestConfigDefaultFileSettingsS3SSE(t *testing.T) {
   109  	c1 := Config{}
   110  	c1.SetDefaults()
   111  
   112  	require.False(t, *c1.FileSettings.AmazonS3SSE)
   113  }
   114  
   115  func TestConfigDefaultSignatureAlgorithm(t *testing.T) {
   116  	c1 := Config{}
   117  	c1.SetDefaults()
   118  
   119  	require.Equal(t, *c1.SamlSettings.SignatureAlgorithm, SAML_SETTINGS_DEFAULT_SIGNATURE_ALGORITHM)
   120  	require.Equal(t, *c1.SamlSettings.CanonicalAlgorithm, SAML_SETTINGS_DEFAULT_CANONICAL_ALGORITHM)
   121  }
   122  
   123  func TestConfigOverwriteSignatureAlgorithm(t *testing.T) {
   124  	const testAlgorithm = "FakeAlgorithm"
   125  	c1 := Config{
   126  		SamlSettings: SamlSettings{
   127  			CanonicalAlgorithm: NewString(testAlgorithm),
   128  			SignatureAlgorithm: NewString(testAlgorithm),
   129  		},
   130  	}
   131  
   132  	c1.SetDefaults()
   133  
   134  	require.Equal(t, *c1.SamlSettings.SignatureAlgorithm, testAlgorithm)
   135  	require.Equal(t, *c1.SamlSettings.CanonicalAlgorithm, testAlgorithm)
   136  }
   137  
   138  func TestConfigIsValidDefaultAlgorithms(t *testing.T) {
   139  	c1 := Config{}
   140  	c1.SetDefaults()
   141  
   142  	*c1.SamlSettings.Enable = true
   143  	*c1.SamlSettings.Verify = false
   144  	*c1.SamlSettings.Encrypt = false
   145  
   146  	*c1.SamlSettings.IdpUrl = "http://test.url.com"
   147  	*c1.SamlSettings.IdpDescriptorUrl = "http://test.url.com"
   148  	*c1.SamlSettings.IdpCertificateFile = "certificatefile"
   149  	*c1.SamlSettings.ServiceProviderIdentifier = "http://test.url.com"
   150  	*c1.SamlSettings.EmailAttribute = "Email"
   151  	*c1.SamlSettings.UsernameAttribute = "Username"
   152  
   153  	err := c1.SamlSettings.isValid()
   154  	require.Nil(t, err)
   155  }
   156  
   157  func TestConfigServiceProviderDefault(t *testing.T) {
   158  	c1 := &Config{
   159  		SamlSettings: *&SamlSettings{
   160  			Enable:             NewBool(true),
   161  			Verify:             NewBool(false),
   162  			Encrypt:            NewBool(false),
   163  			IdpUrl:             NewString("http://test.url.com"),
   164  			IdpDescriptorUrl:   NewString("http://test2.url.com"),
   165  			IdpCertificateFile: NewString("certificatefile"),
   166  			EmailAttribute:     NewString("Email"),
   167  			UsernameAttribute:  NewString("Username"),
   168  		},
   169  	}
   170  
   171  	c1.SetDefaults()
   172  	assert.Equal(t, *c1.SamlSettings.ServiceProviderIdentifier, *c1.SamlSettings.IdpDescriptorUrl)
   173  
   174  	err := c1.SamlSettings.isValid()
   175  	require.Nil(t, err)
   176  }
   177  
   178  func TestConfigIsValidFakeAlgorithm(t *testing.T) {
   179  	c1 := Config{}
   180  	c1.SetDefaults()
   181  
   182  	*c1.SamlSettings.Enable = true
   183  	*c1.SamlSettings.Verify = false
   184  	*c1.SamlSettings.Encrypt = false
   185  
   186  	*c1.SamlSettings.IdpUrl = "http://test.url.com"
   187  	*c1.SamlSettings.IdpDescriptorUrl = "http://test.url.com"
   188  	*c1.SamlSettings.IdpMetadataUrl = "http://test.url.com"
   189  	*c1.SamlSettings.IdpCertificateFile = "certificatefile"
   190  	*c1.SamlSettings.ServiceProviderIdentifier = "http://test.url.com"
   191  	*c1.SamlSettings.EmailAttribute = "Email"
   192  	*c1.SamlSettings.UsernameAttribute = "Username"
   193  
   194  	temp := *c1.SamlSettings.CanonicalAlgorithm
   195  	*c1.SamlSettings.CanonicalAlgorithm = "Fake Algorithm"
   196  	err := c1.SamlSettings.isValid()
   197  	require.NotNil(t, err)
   198  
   199  	require.Equal(t, "model.config.is_valid.saml_canonical_algorithm.app_error", err.Message)
   200  	*c1.SamlSettings.CanonicalAlgorithm = temp
   201  
   202  	*c1.SamlSettings.SignatureAlgorithm = "Fake Algorithm"
   203  	err = c1.SamlSettings.isValid()
   204  	require.NotNil(t, err)
   205  
   206  	require.Equal(t, "model.config.is_valid.saml_signature_algorithm.app_error", err.Message)
   207  }
   208  
   209  func TestConfigOverwriteGuestSettings(t *testing.T) {
   210  	const attribute = "FakeAttributeName"
   211  	c1 := Config{
   212  		SamlSettings: SamlSettings{
   213  			GuestAttribute: NewString(attribute),
   214  		},
   215  	}
   216  
   217  	c1.SetDefaults()
   218  
   219  	require.Equal(t, *c1.SamlSettings.GuestAttribute, attribute)
   220  }
   221  
   222  func TestConfigOverwriteAdminSettings(t *testing.T) {
   223  	const attribute = "FakeAttributeName"
   224  	c1 := Config{
   225  		SamlSettings: SamlSettings{
   226  			AdminAttribute: NewString(attribute),
   227  		},
   228  	}
   229  
   230  	c1.SetDefaults()
   231  
   232  	require.Equal(t, *c1.SamlSettings.AdminAttribute, attribute)
   233  }
   234  
   235  func TestConfigDefaultServiceSettingsExperimentalGroupUnreadChannels(t *testing.T) {
   236  	c1 := Config{}
   237  	c1.SetDefaults()
   238  
   239  	require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GROUP_UNREAD_CHANNELS_DISABLED)
   240  
   241  	// This setting was briefly a boolean, so ensure that those values still work as expected
   242  	c1 = Config{
   243  		ServiceSettings: ServiceSettings{
   244  			ExperimentalGroupUnreadChannels: NewString("1"),
   245  		},
   246  	}
   247  	c1.SetDefaults()
   248  
   249  	require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GROUP_UNREAD_CHANNELS_DEFAULT_ON)
   250  
   251  	c1 = Config{
   252  		ServiceSettings: ServiceSettings{
   253  			ExperimentalGroupUnreadChannels: NewString("0"),
   254  		},
   255  	}
   256  	c1.SetDefaults()
   257  
   258  	require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GROUP_UNREAD_CHANNELS_DISABLED)
   259  }
   260  
   261  func TestConfigDefaultNPSPluginState(t *testing.T) {
   262  	t.Run("should enable NPS plugin by default", func(t *testing.T) {
   263  		c1 := Config{}
   264  		c1.SetDefaults()
   265  
   266  		assert.True(t, c1.PluginSettings.PluginStates["com.mattermost.nps"].Enable)
   267  	})
   268  
   269  	t.Run("should enable NPS plugin if diagnostics are enabled", func(t *testing.T) {
   270  		c1 := Config{
   271  			LogSettings: LogSettings{
   272  				EnableDiagnostics: NewBool(true),
   273  			},
   274  		}
   275  
   276  		c1.SetDefaults()
   277  
   278  		assert.True(t, c1.PluginSettings.PluginStates["com.mattermost.nps"].Enable)
   279  	})
   280  
   281  	t.Run("should not enable NPS plugin if diagnostics are disabled", func(t *testing.T) {
   282  		c1 := Config{
   283  			LogSettings: LogSettings{
   284  				EnableDiagnostics: NewBool(false),
   285  			},
   286  		}
   287  
   288  		c1.SetDefaults()
   289  
   290  		assert.False(t, c1.PluginSettings.PluginStates["com.mattermost.nps"].Enable)
   291  	})
   292  
   293  	t.Run("should not re-enable NPS plugin after it has been disabled", func(t *testing.T) {
   294  		c1 := Config{
   295  			PluginSettings: PluginSettings{
   296  				PluginStates: map[string]*PluginState{
   297  					"com.mattermost.nps": {
   298  						Enable: false,
   299  					},
   300  				},
   301  			},
   302  		}
   303  
   304  		c1.SetDefaults()
   305  
   306  		assert.False(t, c1.PluginSettings.PluginStates["com.mattermost.nps"].Enable)
   307  	})
   308  }
   309  
   310  func TestTeamSettingsIsValidSiteNameEmpty(t *testing.T) {
   311  	c1 := Config{}
   312  	c1.SetDefaults()
   313  	c1.TeamSettings.SiteName = NewString("")
   314  
   315  	// should not fail if ts.SiteName is not set, defaults are used
   316  	require.Nil(t, c1.TeamSettings.isValid())
   317  }
   318  
   319  func TestMessageExportSettingsIsValidEnableExportNotSet(t *testing.T) {
   320  	fs := &FileSettings{}
   321  	mes := &MessageExportSettings{}
   322  
   323  	// should fail fast because mes.EnableExport is not set
   324  	require.Error(t, mes.isValid(*fs))
   325  }
   326  
   327  func TestMessageExportSettingsIsValidEnableExportFalse(t *testing.T) {
   328  	fs := &FileSettings{}
   329  	mes := &MessageExportSettings{
   330  		EnableExport: NewBool(false),
   331  	}
   332  
   333  	// should fail fast because message export isn't enabled
   334  	require.Nil(t, mes.isValid(*fs))
   335  }
   336  
   337  func TestMessageExportSettingsIsValidExportFromTimestampInvalid(t *testing.T) {
   338  	fs := &FileSettings{}
   339  	mes := &MessageExportSettings{
   340  		EnableExport: NewBool(true),
   341  	}
   342  
   343  	// should fail fast because export from timestamp isn't set
   344  	require.Error(t, mes.isValid(*fs))
   345  
   346  	mes.ExportFromTimestamp = NewInt64(-1)
   347  
   348  	// should fail fast because export from timestamp isn't valid
   349  	require.Error(t, mes.isValid(*fs))
   350  
   351  	mes.ExportFromTimestamp = NewInt64(GetMillis() + 10000)
   352  
   353  	// should fail fast because export from timestamp is greater than current time
   354  	require.Error(t, mes.isValid(*fs))
   355  }
   356  
   357  func TestMessageExportSettingsIsValidDailyRunTimeInvalid(t *testing.T) {
   358  	fs := &FileSettings{}
   359  	mes := &MessageExportSettings{
   360  		EnableExport:        NewBool(true),
   361  		ExportFromTimestamp: NewInt64(0),
   362  	}
   363  
   364  	// should fail fast because daily runtime isn't set
   365  	require.Error(t, mes.isValid(*fs))
   366  
   367  	mes.DailyRunTime = NewString("33:33:33")
   368  
   369  	// should fail fast because daily runtime is invalid format
   370  	require.Error(t, mes.isValid(*fs))
   371  }
   372  
   373  func TestMessageExportSettingsIsValidBatchSizeInvalid(t *testing.T) {
   374  	fs := &FileSettings{
   375  		DriverName: NewString("foo"), // bypass file location check
   376  	}
   377  	mes := &MessageExportSettings{
   378  		EnableExport:        NewBool(true),
   379  		ExportFromTimestamp: NewInt64(0),
   380  		DailyRunTime:        NewString("15:04"),
   381  	}
   382  
   383  	// should fail fast because batch size isn't set
   384  	require.Error(t, mes.isValid(*fs))
   385  }
   386  
   387  func TestMessageExportSettingsIsValidExportFormatInvalid(t *testing.T) {
   388  	fs := &FileSettings{
   389  		DriverName: NewString("foo"), // bypass file location check
   390  	}
   391  	mes := &MessageExportSettings{
   392  		EnableExport:        NewBool(true),
   393  		ExportFromTimestamp: NewInt64(0),
   394  		DailyRunTime:        NewString("15:04"),
   395  		BatchSize:           NewInt(100),
   396  	}
   397  
   398  	// should fail fast because export format isn't set
   399  	require.Error(t, mes.isValid(*fs))
   400  }
   401  
   402  func TestMessageExportSettingsIsValidGlobalRelayEmailAddressInvalid(t *testing.T) {
   403  	fs := &FileSettings{
   404  		DriverName: NewString("foo"), // bypass file location check
   405  	}
   406  	mes := &MessageExportSettings{
   407  		EnableExport:        NewBool(true),
   408  		ExportFormat:        NewString(COMPLIANCE_EXPORT_TYPE_GLOBALRELAY),
   409  		ExportFromTimestamp: NewInt64(0),
   410  		DailyRunTime:        NewString("15:04"),
   411  		BatchSize:           NewInt(100),
   412  	}
   413  
   414  	// should fail fast because global relay email address isn't set
   415  	require.Error(t, mes.isValid(*fs))
   416  }
   417  
   418  func TestMessageExportSettingsIsValidActiance(t *testing.T) {
   419  	fs := &FileSettings{
   420  		DriverName: NewString("foo"), // bypass file location check
   421  	}
   422  	mes := &MessageExportSettings{
   423  		EnableExport:        NewBool(true),
   424  		ExportFormat:        NewString(COMPLIANCE_EXPORT_TYPE_ACTIANCE),
   425  		ExportFromTimestamp: NewInt64(0),
   426  		DailyRunTime:        NewString("15:04"),
   427  		BatchSize:           NewInt(100),
   428  	}
   429  
   430  	// should pass because everything is valid
   431  	require.Nil(t, mes.isValid(*fs))
   432  }
   433  
   434  func TestMessageExportSettingsIsValidGlobalRelaySettingsMissing(t *testing.T) {
   435  	fs := &FileSettings{
   436  		DriverName: NewString("foo"), // bypass file location check
   437  	}
   438  	mes := &MessageExportSettings{
   439  		EnableExport:        NewBool(true),
   440  		ExportFormat:        NewString(COMPLIANCE_EXPORT_TYPE_GLOBALRELAY),
   441  		ExportFromTimestamp: NewInt64(0),
   442  		DailyRunTime:        NewString("15:04"),
   443  		BatchSize:           NewInt(100),
   444  	}
   445  
   446  	// should fail because globalrelay settings are missing
   447  	require.Error(t, mes.isValid(*fs))
   448  }
   449  
   450  func TestMessageExportSettingsIsValidGlobalRelaySettingsInvalidCustomerType(t *testing.T) {
   451  	fs := &FileSettings{
   452  		DriverName: NewString("foo"), // bypass file location check
   453  	}
   454  	mes := &MessageExportSettings{
   455  		EnableExport:        NewBool(true),
   456  		ExportFormat:        NewString(COMPLIANCE_EXPORT_TYPE_GLOBALRELAY),
   457  		ExportFromTimestamp: NewInt64(0),
   458  		DailyRunTime:        NewString("15:04"),
   459  		BatchSize:           NewInt(100),
   460  		GlobalRelaySettings: &GlobalRelayMessageExportSettings{
   461  			CustomerType: NewString("Invalid"),
   462  			EmailAddress: NewString("valid@mattermost.com"),
   463  			SmtpUsername: NewString("SomeUsername"),
   464  			SmtpPassword: NewString("SomePassword"),
   465  		},
   466  	}
   467  
   468  	// should fail because customer type is invalid
   469  	require.Error(t, mes.isValid(*fs))
   470  }
   471  
   472  // func TestMessageExportSettingsIsValidGlobalRelaySettingsInvalidEmailAddress(t *testing.T) {
   473  func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) {
   474  	fs := &FileSettings{
   475  		DriverName: NewString("foo"), // bypass file location check
   476  	}
   477  	tests := []struct {
   478  		name    string
   479  		value   *GlobalRelayMessageExportSettings
   480  		success bool
   481  	}{
   482  		{
   483  			"Invalid email address",
   484  			&GlobalRelayMessageExportSettings{
   485  				CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A9),
   486  				EmailAddress: NewString("invalidEmailAddress"),
   487  				SmtpUsername: NewString("SomeUsername"),
   488  				SmtpPassword: NewString("SomePassword"),
   489  			},
   490  			false,
   491  		},
   492  		{
   493  			"Missing smtp username",
   494  			&GlobalRelayMessageExportSettings{
   495  				CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A10),
   496  				EmailAddress: NewString("valid@mattermost.com"),
   497  				SmtpPassword: NewString("SomePassword"),
   498  			},
   499  			false,
   500  		},
   501  		{
   502  			"Invalid smtp username",
   503  			&GlobalRelayMessageExportSettings{
   504  				CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A10),
   505  				EmailAddress: NewString("valid@mattermost.com"),
   506  				SmtpUsername: NewString(""),
   507  				SmtpPassword: NewString("SomePassword"),
   508  			},
   509  			false,
   510  		},
   511  		{
   512  			"Invalid smtp password",
   513  			&GlobalRelayMessageExportSettings{
   514  				CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A10),
   515  				EmailAddress: NewString("valid@mattermost.com"),
   516  				SmtpUsername: NewString("SomeUsername"),
   517  				SmtpPassword: NewString(""),
   518  			},
   519  			false,
   520  		},
   521  		{
   522  			"Valid data",
   523  			&GlobalRelayMessageExportSettings{
   524  				CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A9),
   525  				EmailAddress: NewString("valid@mattermost.com"),
   526  				SmtpUsername: NewString("SomeUsername"),
   527  				SmtpPassword: NewString("SomePassword"),
   528  			},
   529  			true,
   530  		},
   531  	}
   532  
   533  	for _, tt := range tests {
   534  		t.Run(tt.name, func(t *testing.T) {
   535  			mes := &MessageExportSettings{
   536  				EnableExport:        NewBool(true),
   537  				ExportFormat:        NewString(COMPLIANCE_EXPORT_TYPE_GLOBALRELAY),
   538  				ExportFromTimestamp: NewInt64(0),
   539  				DailyRunTime:        NewString("15:04"),
   540  				BatchSize:           NewInt(100),
   541  				GlobalRelaySettings: tt.value,
   542  			}
   543  
   544  			if tt.success {
   545  				require.Nil(t, mes.isValid(*fs))
   546  			} else {
   547  				require.Error(t, mes.isValid(*fs))
   548  			}
   549  		})
   550  	}
   551  }
   552  
   553  func TestMessageExportSetDefaults(t *testing.T) {
   554  	mes := &MessageExportSettings{}
   555  	mes.SetDefaults()
   556  
   557  	require.False(t, *mes.EnableExport)
   558  	require.Equal(t, "01:00", *mes.DailyRunTime)
   559  	require.Equal(t, int64(0), *mes.ExportFromTimestamp)
   560  	require.Equal(t, 10000, *mes.BatchSize)
   561  	require.Equal(t, COMPLIANCE_EXPORT_TYPE_ACTIANCE, *mes.ExportFormat)
   562  }
   563  
   564  func TestMessageExportSetDefaultsExportEnabledExportFromTimestampNil(t *testing.T) {
   565  	// Test retained as protection against regression of MM-13185
   566  	mes := &MessageExportSettings{
   567  		EnableExport: NewBool(true),
   568  	}
   569  	mes.SetDefaults()
   570  
   571  	require.True(t, *mes.EnableExport)
   572  	require.Equal(t, "01:00", *mes.DailyRunTime)
   573  	require.Equal(t, int64(0), *mes.ExportFromTimestamp)
   574  	require.True(t, *mes.ExportFromTimestamp <= GetMillis())
   575  	require.Equal(t, 10000, *mes.BatchSize)
   576  }
   577  
   578  func TestMessageExportSetDefaultsExportEnabledExportFromTimestampZero(t *testing.T) {
   579  	// Test retained as protection against regression of MM-13185
   580  	mes := &MessageExportSettings{
   581  		EnableExport:        NewBool(true),
   582  		ExportFromTimestamp: NewInt64(0),
   583  	}
   584  	mes.SetDefaults()
   585  
   586  	require.True(t, *mes.EnableExport)
   587  	require.Equal(t, "01:00", *mes.DailyRunTime)
   588  	require.Equal(t, int64(0), *mes.ExportFromTimestamp)
   589  	require.True(t, *mes.ExportFromTimestamp <= GetMillis())
   590  	require.Equal(t, 10000, *mes.BatchSize)
   591  }
   592  
   593  func TestMessageExportSetDefaultsExportEnabledExportFromTimestampNonZero(t *testing.T) {
   594  	mes := &MessageExportSettings{
   595  		EnableExport:        NewBool(true),
   596  		ExportFromTimestamp: NewInt64(12345),
   597  	}
   598  	mes.SetDefaults()
   599  
   600  	require.True(t, *mes.EnableExport)
   601  	require.Equal(t, "01:00", *mes.DailyRunTime)
   602  	require.Equal(t, int64(12345), *mes.ExportFromTimestamp)
   603  	require.Equal(t, 10000, *mes.BatchSize)
   604  }
   605  
   606  func TestMessageExportSetDefaultsExportDisabledExportFromTimestampNil(t *testing.T) {
   607  	mes := &MessageExportSettings{
   608  		EnableExport: NewBool(false),
   609  	}
   610  	mes.SetDefaults()
   611  
   612  	require.False(t, *mes.EnableExport)
   613  	require.Equal(t, "01:00", *mes.DailyRunTime)
   614  	require.Equal(t, int64(0), *mes.ExportFromTimestamp)
   615  	require.Equal(t, 10000, *mes.BatchSize)
   616  }
   617  
   618  func TestMessageExportSetDefaultsExportDisabledExportFromTimestampZero(t *testing.T) {
   619  	mes := &MessageExportSettings{
   620  		EnableExport:        NewBool(false),
   621  		ExportFromTimestamp: NewInt64(0),
   622  	}
   623  	mes.SetDefaults()
   624  
   625  	require.False(t, *mes.EnableExport)
   626  	require.Equal(t, "01:00", *mes.DailyRunTime)
   627  	require.Equal(t, int64(0), *mes.ExportFromTimestamp)
   628  	require.Equal(t, 10000, *mes.BatchSize)
   629  }
   630  
   631  func TestMessageExportSetDefaultsExportDisabledExportFromTimestampNonZero(t *testing.T) {
   632  	// Test retained as protection against regression of MM-13185
   633  	mes := &MessageExportSettings{
   634  		EnableExport:        NewBool(false),
   635  		ExportFromTimestamp: NewInt64(12345),
   636  	}
   637  	mes.SetDefaults()
   638  
   639  	require.False(t, *mes.EnableExport)
   640  	require.Equal(t, "01:00", *mes.DailyRunTime)
   641  	require.Equal(t, int64(12345), *mes.ExportFromTimestamp)
   642  	require.Equal(t, 10000, *mes.BatchSize)
   643  }
   644  
   645  func TestDisplaySettingsIsValidCustomUrlSchemes(t *testing.T) {
   646  	tests := []struct {
   647  		name  string
   648  		value []string
   649  		valid bool
   650  	}{
   651  		{
   652  			name:  "empty",
   653  			value: []string{},
   654  			valid: true,
   655  		},
   656  		{
   657  			name:  "custom protocol",
   658  			value: []string{"steam"},
   659  			valid: true,
   660  		},
   661  		{
   662  			name:  "multiple custom protocols",
   663  			value: []string{"bitcoin", "rss", "redis"},
   664  			valid: true,
   665  		},
   666  		{
   667  			name:  "containing numbers",
   668  			value: []string{"ut2004", "ts3server", "h323"},
   669  			valid: true,
   670  		},
   671  		{
   672  			name:  "containing period",
   673  			value: []string{"iris.beep"},
   674  			valid: true,
   675  		},
   676  		{
   677  			name:  "containing hyphen",
   678  			value: []string{"ms-excel"},
   679  			valid: true,
   680  		},
   681  		{
   682  			name:  "containing plus",
   683  			value: []string{"coap+tcp", "coap+ws"},
   684  			valid: true,
   685  		},
   686  		{
   687  			name:  "starting with number",
   688  			value: []string{"4four"},
   689  			valid: false,
   690  		},
   691  		{
   692  			name:  "starting with period",
   693  			value: []string{"data", ".dot"},
   694  			valid: false,
   695  		},
   696  		{
   697  			name:  "starting with hyphen",
   698  			value: []string{"-hyphen", "dns"},
   699  			valid: false,
   700  		},
   701  		{
   702  			name:  "invalid symbols",
   703  			value: []string{"!!fun!!"},
   704  			valid: false,
   705  		},
   706  		{
   707  			name:  "invalid letters",
   708  			value: []string{"école"},
   709  			valid: false,
   710  		},
   711  	}
   712  	for _, test := range tests {
   713  		t.Run(test.name, func(t *testing.T) {
   714  			ds := &DisplaySettings{}
   715  			ds.SetDefaults()
   716  
   717  			ds.CustomUrlSchemes = test.value
   718  
   719  			if err := ds.isValid(); err != nil && test.valid {
   720  				t.Error("Expected CustomUrlSchemes to be valid but got error:", err)
   721  			} else if err == nil && !test.valid {
   722  				t.Error("Expected CustomUrlSchemes to be invalid but got no error")
   723  			}
   724  		})
   725  	}
   726  }
   727  
   728  func TestListenAddressIsValidated(t *testing.T) {
   729  
   730  	testValues := map[string]bool{
   731  		":8065":                true,
   732  		":9917":                true,
   733  		"0.0.0.0:9917":         true,
   734  		"[2001:db8::68]:9918":  true,
   735  		"[::1]:8065":           true,
   736  		"localhost:8065":       true,
   737  		"test.com:8065":        true,
   738  		":0":                   true,
   739  		":33147":               true,
   740  		"123:8065":             false,
   741  		"[::1]:99999":          false,
   742  		"[::1]:-1":             false,
   743  		"[::1]:8065a":          false,
   744  		"0.0.0:9917":           false,
   745  		"0.0.0.0:9917/":        false,
   746  		"0..0.0:9917/":         false,
   747  		"0.0.0222.0:9917/":     false,
   748  		"http://0.0.0.0:9917/": false,
   749  		"http://0.0.0.0:9917":  false,
   750  		"8065":                 false,
   751  		"[2001:db8::68]":       false,
   752  	}
   753  
   754  	for key, expected := range testValues {
   755  		ss := &ServiceSettings{
   756  			ListenAddress: NewString(key),
   757  		}
   758  		ss.SetDefaults(true)
   759  		if expected {
   760  			require.Nil(t, ss.isValid(), fmt.Sprintf("Got an error from '%v'.", key))
   761  		} else {
   762  			err := ss.isValid()
   763  			require.NotNil(t, err, fmt.Sprintf("Expected '%v' to throw an error.", key))
   764  			require.Equal(t, "model.config.is_valid.listen_address.app_error", err.Message)
   765  		}
   766  	}
   767  
   768  }
   769  
   770  func TestImageProxySettingsSetDefaults(t *testing.T) {
   771  	ss := ServiceSettings{
   772  		DEPRECATED_DO_NOT_USE_ImageProxyType:    NewString(IMAGE_PROXY_TYPE_ATMOS_CAMO),
   773  		DEPRECATED_DO_NOT_USE_ImageProxyURL:     NewString("http://images.example.com"),
   774  		DEPRECATED_DO_NOT_USE_ImageProxyOptions: NewString("1234abcd"),
   775  	}
   776  
   777  	t.Run("default, no old settings", func(t *testing.T) {
   778  		ips := ImageProxySettings{}
   779  		ips.SetDefaults(ServiceSettings{})
   780  
   781  		assert.Equal(t, false, *ips.Enable)
   782  		assert.Equal(t, IMAGE_PROXY_TYPE_LOCAL, *ips.ImageProxyType)
   783  		assert.Equal(t, "", *ips.RemoteImageProxyURL)
   784  		assert.Equal(t, "", *ips.RemoteImageProxyOptions)
   785  	})
   786  
   787  	t.Run("default, old settings", func(t *testing.T) {
   788  		ips := ImageProxySettings{}
   789  		ips.SetDefaults(ss)
   790  
   791  		assert.Equal(t, true, *ips.Enable)
   792  		assert.Equal(t, *ss.DEPRECATED_DO_NOT_USE_ImageProxyType, *ips.ImageProxyType)
   793  		assert.Equal(t, *ss.DEPRECATED_DO_NOT_USE_ImageProxyURL, *ips.RemoteImageProxyURL)
   794  		assert.Equal(t, *ss.DEPRECATED_DO_NOT_USE_ImageProxyOptions, *ips.RemoteImageProxyOptions)
   795  	})
   796  
   797  	t.Run("not default, old settings", func(t *testing.T) {
   798  		url := "http://images.mattermost.com"
   799  		options := "aaaaaaaa"
   800  
   801  		ips := ImageProxySettings{
   802  			Enable:                  NewBool(false),
   803  			ImageProxyType:          NewString(IMAGE_PROXY_TYPE_LOCAL),
   804  			RemoteImageProxyURL:     &url,
   805  			RemoteImageProxyOptions: &options,
   806  		}
   807  		ips.SetDefaults(ss)
   808  
   809  		assert.Equal(t, false, *ips.Enable)
   810  		assert.Equal(t, IMAGE_PROXY_TYPE_LOCAL, *ips.ImageProxyType)
   811  		assert.Equal(t, url, *ips.RemoteImageProxyURL)
   812  		assert.Equal(t, options, *ips.RemoteImageProxyOptions)
   813  	})
   814  }
   815  
   816  func TestImageProxySettingsIsValid(t *testing.T) {
   817  	for _, test := range []struct {
   818  		Name                    string
   819  		Enable                  bool
   820  		ImageProxyType          string
   821  		RemoteImageProxyURL     string
   822  		RemoteImageProxyOptions string
   823  		ExpectError             bool
   824  	}{
   825  		{
   826  			Name:        "disabled",
   827  			Enable:      false,
   828  			ExpectError: false,
   829  		},
   830  		{
   831  			Name:                    "disabled with bad values",
   832  			Enable:                  false,
   833  			ImageProxyType:          "garbage",
   834  			RemoteImageProxyURL:     "garbage",
   835  			RemoteImageProxyOptions: "garbage",
   836  			ExpectError:             false,
   837  		},
   838  		{
   839  			Name:           "missing type",
   840  			Enable:         true,
   841  			ImageProxyType: "",
   842  			ExpectError:    true,
   843  		},
   844  		{
   845  			Name:                    "local",
   846  			Enable:                  true,
   847  			ImageProxyType:          "local",
   848  			RemoteImageProxyURL:     "garbage",
   849  			RemoteImageProxyOptions: "garbage",
   850  			ExpectError:             false,
   851  		},
   852  		{
   853  			Name:                    "atmos/camo",
   854  			Enable:                  true,
   855  			ImageProxyType:          IMAGE_PROXY_TYPE_ATMOS_CAMO,
   856  			RemoteImageProxyURL:     "someurl",
   857  			RemoteImageProxyOptions: "someoptions",
   858  			ExpectError:             false,
   859  		},
   860  		{
   861  			Name:                    "atmos/camo, missing url",
   862  			Enable:                  true,
   863  			ImageProxyType:          IMAGE_PROXY_TYPE_ATMOS_CAMO,
   864  			RemoteImageProxyURL:     "",
   865  			RemoteImageProxyOptions: "garbage",
   866  			ExpectError:             true,
   867  		},
   868  		{
   869  			Name:                    "atmos/camo, missing options",
   870  			Enable:                  true,
   871  			ImageProxyType:          IMAGE_PROXY_TYPE_ATMOS_CAMO,
   872  			RemoteImageProxyURL:     "someurl",
   873  			RemoteImageProxyOptions: "",
   874  			ExpectError:             true,
   875  		},
   876  	} {
   877  		t.Run(test.Name, func(t *testing.T) {
   878  			ips := &ImageProxySettings{
   879  				Enable:                  &test.Enable,
   880  				ImageProxyType:          &test.ImageProxyType,
   881  				RemoteImageProxyURL:     &test.RemoteImageProxyURL,
   882  				RemoteImageProxyOptions: &test.RemoteImageProxyOptions,
   883  			}
   884  
   885  			err := ips.isValid()
   886  			if test.ExpectError {
   887  				assert.NotNil(t, err)
   888  			} else {
   889  				assert.Nil(t, err)
   890  			}
   891  		})
   892  	}
   893  }
   894  
   895  func TestLdapSettingsIsValid(t *testing.T) {
   896  	for _, test := range []struct {
   897  		Name         string
   898  		LdapSettings LdapSettings
   899  		ExpectError  bool
   900  	}{
   901  		{
   902  			Name: "disabled",
   903  			LdapSettings: LdapSettings{
   904  				Enable: NewBool(false),
   905  			},
   906  			ExpectError: false,
   907  		},
   908  		{
   909  			Name: "missing server",
   910  			LdapSettings: LdapSettings{
   911  				Enable:            NewBool(true),
   912  				LdapServer:        NewString(""),
   913  				BaseDN:            NewString("basedn"),
   914  				EmailAttribute:    NewString("email"),
   915  				UsernameAttribute: NewString("username"),
   916  				IdAttribute:       NewString("id"),
   917  				LoginIdAttribute:  NewString("loginid"),
   918  				UserFilter:        NewString(""),
   919  			},
   920  			ExpectError: true,
   921  		},
   922  		{
   923  			Name: "empty user filter",
   924  			LdapSettings: LdapSettings{
   925  				Enable:            NewBool(true),
   926  				LdapServer:        NewString("server"),
   927  				BaseDN:            NewString("basedn"),
   928  				EmailAttribute:    NewString("email"),
   929  				UsernameAttribute: NewString("username"),
   930  				IdAttribute:       NewString("id"),
   931  				LoginIdAttribute:  NewString("loginid"),
   932  				UserFilter:        NewString(""),
   933  			},
   934  			ExpectError: false,
   935  		},
   936  		{
   937  			Name: "valid user filter #1",
   938  			LdapSettings: LdapSettings{
   939  				Enable:            NewBool(true),
   940  				LdapServer:        NewString("server"),
   941  				BaseDN:            NewString("basedn"),
   942  				EmailAttribute:    NewString("email"),
   943  				UsernameAttribute: NewString("username"),
   944  				IdAttribute:       NewString("id"),
   945  				LoginIdAttribute:  NewString("loginid"),
   946  				UserFilter:        NewString("(property=value)"),
   947  			},
   948  			ExpectError: false,
   949  		},
   950  		{
   951  			Name: "invalid user filter #1",
   952  			LdapSettings: LdapSettings{
   953  				Enable:            NewBool(true),
   954  				LdapServer:        NewString("server"),
   955  				BaseDN:            NewString("basedn"),
   956  				EmailAttribute:    NewString("email"),
   957  				UsernameAttribute: NewString("username"),
   958  				IdAttribute:       NewString("id"),
   959  				LoginIdAttribute:  NewString("loginid"),
   960  				UserFilter:        NewString("("),
   961  			},
   962  			ExpectError: true,
   963  		},
   964  		{
   965  			Name: "invalid user filter #2",
   966  			LdapSettings: LdapSettings{
   967  				Enable:            NewBool(true),
   968  				LdapServer:        NewString("server"),
   969  				BaseDN:            NewString("basedn"),
   970  				EmailAttribute:    NewString("email"),
   971  				UsernameAttribute: NewString("username"),
   972  				IdAttribute:       NewString("id"),
   973  				LoginIdAttribute:  NewString("loginid"),
   974  				UserFilter:        NewString("()"),
   975  			},
   976  			ExpectError: true,
   977  		},
   978  		{
   979  			Name: "valid user filter #2",
   980  			LdapSettings: LdapSettings{
   981  				Enable:            NewBool(true),
   982  				LdapServer:        NewString("server"),
   983  				BaseDN:            NewString("basedn"),
   984  				EmailAttribute:    NewString("email"),
   985  				UsernameAttribute: NewString("username"),
   986  				IdAttribute:       NewString("id"),
   987  				LoginIdAttribute:  NewString("loginid"),
   988  				UserFilter:        NewString("(&(property=value)(otherthing=othervalue))"),
   989  			},
   990  			ExpectError: false,
   991  		},
   992  		{
   993  			Name: "valid user filter #3",
   994  			LdapSettings: LdapSettings{
   995  				Enable:            NewBool(true),
   996  				LdapServer:        NewString("server"),
   997  				BaseDN:            NewString("basedn"),
   998  				EmailAttribute:    NewString("email"),
   999  				UsernameAttribute: NewString("username"),
  1000  				IdAttribute:       NewString("id"),
  1001  				LoginIdAttribute:  NewString("loginid"),
  1002  				UserFilter:        NewString("(&(property=value)(|(otherthing=othervalue)(other=thing)))"),
  1003  			},
  1004  			ExpectError: false,
  1005  		},
  1006  		{
  1007  			Name: "invalid user filter #3",
  1008  			LdapSettings: LdapSettings{
  1009  				Enable:            NewBool(true),
  1010  				LdapServer:        NewString("server"),
  1011  				BaseDN:            NewString("basedn"),
  1012  				EmailAttribute:    NewString("email"),
  1013  				UsernameAttribute: NewString("username"),
  1014  				IdAttribute:       NewString("id"),
  1015  				LoginIdAttribute:  NewString("loginid"),
  1016  				UserFilter:        NewString("(&(property=value)(|(otherthing=othervalue)(other=thing))"),
  1017  			},
  1018  			ExpectError: true,
  1019  		},
  1020  		{
  1021  			Name: "invalid user filter #4",
  1022  			LdapSettings: LdapSettings{
  1023  				Enable:            NewBool(true),
  1024  				LdapServer:        NewString("server"),
  1025  				BaseDN:            NewString("basedn"),
  1026  				EmailAttribute:    NewString("email"),
  1027  				UsernameAttribute: NewString("username"),
  1028  				IdAttribute:       NewString("id"),
  1029  				LoginIdAttribute:  NewString("loginid"),
  1030  				UserFilter:        NewString("(&(property=value)((otherthing=othervalue)(other=thing)))"),
  1031  			},
  1032  			ExpectError: true,
  1033  		},
  1034  
  1035  		{
  1036  			Name: "valid guest filter #1",
  1037  			LdapSettings: LdapSettings{
  1038  				Enable:            NewBool(true),
  1039  				LdapServer:        NewString("server"),
  1040  				BaseDN:            NewString("basedn"),
  1041  				EmailAttribute:    NewString("email"),
  1042  				UsernameAttribute: NewString("username"),
  1043  				IdAttribute:       NewString("id"),
  1044  				LoginIdAttribute:  NewString("loginid"),
  1045  				GuestFilter:       NewString("(property=value)"),
  1046  			},
  1047  			ExpectError: false,
  1048  		},
  1049  		{
  1050  			Name: "invalid guest filter #1",
  1051  			LdapSettings: LdapSettings{
  1052  				Enable:            NewBool(true),
  1053  				LdapServer:        NewString("server"),
  1054  				BaseDN:            NewString("basedn"),
  1055  				EmailAttribute:    NewString("email"),
  1056  				UsernameAttribute: NewString("username"),
  1057  				IdAttribute:       NewString("id"),
  1058  				LoginIdAttribute:  NewString("loginid"),
  1059  				GuestFilter:       NewString("("),
  1060  			},
  1061  			ExpectError: true,
  1062  		},
  1063  		{
  1064  			Name: "invalid guest filter #2",
  1065  			LdapSettings: LdapSettings{
  1066  				Enable:            NewBool(true),
  1067  				LdapServer:        NewString("server"),
  1068  				BaseDN:            NewString("basedn"),
  1069  				EmailAttribute:    NewString("email"),
  1070  				UsernameAttribute: NewString("username"),
  1071  				IdAttribute:       NewString("id"),
  1072  				LoginIdAttribute:  NewString("loginid"),
  1073  				GuestFilter:       NewString("()"),
  1074  			},
  1075  			ExpectError: true,
  1076  		},
  1077  		{
  1078  			Name: "valid guest filter #2",
  1079  			LdapSettings: LdapSettings{
  1080  				Enable:            NewBool(true),
  1081  				LdapServer:        NewString("server"),
  1082  				BaseDN:            NewString("basedn"),
  1083  				EmailAttribute:    NewString("email"),
  1084  				UsernameAttribute: NewString("username"),
  1085  				IdAttribute:       NewString("id"),
  1086  				LoginIdAttribute:  NewString("loginid"),
  1087  				GuestFilter:       NewString("(&(property=value)(otherthing=othervalue))"),
  1088  			},
  1089  			ExpectError: false,
  1090  		},
  1091  		{
  1092  			Name: "valid guest filter #3",
  1093  			LdapSettings: LdapSettings{
  1094  				Enable:            NewBool(true),
  1095  				LdapServer:        NewString("server"),
  1096  				BaseDN:            NewString("basedn"),
  1097  				EmailAttribute:    NewString("email"),
  1098  				UsernameAttribute: NewString("username"),
  1099  				IdAttribute:       NewString("id"),
  1100  				LoginIdAttribute:  NewString("loginid"),
  1101  				GuestFilter:       NewString("(&(property=value)(|(otherthing=othervalue)(other=thing)))"),
  1102  			},
  1103  			ExpectError: false,
  1104  		},
  1105  		{
  1106  			Name: "invalid guest filter #3",
  1107  			LdapSettings: LdapSettings{
  1108  				Enable:            NewBool(true),
  1109  				LdapServer:        NewString("server"),
  1110  				BaseDN:            NewString("basedn"),
  1111  				EmailAttribute:    NewString("email"),
  1112  				UsernameAttribute: NewString("username"),
  1113  				IdAttribute:       NewString("id"),
  1114  				LoginIdAttribute:  NewString("loginid"),
  1115  				GuestFilter:       NewString("(&(property=value)(|(otherthing=othervalue)(other=thing))"),
  1116  			},
  1117  			ExpectError: true,
  1118  		},
  1119  		{
  1120  			Name: "invalid guest filter #4",
  1121  			LdapSettings: LdapSettings{
  1122  				Enable:            NewBool(true),
  1123  				LdapServer:        NewString("server"),
  1124  				BaseDN:            NewString("basedn"),
  1125  				EmailAttribute:    NewString("email"),
  1126  				UsernameAttribute: NewString("username"),
  1127  				IdAttribute:       NewString("id"),
  1128  				LoginIdAttribute:  NewString("loginid"),
  1129  				GuestFilter:       NewString("(&(property=value)((otherthing=othervalue)(other=thing)))"),
  1130  			},
  1131  			ExpectError: true,
  1132  		},
  1133  
  1134  		{
  1135  			Name: "valid Admin filter #1",
  1136  			LdapSettings: LdapSettings{
  1137  				Enable:            NewBool(true),
  1138  				LdapServer:        NewString("server"),
  1139  				BaseDN:            NewString("basedn"),
  1140  				EmailAttribute:    NewString("email"),
  1141  				UsernameAttribute: NewString("username"),
  1142  				IdAttribute:       NewString("id"),
  1143  				LoginIdAttribute:  NewString("loginid"),
  1144  				AdminFilter:       NewString("(property=value)"),
  1145  			},
  1146  			ExpectError: false,
  1147  		},
  1148  		{
  1149  			Name: "invalid Admin filter #1",
  1150  			LdapSettings: LdapSettings{
  1151  				Enable:            NewBool(true),
  1152  				LdapServer:        NewString("server"),
  1153  				BaseDN:            NewString("basedn"),
  1154  				EmailAttribute:    NewString("email"),
  1155  				UsernameAttribute: NewString("username"),
  1156  				IdAttribute:       NewString("id"),
  1157  				LoginIdAttribute:  NewString("loginid"),
  1158  				AdminFilter:       NewString("("),
  1159  			},
  1160  			ExpectError: true,
  1161  		},
  1162  		{
  1163  			Name: "invalid Admin filter #2",
  1164  			LdapSettings: LdapSettings{
  1165  				Enable:            NewBool(true),
  1166  				LdapServer:        NewString("server"),
  1167  				BaseDN:            NewString("basedn"),
  1168  				EmailAttribute:    NewString("email"),
  1169  				UsernameAttribute: NewString("username"),
  1170  				IdAttribute:       NewString("id"),
  1171  				LoginIdAttribute:  NewString("loginid"),
  1172  				AdminFilter:       NewString("()"),
  1173  			},
  1174  			ExpectError: true,
  1175  		},
  1176  		{
  1177  			Name: "valid Admin filter #2",
  1178  			LdapSettings: LdapSettings{
  1179  				Enable:            NewBool(true),
  1180  				LdapServer:        NewString("server"),
  1181  				BaseDN:            NewString("basedn"),
  1182  				EmailAttribute:    NewString("email"),
  1183  				UsernameAttribute: NewString("username"),
  1184  				IdAttribute:       NewString("id"),
  1185  				LoginIdAttribute:  NewString("loginid"),
  1186  				AdminFilter:       NewString("(&(property=value)(otherthing=othervalue))"),
  1187  			},
  1188  			ExpectError: false,
  1189  		},
  1190  		{
  1191  			Name: "valid Admin filter #3",
  1192  			LdapSettings: LdapSettings{
  1193  				Enable:            NewBool(true),
  1194  				LdapServer:        NewString("server"),
  1195  				BaseDN:            NewString("basedn"),
  1196  				EmailAttribute:    NewString("email"),
  1197  				UsernameAttribute: NewString("username"),
  1198  				IdAttribute:       NewString("id"),
  1199  				LoginIdAttribute:  NewString("loginid"),
  1200  				AdminFilter:       NewString("(&(property=value)(|(otherthing=othervalue)(other=thing)))"),
  1201  			},
  1202  			ExpectError: false,
  1203  		},
  1204  		{
  1205  			Name: "invalid Admin filter #3",
  1206  			LdapSettings: LdapSettings{
  1207  				Enable:            NewBool(true),
  1208  				LdapServer:        NewString("server"),
  1209  				BaseDN:            NewString("basedn"),
  1210  				EmailAttribute:    NewString("email"),
  1211  				UsernameAttribute: NewString("username"),
  1212  				IdAttribute:       NewString("id"),
  1213  				LoginIdAttribute:  NewString("loginid"),
  1214  				AdminFilter:       NewString("(&(property=value)(|(otherthing=othervalue)(other=thing))"),
  1215  			},
  1216  			ExpectError: true,
  1217  		},
  1218  		{
  1219  			Name: "invalid Admin filter #4",
  1220  			LdapSettings: LdapSettings{
  1221  				Enable:            NewBool(true),
  1222  				LdapServer:        NewString("server"),
  1223  				BaseDN:            NewString("basedn"),
  1224  				EmailAttribute:    NewString("email"),
  1225  				UsernameAttribute: NewString("username"),
  1226  				IdAttribute:       NewString("id"),
  1227  				LoginIdAttribute:  NewString("loginid"),
  1228  				AdminFilter:       NewString("(&(property=value)((otherthing=othervalue)(other=thing)))"),
  1229  			},
  1230  			ExpectError: true,
  1231  		},
  1232  	} {
  1233  		t.Run(test.Name, func(t *testing.T) {
  1234  			test.LdapSettings.SetDefaults()
  1235  
  1236  			err := test.LdapSettings.isValid()
  1237  			if test.ExpectError {
  1238  				assert.NotNil(t, err)
  1239  			} else {
  1240  				assert.Nil(t, err)
  1241  			}
  1242  		})
  1243  	}
  1244  }
  1245  
  1246  func TestConfigSanitize(t *testing.T) {
  1247  	c := Config{}
  1248  	c.SetDefaults()
  1249  
  1250  	*c.LdapSettings.BindPassword = "foo"
  1251  	*c.FileSettings.AmazonS3SecretAccessKey = "bar"
  1252  	*c.EmailSettings.SMTPPassword = "baz"
  1253  	*c.GitLabSettings.Secret = "bingo"
  1254  	c.SqlSettings.DataSourceReplicas = []string{"stuff"}
  1255  	c.SqlSettings.DataSourceSearchReplicas = []string{"stuff"}
  1256  
  1257  	c.Sanitize()
  1258  
  1259  	assert.Equal(t, FAKE_SETTING, *c.LdapSettings.BindPassword)
  1260  	assert.Equal(t, FAKE_SETTING, *c.FileSettings.PublicLinkSalt)
  1261  	assert.Equal(t, FAKE_SETTING, *c.FileSettings.AmazonS3SecretAccessKey)
  1262  	assert.Equal(t, FAKE_SETTING, *c.EmailSettings.SMTPPassword)
  1263  	assert.Equal(t, FAKE_SETTING, *c.GitLabSettings.Secret)
  1264  	assert.Equal(t, FAKE_SETTING, *c.SqlSettings.DataSource)
  1265  	assert.Equal(t, FAKE_SETTING, *c.SqlSettings.AtRestEncryptKey)
  1266  	assert.Equal(t, FAKE_SETTING, *c.ElasticsearchSettings.Password)
  1267  	assert.Equal(t, FAKE_SETTING, c.SqlSettings.DataSourceReplicas[0])
  1268  	assert.Equal(t, FAKE_SETTING, c.SqlSettings.DataSourceSearchReplicas[0])
  1269  }
  1270  
  1271  func TestConfigMarketplaceDefaults(t *testing.T) {
  1272  	t.Parallel()
  1273  
  1274  	t.Run("no marketplace url", func(t *testing.T) {
  1275  		c := Config{}
  1276  		c.SetDefaults()
  1277  
  1278  		require.True(t, *c.PluginSettings.EnableMarketplace)
  1279  		require.Equal(t, PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL, *c.PluginSettings.MarketplaceUrl)
  1280  	})
  1281  
  1282  	t.Run("old marketplace url", func(t *testing.T) {
  1283  		c := Config{}
  1284  		c.SetDefaults()
  1285  
  1286  		*c.PluginSettings.MarketplaceUrl = PLUGIN_SETTINGS_OLD_MARKETPLACE_URL
  1287  		c.SetDefaults()
  1288  
  1289  		require.True(t, *c.PluginSettings.EnableMarketplace)
  1290  		require.Equal(t, PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL, *c.PluginSettings.MarketplaceUrl)
  1291  	})
  1292  
  1293  	t.Run("custom marketplace url", func(t *testing.T) {
  1294  		c := Config{}
  1295  		c.SetDefaults()
  1296  
  1297  		*c.PluginSettings.MarketplaceUrl = "https://marketplace.example.com"
  1298  		c.SetDefaults()
  1299  
  1300  		require.True(t, *c.PluginSettings.EnableMarketplace)
  1301  		require.Equal(t, "https://marketplace.example.com", *c.PluginSettings.MarketplaceUrl)
  1302  	})
  1303  }