github.com/mad-app/mattermost-server@v5.11.1+incompatible/api4/system_test.go (about)

     1  package api4
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"os"
     8  	"testing"
     9  
    10  	"github.com/mattermost/mattermost-server/mlog"
    11  	"github.com/mattermost/mattermost-server/model"
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  func TestGetPing(t *testing.T) {
    16  	th := Setup().InitBasic()
    17  	defer th.TearDown()
    18  	Client := th.Client
    19  
    20  	goRoutineHealthThreshold := *th.App.Config().ServiceSettings.GoroutineHealthThreshold
    21  	defer func() {
    22  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.GoroutineHealthThreshold = goRoutineHealthThreshold })
    23  	}()
    24  
    25  	status, resp := Client.GetPing()
    26  	CheckNoError(t, resp)
    27  	if status != "OK" {
    28  		t.Fatal("should return OK")
    29  	}
    30  
    31  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.GoroutineHealthThreshold = 10 })
    32  	status, resp = th.SystemAdminClient.GetPing()
    33  	CheckInternalErrorStatus(t, resp)
    34  	if status != "unhealthy" {
    35  		t.Fatal("should return unhealthy")
    36  	}
    37  }
    38  
    39  func TestGetAudits(t *testing.T) {
    40  	th := Setup().InitBasic()
    41  	defer th.TearDown()
    42  	Client := th.Client
    43  
    44  	audits, resp := th.SystemAdminClient.GetAudits(0, 100, "")
    45  	CheckNoError(t, resp)
    46  
    47  	if len(audits) == 0 {
    48  		t.Fatal("should not be empty")
    49  	}
    50  
    51  	audits, resp = th.SystemAdminClient.GetAudits(0, 1, "")
    52  	CheckNoError(t, resp)
    53  
    54  	if len(audits) != 1 {
    55  		t.Fatal("should only be 1")
    56  	}
    57  
    58  	audits, resp = th.SystemAdminClient.GetAudits(1, 1, "")
    59  	CheckNoError(t, resp)
    60  
    61  	if len(audits) != 1 {
    62  		t.Fatal("should only be 1")
    63  	}
    64  
    65  	_, resp = th.SystemAdminClient.GetAudits(-1, -1, "")
    66  	CheckNoError(t, resp)
    67  
    68  	_, resp = Client.GetAudits(0, 100, "")
    69  	CheckForbiddenStatus(t, resp)
    70  
    71  	Client.Logout()
    72  	_, resp = Client.GetAudits(0, 100, "")
    73  	CheckUnauthorizedStatus(t, resp)
    74  }
    75  
    76  func TestEmailTest(t *testing.T) {
    77  	th := Setup().InitBasic()
    78  	defer th.TearDown()
    79  	Client := th.Client
    80  
    81  	config := model.Config{
    82  		ServiceSettings: model.ServiceSettings{
    83  			SiteURL: model.NewString(""),
    84  		},
    85  		EmailSettings: model.EmailSettings{
    86  			SMTPServer:             model.NewString(""),
    87  			SMTPPort:               model.NewString(""),
    88  			SMTPPassword:           model.NewString(""),
    89  			FeedbackName:           model.NewString(""),
    90  			FeedbackEmail:          model.NewString(""),
    91  			ReplyToAddress:         model.NewString(""),
    92  			SendEmailNotifications: model.NewBool(false),
    93  		},
    94  	}
    95  
    96  	t.Run("as system user", func(t *testing.T) {
    97  		_, resp := Client.TestEmail(&config)
    98  		CheckForbiddenStatus(t, resp)
    99  	})
   100  
   101  	t.Run("as system admin", func(t *testing.T) {
   102  		_, resp := th.SystemAdminClient.TestEmail(&config)
   103  		CheckErrorMessage(t, resp, "api.admin.test_email.missing_server")
   104  		CheckBadRequestStatus(t, resp)
   105  
   106  		inbucket_host := os.Getenv("CI_INBUCKET_HOST")
   107  		if inbucket_host == "" {
   108  			inbucket_host = "dockerhost"
   109  		}
   110  
   111  		inbucket_port := os.Getenv("CI_INBUCKET_PORT")
   112  		if inbucket_port == "" {
   113  			inbucket_port = "9000"
   114  		}
   115  
   116  		*config.EmailSettings.SMTPServer = inbucket_host
   117  		*config.EmailSettings.SMTPPort = inbucket_port
   118  		_, resp = th.SystemAdminClient.TestEmail(&config)
   119  		CheckOKStatus(t, resp)
   120  	})
   121  
   122  	t.Run("as restricted system admin", func(t *testing.T) {
   123  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
   124  
   125  		_, resp := th.SystemAdminClient.TestEmail(&config)
   126  		CheckForbiddenStatus(t, resp)
   127  	})
   128  }
   129  
   130  func TestDatabaseRecycle(t *testing.T) {
   131  	th := Setup().InitBasic()
   132  	defer th.TearDown()
   133  	Client := th.Client
   134  
   135  	t.Run("as system user", func(t *testing.T) {
   136  		_, resp := Client.DatabaseRecycle()
   137  		CheckForbiddenStatus(t, resp)
   138  	})
   139  
   140  	t.Run("as system admin", func(t *testing.T) {
   141  		_, resp := th.SystemAdminClient.DatabaseRecycle()
   142  		CheckNoError(t, resp)
   143  	})
   144  
   145  	t.Run("as restricted system admin", func(t *testing.T) {
   146  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
   147  
   148  		_, resp := th.SystemAdminClient.DatabaseRecycle()
   149  		CheckForbiddenStatus(t, resp)
   150  	})
   151  }
   152  
   153  func TestInvalidateCaches(t *testing.T) {
   154  	th := Setup().InitBasic()
   155  	defer th.TearDown()
   156  	Client := th.Client
   157  
   158  	t.Run("as system user", func(t *testing.T) {
   159  		ok, resp := Client.InvalidateCaches()
   160  		CheckForbiddenStatus(t, resp)
   161  		if ok {
   162  			t.Fatal("should not clean the cache due no permission.")
   163  		}
   164  	})
   165  
   166  	t.Run("as system admin", func(t *testing.T) {
   167  		ok, resp := th.SystemAdminClient.InvalidateCaches()
   168  		CheckNoError(t, resp)
   169  		if !ok {
   170  			t.Fatal("should clean the cache")
   171  		}
   172  	})
   173  
   174  	t.Run("as restricted system admin", func(t *testing.T) {
   175  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
   176  
   177  		ok, resp := th.SystemAdminClient.InvalidateCaches()
   178  		CheckForbiddenStatus(t, resp)
   179  		if ok {
   180  			t.Fatal("should not clean the cache due no permission.")
   181  		}
   182  	})
   183  }
   184  
   185  func TestGetLogs(t *testing.T) {
   186  	th := Setup().InitBasic()
   187  	defer th.TearDown()
   188  	Client := th.Client
   189  
   190  	for i := 0; i < 20; i++ {
   191  		mlog.Info(fmt.Sprint(i))
   192  	}
   193  
   194  	logs, resp := th.SystemAdminClient.GetLogs(0, 10)
   195  	CheckNoError(t, resp)
   196  
   197  	if len(logs) != 10 {
   198  		t.Log(len(logs))
   199  		t.Fatal("wrong length")
   200  	}
   201  
   202  	logs, resp = th.SystemAdminClient.GetLogs(1, 10)
   203  	CheckNoError(t, resp)
   204  
   205  	if len(logs) != 10 {
   206  		t.Log(len(logs))
   207  		t.Fatal("wrong length")
   208  	}
   209  
   210  	logs, resp = th.SystemAdminClient.GetLogs(-1, -1)
   211  	CheckNoError(t, resp)
   212  
   213  	if len(logs) == 0 {
   214  		t.Fatal("should not be empty")
   215  	}
   216  
   217  	_, resp = Client.GetLogs(0, 10)
   218  	CheckForbiddenStatus(t, resp)
   219  
   220  	Client.Logout()
   221  	_, resp = Client.GetLogs(0, 10)
   222  	CheckUnauthorizedStatus(t, resp)
   223  }
   224  
   225  func TestPostLog(t *testing.T) {
   226  	th := Setup().InitBasic()
   227  	defer th.TearDown()
   228  	Client := th.Client
   229  
   230  	enableDev := *th.App.Config().ServiceSettings.EnableDeveloper
   231  	defer func() {
   232  		*th.App.Config().ServiceSettings.EnableDeveloper = enableDev
   233  	}()
   234  	*th.App.Config().ServiceSettings.EnableDeveloper = true
   235  
   236  	message := make(map[string]string)
   237  	message["level"] = "ERROR"
   238  	message["message"] = "this is a test"
   239  
   240  	_, resp := Client.PostLog(message)
   241  	CheckNoError(t, resp)
   242  
   243  	Client.Logout()
   244  
   245  	_, resp = Client.PostLog(message)
   246  	CheckNoError(t, resp)
   247  
   248  	*th.App.Config().ServiceSettings.EnableDeveloper = false
   249  
   250  	_, resp = Client.PostLog(message)
   251  	CheckForbiddenStatus(t, resp)
   252  
   253  	logMessage, resp := th.SystemAdminClient.PostLog(message)
   254  	CheckNoError(t, resp)
   255  	if len(logMessage) == 0 {
   256  		t.Fatal("should return the log message")
   257  	}
   258  }
   259  
   260  func TestGetAnalyticsOld(t *testing.T) {
   261  	th := Setup().InitBasic()
   262  	defer th.TearDown()
   263  	Client := th.Client
   264  
   265  	rows, resp := Client.GetAnalyticsOld("", "")
   266  	CheckForbiddenStatus(t, resp)
   267  	if rows != nil {
   268  		t.Fatal("should be nil")
   269  	}
   270  
   271  	rows, resp = th.SystemAdminClient.GetAnalyticsOld("", "")
   272  	CheckNoError(t, resp)
   273  
   274  	found := false
   275  	found2 := false
   276  	for _, row := range rows {
   277  		if row.Name == "unique_user_count" {
   278  			found = true
   279  		} else if row.Name == "inactive_user_count" {
   280  			found2 = true
   281  			assert.True(t, row.Value >= 0)
   282  		}
   283  	}
   284  
   285  	assert.True(t, found, "should return unique user count")
   286  	assert.True(t, found2, "should return inactive user count")
   287  
   288  	_, resp = th.SystemAdminClient.GetAnalyticsOld("post_counts_day", "")
   289  	CheckNoError(t, resp)
   290  
   291  	_, resp = th.SystemAdminClient.GetAnalyticsOld("user_counts_with_posts_day", "")
   292  	CheckNoError(t, resp)
   293  
   294  	_, resp = th.SystemAdminClient.GetAnalyticsOld("extra_counts", "")
   295  	CheckNoError(t, resp)
   296  
   297  	rows, resp = th.SystemAdminClient.GetAnalyticsOld("", th.BasicTeam.Id)
   298  	CheckNoError(t, resp)
   299  
   300  	for _, row := range rows {
   301  		if row.Name == "inactive_user_count" {
   302  			assert.Equal(t, float64(-1), row.Value, "inactive user count should be -1 when team specified")
   303  		}
   304  	}
   305  
   306  	rows2, resp2 := th.SystemAdminClient.GetAnalyticsOld("standard", "")
   307  	CheckNoError(t, resp2)
   308  	assert.Equal(t, "total_websocket_connections", rows2[5].Name)
   309  	assert.Equal(t, float64(0), rows2[5].Value)
   310  
   311  	WebSocketClient, err := th.CreateWebSocketClient()
   312  	if err != nil {
   313  		t.Fatal(err)
   314  	}
   315  
   316  	rows2, resp2 = th.SystemAdminClient.GetAnalyticsOld("standard", "")
   317  	CheckNoError(t, resp2)
   318  	assert.Equal(t, "total_websocket_connections", rows2[5].Name)
   319  	assert.Equal(t, float64(1), rows2[5].Value)
   320  
   321  	WebSocketClient.Close()
   322  
   323  	rows2, resp2 = th.SystemAdminClient.GetAnalyticsOld("standard", "")
   324  	CheckNoError(t, resp2)
   325  	assert.Equal(t, "total_websocket_connections", rows2[5].Name)
   326  	assert.Equal(t, float64(0), rows2[5].Value)
   327  
   328  	Client.Logout()
   329  	_, resp = Client.GetAnalyticsOld("", th.BasicTeam.Id)
   330  	CheckUnauthorizedStatus(t, resp)
   331  }
   332  
   333  func TestS3TestConnection(t *testing.T) {
   334  	th := Setup().InitBasic()
   335  	defer th.TearDown()
   336  	Client := th.Client
   337  
   338  	s3Host := os.Getenv("CI_MINIO_HOST")
   339  	if s3Host == "" {
   340  		s3Host = "dockerhost"
   341  	}
   342  
   343  	s3Port := os.Getenv("CI_MINIO_PORT")
   344  	if s3Port == "" {
   345  		s3Port = "9001"
   346  	}
   347  
   348  	s3Endpoint := fmt.Sprintf("%s:%s", s3Host, s3Port)
   349  	config := model.Config{
   350  		FileSettings: model.FileSettings{
   351  			DriverName:              model.NewString(model.IMAGE_DRIVER_S3),
   352  			AmazonS3AccessKeyId:     model.NewString(model.MINIO_ACCESS_KEY),
   353  			AmazonS3SecretAccessKey: model.NewString(model.MINIO_SECRET_KEY),
   354  			AmazonS3Bucket:          model.NewString(""),
   355  			AmazonS3Endpoint:        model.NewString(s3Endpoint),
   356  			AmazonS3Region:          model.NewString(""),
   357  			AmazonS3SSL:             model.NewBool(false),
   358  		},
   359  	}
   360  
   361  	t.Run("as system user", func(t *testing.T) {
   362  		_, resp := Client.TestS3Connection(&config)
   363  		CheckForbiddenStatus(t, resp)
   364  	})
   365  
   366  	t.Run("as system admin", func(t *testing.T) {
   367  		_, resp := th.SystemAdminClient.TestS3Connection(&config)
   368  		CheckBadRequestStatus(t, resp)
   369  		if resp.Error.Message != "S3 Bucket is required" {
   370  			t.Fatal("should return error - missing s3 bucket")
   371  		}
   372  
   373  		// If this fails, check the test configuration to ensure minio is setup with the
   374  		// `mattermost-test` bucket defined by model.MINIO_BUCKET.
   375  		*config.FileSettings.AmazonS3Bucket = model.MINIO_BUCKET
   376  		*config.FileSettings.AmazonS3Region = "us-east-1"
   377  		_, resp = th.SystemAdminClient.TestS3Connection(&config)
   378  		CheckOKStatus(t, resp)
   379  
   380  		config.FileSettings.AmazonS3Region = model.NewString("")
   381  		_, resp = th.SystemAdminClient.TestS3Connection(&config)
   382  		CheckOKStatus(t, resp)
   383  
   384  		config.FileSettings.AmazonS3Bucket = model.NewString("Wrong_bucket")
   385  		_, resp = th.SystemAdminClient.TestS3Connection(&config)
   386  		CheckInternalErrorStatus(t, resp)
   387  		assert.Equal(t, "Unable to create bucket.", resp.Error.Message)
   388  
   389  		*config.FileSettings.AmazonS3Bucket = "shouldcreatenewbucket"
   390  		_, resp = th.SystemAdminClient.TestS3Connection(&config)
   391  		CheckOKStatus(t, resp)
   392  	})
   393  
   394  	t.Run("as restricted system admin", func(t *testing.T) {
   395  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
   396  
   397  		_, resp := th.SystemAdminClient.TestS3Connection(&config)
   398  		CheckForbiddenStatus(t, resp)
   399  	})
   400  
   401  }
   402  
   403  func TestSupportedTimezones(t *testing.T) {
   404  	th := Setup().InitBasic()
   405  	defer th.TearDown()
   406  	Client := th.Client
   407  
   408  	supportedTimezonesFromConfig := th.App.Timezones.GetSupported()
   409  	supportedTimezones, resp := Client.GetSupportedTimezone()
   410  
   411  	CheckNoError(t, resp)
   412  	assert.Equal(t, supportedTimezonesFromConfig, supportedTimezones)
   413  }
   414  
   415  func TestRedirectLocation(t *testing.T) {
   416  	expected := "https://mattermost.com/wp-content/themes/mattermostv2/img/logo-light.svg"
   417  
   418  	testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
   419  		res.Header().Set("Location", expected)
   420  		res.WriteHeader(http.StatusFound)
   421  		res.Write([]byte("body"))
   422  	}))
   423  	defer func() { testServer.Close() }()
   424  
   425  	mockBitlyLink := testServer.URL
   426  
   427  	th := Setup().InitBasic()
   428  	defer th.TearDown()
   429  	Client := th.Client
   430  	enableLinkPreviews := *th.App.Config().ServiceSettings.EnableLinkPreviews
   431  	defer func() {
   432  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = enableLinkPreviews })
   433  	}()
   434  
   435  	*th.App.Config().ServiceSettings.EnableLinkPreviews = true
   436  	*th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections = "127.0.0.1"
   437  
   438  	_, resp := th.SystemAdminClient.GetRedirectLocation("https://mattermost.com/", "")
   439  	CheckNoError(t, resp)
   440  
   441  	_, resp = th.SystemAdminClient.GetRedirectLocation("", "")
   442  	CheckBadRequestStatus(t, resp)
   443  
   444  	actual, resp := th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
   445  	CheckNoError(t, resp)
   446  	assert.Equal(t, expected, actual)
   447  
   448  	// Check cached value
   449  	actual, resp = th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
   450  	CheckNoError(t, resp)
   451  	assert.Equal(t, expected, actual)
   452  
   453  	*th.App.Config().ServiceSettings.EnableLinkPreviews = false
   454  	actual, resp = th.SystemAdminClient.GetRedirectLocation("https://mattermost.com/", "")
   455  	CheckNoError(t, resp)
   456  	assert.Equal(t, actual, "")
   457  
   458  	actual, resp = th.SystemAdminClient.GetRedirectLocation("", "")
   459  	CheckNoError(t, resp)
   460  	assert.Equal(t, actual, "")
   461  
   462  	actual, resp = th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
   463  	CheckNoError(t, resp)
   464  	assert.Equal(t, actual, "")
   465  
   466  	Client.Logout()
   467  	_, resp = Client.GetRedirectLocation("", "")
   468  	CheckUnauthorizedStatus(t, resp)
   469  }