From fd853e74a6e81ae3ea642ec24dd2994dd3498727 Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Thu, 12 Aug 2021 11:49:16 +0200 Subject: [PATCH] [MM-37755] Idiomatic naming (SMTP, TLS, TCP, XML, CSS, HTML, HTTP) (#18103) --- api4/apitestlib.go | 2 +- api4/file_test.go | 2 +- api4/image_test.go | 14 +++---- api4/upload_test.go | 6 +-- api4/user.go | 2 +- api4/user_test.go | 20 ++++----- app/app.go | 2 +- app/download.go | 4 +- app/opengraph.go | 4 +- app/opengraph_test.go | 4 +- app/permissions_migrations.go | 6 +-- app/plugin.go | 2 +- app/plugin_requests.go | 2 +- app/post_metadata_test.go | 2 +- app/post_test.go | 8 ++-- app/server.go | 16 +++---- cmd/mattermost/commands/config_test.go | 12 +++--- cmd/mattermost/commands/utils_test.go | 4 +- config/utils.go | 4 +- einterfaces/metrics.go | 4 +- einterfaces/mocks/MetricsInterface.go | 8 ++-- model/access.go | 2 +- model/authorize.go | 4 +- model/client4.go | 34 +++++++-------- model/command.go | 2 +- model/config.go | 46 ++++++++++---------- model/config_test.go | 22 +++++----- model/manifest.go | 6 +-- model/oauth.go | 6 +-- model/outgoing_webhook.go | 2 +- model/permission.go | 12 +++--- model/role.go | 8 ++-- model/utils.go | 2 +- model/utils_test.go | 4 +- services/telemetry/mocks/ServerIface.go | 4 +- services/telemetry/telemetry.go | 12 +++--- services/telemetry/telemetry_test.go | 2 +- shared/mlog/levels.go | 2 +- shared/mlog/logr.go | 4 +- shared/mlog/tcp.go | 56 ++++++++++++------------- shared/mlog/tcp_test.go | 2 +- tests/test-config.json | 4 +- utils/subpath_test.go | 50 +++++++++++----------- web/handlers.go | 6 +-- web/handlers_test.go | 6 +-- web/oauth_test.go | 20 ++++----- 46 files changed, 223 insertions(+), 223 deletions(-) diff --git a/api4/apitestlib.go b/api4/apitestlib.go index 62e356b4a3..450c123a59 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -469,7 +469,7 @@ func (th *TestHelper) CreateLocalClient(socketPath string) *model.Client4 { return &model.Client4{ ApiUrl: "http://_" + model.ApiUrlSuffix, - HttpClient: httpClient, + HTTPClient: httpClient, } } diff --git a/api4/file_test.go b/api4/file_test.go index 68d3ea7675..9f5b52e031 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -71,7 +71,7 @@ func testDoUploadFileRequest(t testing.TB, c *model.Client4, url string, blob [] req.Header.Set(model.HeaderAuth, c.AuthType+" "+c.AuthToken) } - resp, err := c.HttpClient.Do(req) + resp, err := c.HTTPClient.Do(req) require.NoError(t, err) require.NotNil(t, resp) defer closeBody(resp) diff --git a/api4/image_test.go b/api4/image_test.go index d1518c3891..47e479a073 100644 --- a/api4/image_test.go +++ b/api4/image_test.go @@ -22,7 +22,7 @@ func TestGetImage(t *testing.T) { defer th.TearDown() // Prevent the test client from following a redirect - th.Client.HttpClient.CheckRedirect = func(*http.Request, []*http.Request) error { + th.Client.HTTPClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } @@ -37,7 +37,7 @@ func TestGetImage(t *testing.T) { require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - resp, err := th.Client.HttpClient.Do(r) + resp, err := th.Client.HTTPClient.Do(r) require.NoError(t, err) assert.Equal(t, http.StatusFound, resp.StatusCode) assert.Equal(t, imageURL, resp.Header.Get("Location")) @@ -58,7 +58,7 @@ func TestGetImage(t *testing.T) { require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - resp, err := th.Client.HttpClient.Do(r) + resp, err := th.Client.HTTPClient.Do(r) require.NoError(t, err) assert.Equal(t, http.StatusFound, resp.StatusCode) assert.Equal(t, proxiedURL, resp.Header.Get("Location")) @@ -85,7 +85,7 @@ func TestGetImage(t *testing.T) { require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - resp, err := th.Client.HttpClient.Do(r) + resp, err := th.Client.HTTPClient.Do(r) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) @@ -98,7 +98,7 @@ func TestGetImage(t *testing.T) { require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - resp, err = th.Client.HttpClient.Do(r) + resp, err = th.Client.HTTPClient.Do(r) require.NoError(t, err) assert.Equal(t, http.StatusFound, resp.StatusCode) @@ -110,7 +110,7 @@ func TestGetImage(t *testing.T) { require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - resp, err = th.Client.HttpClient.Do(r) + resp, err = th.Client.HTTPClient.Do(r) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) @@ -119,7 +119,7 @@ func TestGetImage(t *testing.T) { require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - resp, err = th.Client.HttpClient.Do(r) + resp, err = th.Client.HTTPClient.Do(r) require.NoError(t, err) assert.Equal(t, http.StatusBadRequest, resp.StatusCode) }) diff --git a/api4/upload_test.go b/api4/upload_test.go index dc20eb19ba..8179951131 100644 --- a/api4/upload_test.go +++ b/api4/upload_test.go @@ -334,7 +334,7 @@ func TestUploadDataMultipart(t *testing.T) { require.NoError(t, err) req.Header.Set("Content-Type", contentType) req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - res, err := th.Client.HttpClient.Do(req) + res, err := th.Client.HTTPClient.Do(req) require.NoError(t, err) info := model.FileInfoFromJson(res.Body) res.Body.Close() @@ -358,7 +358,7 @@ func TestUploadDataMultipart(t *testing.T) { require.NoError(t, err) req.Header.Set("Content-Type", contentType) req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - res, err := th.Client.HttpClient.Do(req) + res, err := th.Client.HTTPClient.Do(req) require.NoError(t, err) require.Equal(t, http.StatusNoContent, res.StatusCode) require.Equal(t, int64(0), res.ContentLength) @@ -369,7 +369,7 @@ func TestUploadDataMultipart(t *testing.T) { require.NoError(t, err) req.Header.Set("Content-Type", contentType) req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) - res, err = th.Client.HttpClient.Do(req) + res, err = th.Client.HTTPClient.Do(req) require.NoError(t, err) info := model.FileInfoFromJson(res.Body) res.Body.Close() diff --git a/api4/user.go b/api4/user.go index 06753d602d..7a9c514e0c 100644 --- a/api4/user.go +++ b/api4/user.go @@ -1845,7 +1845,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAuditWithUserId(user.Id, "success") - if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXml { + if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXML { c.App.AttachSessionCookies(c.AppContext, w, r) } diff --git a/api4/user_test.go b/api4/user_test.go index 9bf042edbf..8275dcd9aa 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -3425,7 +3425,7 @@ func TestLoginCookies(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.Client.HttpHeader[model.HeaderRequestedWith] = model.HeaderRequestedWithXml + th.Client.HTTPHeader[model.HeaderRequestedWith] = model.HeaderRequestedWithXML user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password) @@ -3463,7 +3463,7 @@ func TestLoginCookies(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.Client.HttpHeader[model.HeaderRequestedWith] = model.HeaderRequestedWithXml + th.Client.HTTPHeader[model.HeaderRequestedWith] = model.HeaderRequestedWithXML testCases := []struct { Description string @@ -3514,20 +3514,20 @@ func TestCBALogin(t *testing.T) { t.Run("missing cert subject", func(t *testing.T) { th.Client.Logout() - th.Client.HttpHeader["X-SSL-Client-Cert"] = "valid_cert_fake" + th.Client.HTTPHeader["X-SSL-Client-Cert"] = "valid_cert_fake" _, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password) CheckBadRequestStatus(t, resp) }) t.Run("emails mismatch", func(t *testing.T) { th.Client.Logout() - th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=mis_match" + th.BasicUser.Email + th.Client.HTTPHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=mis_match" + th.BasicUser.Email _, resp := th.Client.Login(th.BasicUser.Email, "") CheckUnauthorizedStatus(t, resp) }) t.Run("successful cba login", func(t *testing.T) { - th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email + th.Client.HTTPHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email user, resp := th.Client.Login(th.BasicUser.Email, "") CheckNoError(t, resp) require.NotNil(t, user) @@ -3543,7 +3543,7 @@ func TestCBALogin(t *testing.T) { botUser, resp := th.SystemAdminClient.GetUser(bot.UserId, "") CheckNoError(t, resp) - th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + botUser.Email + th.Client.HTTPHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + botUser.Email _, resp = th.Client.Login(botUser.Email, "") CheckErrorMessage(t, resp, "api.user.login.bot_login_forbidden.app_error") @@ -3559,7 +3559,7 @@ func TestCBALogin(t *testing.T) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) - th.Client.HttpHeader["X-SSL-Client-Cert"] = "valid_cert_fake" + th.Client.HTTPHeader["X-SSL-Client-Cert"] = "valid_cert_fake" th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.ClientSideCertEnable = true @@ -3567,13 +3567,13 @@ func TestCBALogin(t *testing.T) { }) t.Run("password required", func(t *testing.T) { - th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email + th.Client.HTTPHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email _, resp := th.Client.Login(th.BasicUser.Email, "") CheckBadRequestStatus(t, resp) }) t.Run("successful cba login with password", func(t *testing.T) { - th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email + th.Client.HTTPHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password) CheckNoError(t, resp) require.NotNil(t, user) @@ -3593,7 +3593,7 @@ func TestCBALogin(t *testing.T) { CheckNoError(t, resp) require.True(t, changed) - th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + botUser.Email + th.Client.HTTPHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + botUser.Email _, resp = th.Client.Login(botUser.Email, "password") CheckErrorMessage(t, resp, "api.user.login.bot_login_forbidden.app_error") diff --git a/app/app.go b/app/app.go index b1950fc270..2b33fa10cc 100644 --- a/app/app.go +++ b/app/app.go @@ -529,7 +529,7 @@ func (a *App) Cloud() einterfaces.CloudInterface { return a.srv.Cloud } func (a *App) HTTPService() httpservice.HTTPService { - return a.srv.HTTPService + return a.srv.httpService } func (a *App) ImageProxy() *imageproxy.ImageProxy { return a.srv.ImageProxy diff --git a/app/download.go b/app/download.go index 9ab983d936..a0ed03df5b 100644 --- a/app/download.go +++ b/app/download.go @@ -27,7 +27,7 @@ func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) { } func (s *Server) downloadFromURL(downloadURL string) ([]byte, error) { - if !model.IsValidHttpUrl(downloadURL) { + if !model.IsValidHTTPUrl(downloadURL) { return nil, errors.Errorf("invalid url %s", downloadURL) } @@ -39,7 +39,7 @@ func (s *Server) downloadFromURL(downloadURL string) ([]byte, error) { return nil, errors.Errorf("insecure url not allowed %s", downloadURL) } - client := s.HTTPService.MakeClient(true) + client := s.HTTPService().MakeClient(true) client.Timeout = HTTPRequestTimeout var resp *http.Response diff --git a/app/opengraph.go b/app/opengraph.go index 3e51440249..dfa5b03e1f 100644 --- a/app/opengraph.go +++ b/app/opengraph.go @@ -36,7 +36,7 @@ func (a *App) parseOpenGraphMetadata(requestURL string, body io.Reader, contentT makeOpenGraphURLsAbsolute(og, requestURL) - openGraphDecodeHtmlEntities(og) + openGraphDecodeHTMLEntities(og) // If image proxy enabled modify open graph data to feed though proxy if toProxyURL := a.ImageProxyAdder(); toProxyURL != nil { @@ -119,7 +119,7 @@ func openGraphDataWithProxyAddedToImageURLs(ogdata *opengraph.OpenGraph, toProxy return ogdata } -func openGraphDecodeHtmlEntities(og *opengraph.OpenGraph) { +func openGraphDecodeHTMLEntities(og *opengraph.OpenGraph) { og.Title = html.UnescapeString(og.Title) og.Description = html.UnescapeString(og.Description) } diff --git a/app/opengraph_test.go b/app/opengraph_test.go index 9a597895ca..3f42f60af1 100644 --- a/app/opengraph_test.go +++ b/app/opengraph_test.go @@ -125,12 +125,12 @@ func TestMakeOpenGraphURLsAbsolute(t *testing.T) { } } -func TestOpenGraphDecodeHtmlEntities(t *testing.T) { +func TestOpenGraphDecodeHTMLEntities(t *testing.T) { og := opengraph.NewOpenGraph() og.Title = "Test's are the best.©" og.Description = "Test's are the worst.©" - openGraphDecodeHtmlEntities(og) + openGraphDecodeHTMLEntities(og) assert.Equal(t, og.Title, "Test's are the best.©") assert.Equal(t, og.Description, "Test's are the worst.©") diff --git a/app/permissions_migrations.go b/app/permissions_migrations.go index 100bab2e8a..36168b48ad 100644 --- a/app/permissions_migrations.go +++ b/app/permissions_migrations.go @@ -705,7 +705,7 @@ func (a *App) getAddEnvironmentSubsectionPermissions() (permissionsMap, error) { model.PermissionSysconsoleReadEnvironmentElasticsearch.Id, model.PermissionSysconsoleReadEnvironmentFileStorage.Id, model.PermissionSysconsoleReadEnvironmentImageProxy.Id, - model.PermissionSysconsoleReadEnvironmentSmtp.Id, + model.PermissionSysconsoleReadEnvironmentSMTP.Id, model.PermissionSysconsoleReadEnvironmentPushNotificationServer.Id, model.PermissionSysconsoleReadEnvironmentHighAvailability.Id, model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, @@ -720,7 +720,7 @@ func (a *App) getAddEnvironmentSubsectionPermissions() (permissionsMap, error) { model.PermissionSysconsoleWriteEnvironmentElasticsearch.Id, model.PermissionSysconsoleWriteEnvironmentFileStorage.Id, model.PermissionSysconsoleWriteEnvironmentImageProxy.Id, - model.PermissionSysconsoleWriteEnvironmentSmtp.Id, + model.PermissionSysconsoleWriteEnvironmentSMTP.Id, model.PermissionSysconsoleWriteEnvironmentPushNotificationServer.Id, model.PermissionSysconsoleWriteEnvironmentHighAvailability.Id, model.PermissionSysconsoleWriteEnvironmentRateLimiting.Id, @@ -908,7 +908,7 @@ func (a *App) getAddTestEmailAncillaryPermission() (permissionsMap, error) { // Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_SMTP transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PermissionSysconsoleWriteEnvironmentSmtp.Id), + On: permissionExists(model.PermissionSysconsoleWriteEnvironmentSMTP.Id), Add: []string{model.PermissionTestEmail.Id}, }) diff --git a/app/plugin.go b/app/plugin.go index c108142a6c..66671e0dbe 100644 --- a/app/plugin.go +++ b/app/plugin.go @@ -554,7 +554,7 @@ func (s *Server) getPrepackagedPlugin(pluginID, version string) (*plugin.Prepack func (s *Server) getRemoteMarketplacePlugin(pluginID, version string) (*model.BaseMarketplacePlugin, *model.AppError) { marketplaceClient, err := marketplace.NewClient( *s.Config().PluginSettings.MarketplaceUrl, - s.HTTPService, + s.HTTPService(), ) if err != nil { return nil, model.NewAppError("GetMarketplacePlugin", "app.plugin.marketplace_client.app_error", nil, err.Error(), http.StatusInternalServerError) diff --git a/app/plugin_requests.go b/app/plugin_requests.go index b6a5305829..e1086174b2 100644 --- a/app/plugin_requests.go +++ b/app/plugin_requests.go @@ -166,7 +166,7 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand } // ToDo(DSchalla) 2019/01/04: Remove after deprecation period and only allow CSRF Header (MM-13657) - if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXml && !csrfCheckPassed { + if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXML && !csrfCheckPassed { csrfErrorMessage := "CSRF Check failed for request - Please migrate your plugin to either send a CSRF Header or Form Field, XMLHttpRequest is deprecated" sid := "" userID := "" diff --git a/app/post_metadata_test.go b/app/post_metadata_test.go index 30317f432d..c16e8ceb47 100644 --- a/app/post_metadata_test.go +++ b/app/post_metadata_test.go @@ -599,7 +599,7 @@ func TestPreparePostForClientWithImageProxy(t *testing.T) { *cfg.ImageProxySettings.RemoteImageProxyOptions = "foo" }) - th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService, th.Server.Log) + th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService(), th.Server.Log) return th } diff --git a/app/post_test.go b/app/post_test.go index a695cf1af6..f0a406c142 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -473,7 +473,7 @@ func TestImageProxy(t *testing.T) { *cfg.ServiceSettings.SiteURL = "http://mymattermost.com" }) - th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService, th.Server.Log) + th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService(), th.Server.Log) for name, tc := range map[string]struct { ProxyType string @@ -688,7 +688,7 @@ func TestCreatePost(t *testing.T) { *cfg.ImageProxySettings.RemoteImageProxyOptions = "foo" }) - th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService, th.Server.Log) + th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService(), th.Server.Log) imageURL := "http://mydomain.com/myimage" proxiedImageURL := "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage" @@ -805,7 +805,7 @@ func TestPatchPost(t *testing.T) { *cfg.ImageProxySettings.RemoteImageProxyOptions = "foo" }) - th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService, th.Server.Log) + th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService(), th.Server.Log) imageURL := "http://mydomain.com/myimage" proxiedImageURL := "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage" @@ -1098,7 +1098,7 @@ func TestUpdatePost(t *testing.T) { *cfg.ImageProxySettings.RemoteImageProxyOptions = "foo" }) - th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService, th.Server.Log) + th.Server.ImageProxy = imageproxy.MakeImageProxy(th.Server, th.Server.HTTPService(), th.Server.Log) imageURL := "http://mydomain.com/myimage" proxiedImageURL := "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage" diff --git a/app/server.go b/app/server.go index cc6364b09c..488719a691 100644 --- a/app/server.go +++ b/app/server.go @@ -165,7 +165,7 @@ type Server struct { phase2PermissionsMigrationComplete bool - HTTPService httpservice.HTTPService + httpService httpservice.HTTPService ImageProxy *imageproxy.ImageProxy @@ -304,10 +304,10 @@ func NewServer(options ...Option) (*Server, error) { s.tracer = tracer } - s.HTTPService = httpservice.MakeHTTPService(s) - s.pushNotificationClient = s.HTTPService.MakeClient(true) + s.httpService = httpservice.MakeHTTPService(s) + s.pushNotificationClient = s.httpService.MakeClient(true) - s.ImageProxy = imageproxy.MakeImageProxy(s, s.HTTPService, s.Log) + s.ImageProxy = imageproxy.MakeImageProxy(s, s.HTTPService(), s.Log) if err := utils.TranslationsPreInit(); err != nil { return nil, errors.Wrapf(err, "unable to load Mattermost translation files") @@ -1237,7 +1237,7 @@ func (s *Server) Start() error { addr := *s.Config().ServiceSettings.ListenAddress if addr == "" { - if *s.Config().ServiceSettings.ConnectionSecurity == model.ConnSecurityTls { + if *s.Config().ServiceSettings.ConnectionSecurity == model.ConnSecurityTLS { addr = ":https" } else { addr = ":http" @@ -1297,7 +1297,7 @@ func (s *Server) Start() error { s.didFinishListen = make(chan struct{}) go func() { var err error - if *s.Config().ServiceSettings.ConnectionSecurity == model.ConnSecurityTls { + if *s.Config().ServiceSettings.ConnectionSecurity == model.ConnSecurityTLS { tlsConfig := &tls.Config{ PreferServerCipherSuites: true, @@ -1922,8 +1922,8 @@ func (s *Server) TelemetryId() string { return s.telemetryService.TelemetryID } -func (s *Server) HttpService() httpservice.HTTPService { - return s.HTTPService +func (s *Server) HTTPService() httpservice.HTTPService { + return s.httpService } func (s *Server) SetLog(l *mlog.Logger) { diff --git a/cmd/mattermost/commands/config_test.go b/cmd/mattermost/commands/config_test.go index 81f1ea5d84..32699a4996 100644 --- a/cmd/mattermost/commands/config_test.go +++ b/cmd/mattermost/commands/config_test.go @@ -34,8 +34,8 @@ type TestMessageExportSettings struct { type TestGlobalRelaySettings struct { Customertype string - Smtpusername string - Smtppassword string + SMTPUsername string + SMTPPassword string } type TestServiceSettings struct { @@ -327,8 +327,8 @@ func TestConfigToMap(t *testing.T) { "Exportformat": "abc", "TestGlobalRelaySettings": map[string]interface{}{ "Customertype": "abc", - "Smtpusername": "def", - "Smtppassword": "ghi", + "SMTPUsername": "def", + "SMTPPassword": "ghi", }, }, }, @@ -351,8 +351,8 @@ func TestPrintConfigValues(t *testing.T) { "Siteurl: \"abc\"\nWebsocketurl: \"def\"\nLicensedfieldlocation: \"ghi\"\n", "Sitename: \"abc\"\nMaxuserperteam: \"1\"\n", "Androidlatestversion: \"abc\"\nAndroidminversion: \"def\"\nDesktoplatestversion: \"ghi\"\n", - "Enableexport: \"true\"\nExportformat: \"abc\"\nTestGlobalRelaySettings:\n\tCustomertype: \"abc\"\n\tSmtpusername: \"def\"\n\tSmtppassword: \"ghi\"\n", - "Customertype: \"abc\"\nSmtpusername: \"def\"\nSmtppassword: \"ghi\"\n", + "Enableexport: \"true\"\nExportformat: \"abc\"\nTestGlobalRelaySettings:\n\tCustomertype: \"abc\"\n\tSMTPUsername: \"def\"\n\tSMTPPassword: \"ghi\"\n", + "Customertype: \"abc\"\nSMTPUsername: \"def\"\nSMTPPassword: \"ghi\"\n", } commands := []string{ diff --git a/cmd/mattermost/commands/utils_test.go b/cmd/mattermost/commands/utils_test.go index db7d4c1e41..0dbcb785c5 100644 --- a/cmd/mattermost/commands/utils_test.go +++ b/cmd/mattermost/commands/utils_test.go @@ -75,8 +75,8 @@ func TestStructToMap(t *testing.T) { "Exportformat": "abc", "TestGlobalRelaySettings": map[string]interface{}{ "Customertype": "abc", - "Smtpusername": "def", - "Smtppassword": "ghi", + "SMTPUsername": "def", + "SMTPPassword": "ghi", }, }, }, diff --git a/config/utils.go b/config/utils.go index 328be92c28..7c9eae64f1 100644 --- a/config/utils.go +++ b/config/utils.go @@ -81,8 +81,8 @@ func desanitize(actual, target *model.Config) { } } - if *target.MessageExportSettings.GlobalRelaySettings.SmtpPassword == model.FakeSetting { - *target.MessageExportSettings.GlobalRelaySettings.SmtpPassword = *actual.MessageExportSettings.GlobalRelaySettings.SmtpPassword + if *target.MessageExportSettings.GlobalRelaySettings.SMTPPassword == model.FakeSetting { + *target.MessageExportSettings.GlobalRelaySettings.SMTPPassword = *actual.MessageExportSettings.GlobalRelaySettings.SMTPPassword } if target.ServiceSettings.GfycatApiSecret != nil && *target.ServiceSettings.GfycatApiSecret == model.FakeSetting { diff --git a/einterfaces/metrics.go b/einterfaces/metrics.go index 8da04ed4ee..2e0f4deb7f 100644 --- a/einterfaces/metrics.go +++ b/einterfaces/metrics.go @@ -18,8 +18,8 @@ type MetricsInterface interface { IncrementPostBroadcast() IncrementPostFileAttachment(count int) - IncrementHttpRequest() - IncrementHttpError() + IncrementHTTPRequest() + IncrementHTTPError() IncrementClusterRequest() ObserveClusterRequestDuration(elapsed float64) diff --git a/einterfaces/mocks/MetricsInterface.go b/einterfaces/mocks/MetricsInterface.go index 908d71e9af..f00a9c8cb1 100644 --- a/einterfaces/mocks/MetricsInterface.go +++ b/einterfaces/mocks/MetricsInterface.go @@ -92,13 +92,13 @@ func (_m *MetricsInterface) IncrementFilesSearchCounter() { _m.Called() } -// IncrementHttpError provides a mock function with given fields: -func (_m *MetricsInterface) IncrementHttpError() { +// IncrementHTTPError provides a mock function with given fields: +func (_m *MetricsInterface) IncrementHTTPError() { _m.Called() } -// IncrementHttpRequest provides a mock function with given fields: -func (_m *MetricsInterface) IncrementHttpRequest() { +// IncrementHTTPRequest provides a mock function with given fields: +func (_m *MetricsInterface) IncrementHTTPRequest() { _m.Called() } diff --git a/model/access.go b/model/access.go index cbc84d9ee7..4ea07d1805 100644 --- a/model/access.go +++ b/model/access.go @@ -52,7 +52,7 @@ func (ad *AccessData) IsValid() *AppError { return NewAppError("AccessData.IsValid", "model.access.is_valid.refresh_token.app_error", nil, "", http.StatusBadRequest) } - if ad.RedirectUri == "" || len(ad.RedirectUri) > 256 || !IsValidHttpUrl(ad.RedirectUri) { + if ad.RedirectUri == "" || len(ad.RedirectUri) > 256 || !IsValidHTTPUrl(ad.RedirectUri) { return NewAppError("AccessData.IsValid", "model.access.is_valid.redirect_uri.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/authorize.go b/model/authorize.go index a6ab4329d9..c0dd49e9bf 100644 --- a/model/authorize.go +++ b/model/authorize.go @@ -57,7 +57,7 @@ func (ad *AuthData) IsValid() *AppError { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.create_at.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest) } - if len(ad.RedirectUri) > 256 || !IsValidHttpUrl(ad.RedirectUri) { + if len(ad.RedirectUri) > 256 || !IsValidHTTPUrl(ad.RedirectUri) { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.redirect_uri.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest) } @@ -84,7 +84,7 @@ func (ar *AuthorizeRequest) IsValid() *AppError { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.response_type.app_error", nil, "", http.StatusBadRequest) } - if ar.RedirectUri == "" || len(ar.RedirectUri) > 256 || !IsValidHttpUrl(ar.RedirectUri) { + if ar.RedirectUri == "" || len(ar.RedirectUri) > 256 || !IsValidHTTPUrl(ar.RedirectUri) { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.redirect_uri.app_error", nil, "client_id="+ar.ClientId, http.StatusBadRequest) } diff --git a/model/client4.go b/model/client4.go index 767e8f8f3a..19b1b9c186 100644 --- a/model/client4.go +++ b/model/client4.go @@ -35,7 +35,7 @@ const ( HeaderRemoteclusterToken = "X-RemoteCluster-Token" HeaderRemoteclusterId = "X-RemoteCluster-Id" HeaderRequestedWith = "X-Requested-With" - HeaderRequestedWithXml = "XMLHttpRequest" + HeaderRequestedWithXML = "XMLHttpRequest" HeaderRange = "Range" STATUS = "status" StatusOk = "OK" @@ -62,10 +62,10 @@ type Response struct { type Client4 struct { Url string // The location of the server, for example "http://localhost:8065" ApiUrl string // The api location of the server, for example "http://localhost:8065/api/v4" - HttpClient *http.Client // The http client + HTTPClient *http.Client // The http client AuthToken string AuthType string - HttpHeader map[string]string // Headers to be copied over for each request + HTTPHeader map[string]string // Headers to be copied over for each request // TrueString is the string value sent to the server for true boolean query parameters. trueString string @@ -131,7 +131,7 @@ func NewAPIv4SocketClient(socketPath string) *Client4 { } client := NewAPIv4Client("http://_") - client.HttpClient = &http.Client{Transport: tr} + client.HTTPClient = &http.Client{Transport: tr} return client } @@ -635,13 +635,13 @@ func (c *Client4) doApiRequestReader(method, url string, data io.Reader, headers rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - if c.HttpHeader != nil && len(c.HttpHeader) > 0 { - for k, v := range c.HttpHeader { + if c.HTTPHeader != nil && len(c.HTTPHeader) > 0 { + for k, v := range c.HTTPHeader { rq.Header.Set(k, v) } } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return nil, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0) } @@ -676,7 +676,7 @@ func (c *Client4) doUploadFile(url string, body io.Reader, contentType string, c rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return nil, BuildErrorResponse(rp, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0)) } @@ -700,7 +700,7 @@ func (c *Client4) DoEmojiUploadFile(url string, data []byte, contentType string) rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return nil, BuildErrorResponse(rp, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0)) } @@ -724,7 +724,7 @@ func (c *Client4) DoUploadImportTeam(url string, data []byte, contentType string rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return nil, BuildErrorResponse(rp, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0)) } @@ -1566,7 +1566,7 @@ func (c *Client4) SetProfileImage(userId string, data []byte) (bool, *Response) rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return false, &Response{StatusCode: http.StatusForbidden, Error: NewAppError(c.GetUserRoute(userId)+"/image", "model.client.connecting.app_error", nil, err.Error(), http.StatusForbidden)} } @@ -2402,7 +2402,7 @@ func (c *Client4) SetTeamIcon(teamId string, data []byte) (bool, *Response) { rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { // set to http.StatusForbidden(403) return false, &Response{StatusCode: http.StatusForbidden, Error: NewAppError(c.GetTeamRoute(teamId)+"/image", "model.client.connecting.app_error", nil, err.Error(), 403)} @@ -3894,7 +3894,7 @@ func (c *Client4) UploadLicenseFile(data []byte) (bool, *Response) { rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return false, &Response{StatusCode: http.StatusForbidden, Error: NewAppError(c.GetLicenseRoute(), "model.client.connecting.app_error", nil, err.Error(), http.StatusForbidden)} } @@ -4357,7 +4357,7 @@ func (c *Client4) DownloadComplianceReport(reportId string) ([]byte, *Response) rq.Header.Set(HeaderAuth, "BEARER "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return nil, &Response{Error: NewAppError("DownloadComplianceReport", "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)} } @@ -4738,7 +4738,7 @@ func (c *Client4) UploadBrandImage(data []byte) (bool, *Response) { rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return false, &Response{StatusCode: http.StatusForbidden, Error: NewAppError(c.GetBrandRoute()+"/image", "model.client.connecting.app_error", nil, err.Error(), http.StatusForbidden)} } @@ -4906,7 +4906,7 @@ func (c *Client4) GetOAuthAccessToken(data url.Values) (*AccessResponse, *Respon rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return nil, &Response{StatusCode: http.StatusForbidden, Error: NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 403)} } @@ -5832,7 +5832,7 @@ func (c *Client4) uploadPlugin(file io.Reader, force bool) (*Manifest, *Response rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } - rp, err := c.HttpClient.Do(rq) + rp, err := c.HTTPClient.Do(rq) if err != nil || rp == nil { return nil, BuildErrorResponse(rp, NewAppError("UploadPlugin", "model.client.connecting.app_error", nil, err.Error(), 0)) } diff --git a/model/command.go b/model/command.go index dad00bc17f..daad03a7b2 100644 --- a/model/command.go +++ b/model/command.go @@ -99,7 +99,7 @@ func (o *Command) IsValid() *AppError { return NewAppError("Command.IsValid", "model.command.is_valid.url.app_error", nil, "", http.StatusBadRequest) } - if !IsValidHttpUrl(o.URL) { + if !IsValidHTTPUrl(o.URL) { return NewAppError("Command.IsValid", "model.command.is_valid.url_http.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/config.go b/model/config.go index ae9d268732..076da47a64 100644 --- a/model/config.go +++ b/model/config.go @@ -27,7 +27,7 @@ import ( const ( ConnSecurityNone = "" ConnSecurityPlain = "PLAIN" - ConnSecurityTls = "TLS" + ConnSecurityTLS = "TLS" ConnSecurityStarttls = "STARTTLS" ImageDriverLocal = "local" @@ -100,8 +100,8 @@ const ( SitenameMaxLength = 30 ServiceSettingsDefaultSiteUrl = "http://localhost:8065" - ServiceSettingsDefaultTlsCertFile = "" - ServiceSettingsDefaultTlsKeyFile = "" + ServiceSettingsDefaultTLSCertFile = "" + ServiceSettingsDefaultTLSKeyFile = "" ServiceSettingsDefaultReadTimeout = 300 ServiceSettingsDefaultWriteTimeout = 300 ServiceSettingsDefaultIdleTimeout = 60 @@ -483,11 +483,11 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.TLSKeyFile == nil { - s.TLSKeyFile = NewString(ServiceSettingsDefaultTlsKeyFile) + s.TLSKeyFile = NewString(ServiceSettingsDefaultTLSKeyFile) } if s.TLSCertFile == nil { - s.TLSCertFile = NewString(ServiceSettingsDefaultTlsCertFile) + s.TLSCertFile = NewString(ServiceSettingsDefaultTLSCertFile) } if s.TLSMinVer == nil { @@ -2870,8 +2870,8 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) { type GlobalRelayMessageExportSettings struct { CustomerType *string `access:"compliance_compliance_export"` // must be either A9 or A10, dictates SMTP server url - SmtpUsername *string `access:"compliance_compliance_export"` - SmtpPassword *string `access:"compliance_compliance_export"` + SMTPUsername *string `access:"compliance_compliance_export"` + SMTPPassword *string `access:"compliance_compliance_export"` EmailAddress *string `access:"compliance_compliance_export"` // the address to send messages to SMTPServerTimeout *int `access:"compliance_compliance_export"` } @@ -2880,11 +2880,11 @@ func (s *GlobalRelayMessageExportSettings) SetDefaults() { if s.CustomerType == nil { s.CustomerType = NewString(GlobalrelayCustomerTypeA9) } - if s.SmtpUsername == nil { - s.SmtpUsername = NewString("") + if s.SMTPUsername == nil { + s.SMTPUsername = NewString("") } - if s.SmtpPassword == nil { - s.SmtpPassword = NewString("") + if s.SMTPPassword == nil { + s.SMTPPassword = NewString("") } if s.EmailAddress == nil { s.EmailAddress = NewString("") @@ -3445,7 +3445,7 @@ func (s *FileSettings) isValid() *AppError { } func (s *EmailSettings) isValid() *AppError { - if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTls || *s.ConnectionSecurity == ConnSecurityStarttls || *s.ConnectionSecurity == ConnSecurityPlain) { + if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTLS || *s.ConnectionSecurity == ConnSecurityStarttls || *s.ConnectionSecurity == ConnSecurityPlain) { return NewAppError("Config.IsValid", "model.config.is_valid.email_security.app_error", nil, "", http.StatusBadRequest) } @@ -3481,7 +3481,7 @@ func (s *RateLimitSettings) isValid() *AppError { } func (s *LdapSettings) isValid() *AppError { - if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTls || *s.ConnectionSecurity == ConnSecurityStarttls) { + if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTLS || *s.ConnectionSecurity == ConnSecurityStarttls) { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_security.app_error", nil, "", http.StatusBadRequest) } @@ -3542,11 +3542,11 @@ func (s *LdapSettings) isValid() *AppError { func (s *SamlSettings) isValid() *AppError { if *s.Enable { - if *s.IdpUrl == "" || !IsValidHttpUrl(*s.IdpUrl) { + if *s.IdpUrl == "" || !IsValidHTTPUrl(*s.IdpUrl) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_url.app_error", nil, "", http.StatusBadRequest) } - if *s.IdpDescriptorUrl == "" || !IsValidHttpUrl(*s.IdpDescriptorUrl) { + if *s.IdpDescriptorUrl == "" || !IsValidHTTPUrl(*s.IdpDescriptorUrl) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_descriptor_url.app_error", nil, "", http.StatusBadRequest) } @@ -3567,7 +3567,7 @@ func (s *SamlSettings) isValid() *AppError { } if *s.Verify { - if *s.AssertionConsumerServiceURL == "" || !IsValidHttpUrl(*s.AssertionConsumerServiceURL) { + if *s.AssertionConsumerServiceURL == "" || !IsValidHTTPUrl(*s.AssertionConsumerServiceURL) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_assertion_consumer_service_url.app_error", nil, "", http.StatusBadRequest) } } @@ -3616,11 +3616,11 @@ func (s *SamlSettings) isValid() *AppError { } func (s *ServiceSettings) isValid() *AppError { - if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTls) { + if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTLS) { return NewAppError("Config.IsValid", "model.config.is_valid.webserver_security.app_error", nil, "", http.StatusBadRequest) } - if *s.ConnectionSecurity == ConnSecurityTls && !*s.UseLetsEncrypt { + if *s.ConnectionSecurity == ConnSecurityTLS && !*s.UseLetsEncrypt { appErr := NewAppError("Config.IsValid", "model.config.is_valid.tls_cert_file_missing.app_error", nil, "", http.StatusBadRequest) if *s.TLSCertFile == "" { @@ -3811,9 +3811,9 @@ func (s *MessageExportSettings) isValid() *AppError { // validating email addresses is hard - just make sure it contains an '@' sign // see https://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.email_address.app_error", nil, "", http.StatusBadRequest) - } else if s.GlobalRelaySettings.SmtpUsername == nil || *s.GlobalRelaySettings.SmtpUsername == "" { + } else if s.GlobalRelaySettings.SMTPUsername == nil || *s.GlobalRelaySettings.SMTPUsername == "" { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.smtp_username.app_error", nil, "", http.StatusBadRequest) - } else if s.GlobalRelaySettings.SmtpPassword == nil || *s.GlobalRelaySettings.SmtpPassword == "" { + } else if s.GlobalRelaySettings.SMTPPassword == nil || *s.GlobalRelaySettings.SMTPPassword == "" { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.smtp_password.app_error", nil, "", http.StatusBadRequest) } } @@ -3914,8 +3914,8 @@ func (o *Config) Sanitize() { o.SqlSettings.DataSourceSearchReplicas[i] = FakeSetting } - if o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != nil && *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != "" { - *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword = FakeSetting + if o.MessageExportSettings.GlobalRelaySettings.SMTPPassword != nil && *o.MessageExportSettings.GlobalRelaySettings.SMTPPassword != "" { + *o.MessageExportSettings.GlobalRelaySettings.SMTPPassword = FakeSetting } if o.ServiceSettings.GfycatApiSecret != nil && *o.ServiceSettings.GfycatApiSecret != "" { @@ -4041,7 +4041,7 @@ func isDomainName(s string) bool { func isSafeLink(link *string) bool { if link != nil { - if IsValidHttpUrl(*link) { + if IsValidHTTPUrl(*link) { return true } else if strings.HasPrefix(*link, "/") { return true diff --git a/model/config_test.go b/model/config_test.go index c6c338e1e6..2df9b7733f 100644 --- a/model/config_test.go +++ b/model/config_test.go @@ -509,8 +509,8 @@ func TestMessageExportSettingsIsValidGlobalRelaySettingsInvalidCustomerType(t *t GlobalRelaySettings: &GlobalRelayMessageExportSettings{ CustomerType: NewString("Invalid"), EmailAddress: NewString("valid@mattermost.com"), - SmtpUsername: NewString("SomeUsername"), - SmtpPassword: NewString("SomePassword"), + SMTPUsername: NewString("SomeUsername"), + SMTPPassword: NewString("SomePassword"), }, } @@ -530,8 +530,8 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { &GlobalRelayMessageExportSettings{ CustomerType: NewString(GlobalrelayCustomerTypeA9), EmailAddress: NewString("invalidEmailAddress"), - SmtpUsername: NewString("SomeUsername"), - SmtpPassword: NewString("SomePassword"), + SMTPUsername: NewString("SomeUsername"), + SMTPPassword: NewString("SomePassword"), }, false, }, @@ -540,7 +540,7 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { &GlobalRelayMessageExportSettings{ CustomerType: NewString(GlobalrelayCustomerTypeA10), EmailAddress: NewString("valid@mattermost.com"), - SmtpPassword: NewString("SomePassword"), + SMTPPassword: NewString("SomePassword"), }, false, }, @@ -549,8 +549,8 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { &GlobalRelayMessageExportSettings{ CustomerType: NewString(GlobalrelayCustomerTypeA10), EmailAddress: NewString("valid@mattermost.com"), - SmtpUsername: NewString(""), - SmtpPassword: NewString("SomePassword"), + SMTPUsername: NewString(""), + SMTPPassword: NewString("SomePassword"), }, false, }, @@ -559,8 +559,8 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { &GlobalRelayMessageExportSettings{ CustomerType: NewString(GlobalrelayCustomerTypeA10), EmailAddress: NewString("valid@mattermost.com"), - SmtpUsername: NewString("SomeUsername"), - SmtpPassword: NewString(""), + SMTPUsername: NewString("SomeUsername"), + SMTPPassword: NewString(""), }, false, }, @@ -569,8 +569,8 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { &GlobalRelayMessageExportSettings{ CustomerType: NewString(GlobalrelayCustomerTypeA9), EmailAddress: NewString("valid@mattermost.com"), - SmtpUsername: NewString("SomeUsername"), - SmtpPassword: NewString("SomePassword"), + SMTPUsername: NewString("SomeUsername"), + SMTPPassword: NewString("SomePassword"), }, true, }, diff --git a/model/manifest.go b/model/manifest.go index b6f4ef7c75..e54549d1eb 100644 --- a/model/manifest.go +++ b/model/manifest.go @@ -329,15 +329,15 @@ func (m *Manifest) IsValid() error { return errors.New("a plugin name is needed") } - if m.HomepageURL != "" && !IsValidHttpUrl(m.HomepageURL) { + if m.HomepageURL != "" && !IsValidHTTPUrl(m.HomepageURL) { return errors.New("invalid HomepageURL") } - if m.SupportURL != "" && !IsValidHttpUrl(m.SupportURL) { + if m.SupportURL != "" && !IsValidHTTPUrl(m.SupportURL) { return errors.New("invalid SupportURL") } - if m.ReleaseNotesURL != "" && !IsValidHttpUrl(m.ReleaseNotesURL) { + if m.ReleaseNotesURL != "" && !IsValidHTTPUrl(m.ReleaseNotesURL) { return errors.New("invalid ReleaseNotesURL") } diff --git a/model/oauth.go b/model/oauth.go index 85e250cff0..b663e2359a 100644 --- a/model/oauth.go +++ b/model/oauth.go @@ -66,12 +66,12 @@ func (a *OAuthApp) IsValid() *AppError { } for _, callback := range a.CallbackUrls { - if !IsValidHttpUrl(callback) { + if !IsValidHTTPUrl(callback) { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.callback.app_error", nil, "", http.StatusBadRequest) } } - if a.Homepage == "" || len(a.Homepage) > 256 || !IsValidHttpUrl(a.Homepage) { + if a.Homepage == "" || len(a.Homepage) > 256 || !IsValidHTTPUrl(a.Homepage) { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.homepage.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } @@ -80,7 +80,7 @@ func (a *OAuthApp) IsValid() *AppError { } if a.IconURL != "" { - if len(a.IconURL) > 512 || !IsValidHttpUrl(a.IconURL) { + if len(a.IconURL) > 512 || !IsValidHTTPUrl(a.IconURL) { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.icon_url.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } } diff --git a/model/outgoing_webhook.go b/model/outgoing_webhook.go index 7df0189ac9..36fd2c1cab 100644 --- a/model/outgoing_webhook.go +++ b/model/outgoing_webhook.go @@ -165,7 +165,7 @@ func (o *OutgoingWebhook) IsValid() *AppError { } for _, callback := range o.CallbackURLs { - if !IsValidHttpUrl(callback) { + if !IsValidHTTPUrl(callback) { return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.url.app_error", nil, "", http.StatusBadRequest) } } diff --git a/model/permission.go b/model/permission.go index 9a90cb0d12..863d538d74 100644 --- a/model/permission.go +++ b/model/permission.go @@ -202,8 +202,8 @@ var PermissionSysconsoleWriteEnvironmentFileStorage *Permission var PermissionSysconsoleReadEnvironmentImageProxy *Permission var PermissionSysconsoleWriteEnvironmentImageProxy *Permission -var PermissionSysconsoleReadEnvironmentSmtp *Permission -var PermissionSysconsoleWriteEnvironmentSmtp *Permission +var PermissionSysconsoleReadEnvironmentSMTP *Permission +var PermissionSysconsoleWriteEnvironmentSMTP *Permission var PermissionSysconsoleReadEnvironmentPushNotificationServer *Permission var PermissionSysconsoleWriteEnvironmentPushNotificationServer *Permission @@ -1366,13 +1366,13 @@ func initializePermissions() { "", PermissionScopeSystem, } - PermissionSysconsoleReadEnvironmentSmtp = &Permission{ + PermissionSysconsoleReadEnvironmentSMTP = &Permission{ "sysconsole_read_environment_smtp", "", "", PermissionScopeSystem, } - PermissionSysconsoleWriteEnvironmentSmtp = &Permission{ + PermissionSysconsoleWriteEnvironmentSMTP = &Permission{ "sysconsole_write_environment_smtp", "", "", @@ -1912,7 +1912,7 @@ func initializePermissions() { PermissionSysconsoleReadEnvironmentElasticsearch, PermissionSysconsoleReadEnvironmentFileStorage, PermissionSysconsoleReadEnvironmentImageProxy, - PermissionSysconsoleReadEnvironmentSmtp, + PermissionSysconsoleReadEnvironmentSMTP, PermissionSysconsoleReadEnvironmentPushNotificationServer, PermissionSysconsoleReadEnvironmentHighAvailability, PermissionSysconsoleReadEnvironmentRateLimiting, @@ -1969,7 +1969,7 @@ func initializePermissions() { PermissionSysconsoleWriteEnvironmentElasticsearch, PermissionSysconsoleWriteEnvironmentFileStorage, PermissionSysconsoleWriteEnvironmentImageProxy, - PermissionSysconsoleWriteEnvironmentSmtp, + PermissionSysconsoleWriteEnvironmentSMTP, PermissionSysconsoleWriteEnvironmentPushNotificationServer, PermissionSysconsoleWriteEnvironmentHighAvailability, PermissionSysconsoleWriteEnvironmentRateLimiting, diff --git a/model/role.go b/model/role.go index db16126051..8a44258d16 100644 --- a/model/role.go +++ b/model/role.go @@ -89,7 +89,7 @@ func init() { PermissionSysconsoleWriteEnvironmentFileStorage.Id: { PermissionTestS3, }, - PermissionSysconsoleWriteEnvironmentSmtp.Id: { + PermissionSysconsoleWriteEnvironmentSMTP.Id: { PermissionTestEmail, }, PermissionSysconsoleReadReportingServerLogs.Id: { @@ -216,7 +216,7 @@ func init() { PermissionSysconsoleReadEnvironmentElasticsearch.Id, PermissionSysconsoleReadEnvironmentFileStorage.Id, PermissionSysconsoleReadEnvironmentImageProxy.Id, - PermissionSysconsoleReadEnvironmentSmtp.Id, + PermissionSysconsoleReadEnvironmentSMTP.Id, PermissionSysconsoleReadEnvironmentPushNotificationServer.Id, PermissionSysconsoleReadEnvironmentHighAvailability.Id, PermissionSysconsoleReadEnvironmentRateLimiting.Id, @@ -274,7 +274,7 @@ func init() { PermissionSysconsoleReadEnvironmentElasticsearch.Id, PermissionSysconsoleReadEnvironmentFileStorage.Id, PermissionSysconsoleReadEnvironmentImageProxy.Id, - PermissionSysconsoleReadEnvironmentSmtp.Id, + PermissionSysconsoleReadEnvironmentSMTP.Id, PermissionSysconsoleReadEnvironmentPushNotificationServer.Id, PermissionSysconsoleReadEnvironmentHighAvailability.Id, PermissionSysconsoleReadEnvironmentRateLimiting.Id, @@ -287,7 +287,7 @@ func init() { PermissionSysconsoleWriteEnvironmentElasticsearch.Id, PermissionSysconsoleWriteEnvironmentFileStorage.Id, PermissionSysconsoleWriteEnvironmentImageProxy.Id, - PermissionSysconsoleWriteEnvironmentSmtp.Id, + PermissionSysconsoleWriteEnvironmentSMTP.Id, PermissionSysconsoleWriteEnvironmentPushNotificationServer.Id, PermissionSysconsoleWriteEnvironmentHighAvailability.Id, PermissionSysconsoleWriteEnvironmentRateLimiting.Id, diff --git a/model/utils.go b/model/utils.go index 2ddc6cabdf..501a64bf7f 100644 --- a/model/utils.go +++ b/model/utils.go @@ -488,7 +488,7 @@ func ClearMentionTags(post string) string { return post } -func IsValidHttpUrl(rawUrl string) bool { +func IsValidHTTPUrl(rawUrl string) bool { if strings.Index(rawUrl, "http://") != 0 && strings.Index(rawUrl, "https://") != 0 { return false } diff --git a/model/utils_test.go b/model/utils_test.go index 2e811a0fc3..18ba3ee771 100644 --- a/model/utils_test.go +++ b/model/utils_test.go @@ -855,7 +855,7 @@ func TestSanitizeUnicode(t *testing.T) { } } -func TestIsValidHttpUrl(t *testing.T) { +func TestIsValidHTTPUrl(t *testing.T) { t.Parallel() testCases := []struct { @@ -940,7 +940,7 @@ func TestIsValidHttpUrl(t *testing.T) { }() t.Parallel() - require.Equal(t, testCase.Expected, IsValidHttpUrl(testCase.Value)) + require.Equal(t, testCase.Expected, IsValidHTTPUrl(testCase.Value)) }) } } diff --git a/services/telemetry/mocks/ServerIface.go b/services/telemetry/mocks/ServerIface.go index dbf28265f8..9d70638949 100644 --- a/services/telemetry/mocks/ServerIface.go +++ b/services/telemetry/mocks/ServerIface.go @@ -102,8 +102,8 @@ func (_m *ServerIface) GetSchemes(_a0 string, _a1 int, _a2 int) ([]*model.Scheme return r0, r1 } -// HttpService provides a mock function with given fields: -func (_m *ServerIface) HttpService() httpservice.HTTPService { +// HTTPService provides a mock function with given fields: +func (_m *ServerIface) HTTPService() httpservice.HTTPService { ret := _m.Called() var r0 httpservice.HTTPService diff --git a/services/telemetry/telemetry.go b/services/telemetry/telemetry.go index f1cd6a376f..a22c4be150 100644 --- a/services/telemetry/telemetry.go +++ b/services/telemetry/telemetry.go @@ -85,7 +85,7 @@ const ( type ServerIface interface { Config() *model.Config IsLeader() bool - HttpService() httpservice.HTTPService + HTTPService() httpservice.HTTPService GetPluginsEnvironment() *plugin.Environment License() *model.License GetRoleByName(context.Context, string) (*model.Role, *model.AppError) @@ -394,8 +394,8 @@ func (ts *TelemetryService) trackConfig() { "session_cache_in_minutes": *cfg.ServiceSettings.SessionCacheInMinutes, "session_idle_timeout_in_minutes": *cfg.ServiceSettings.SessionIdleTimeoutInMinutes, "isdefault_site_url": isDefault(*cfg.ServiceSettings.SiteURL, model.ServiceSettingsDefaultSiteUrl), - "isdefault_tls_cert_file": isDefault(*cfg.ServiceSettings.TLSCertFile, model.ServiceSettingsDefaultTlsCertFile), - "isdefault_tls_key_file": isDefault(*cfg.ServiceSettings.TLSKeyFile, model.ServiceSettingsDefaultTlsKeyFile), + "isdefault_tls_cert_file": isDefault(*cfg.ServiceSettings.TLSCertFile, model.ServiceSettingsDefaultTLSCertFile), + "isdefault_tls_key_file": isDefault(*cfg.ServiceSettings.TLSKeyFile, model.ServiceSettingsDefaultTLSKeyFile), "isdefault_read_timeout": isDefault(*cfg.ServiceSettings.ReadTimeout, model.ServiceSettingsDefaultReadTimeout), "isdefault_write_timeout": isDefault(*cfg.ServiceSettings.WriteTimeout, model.ServiceSettingsDefaultWriteTimeout), "isdefault_idle_timeout": isDefault(*cfg.ServiceSettings.IdleTimeout, model.ServiceSettingsDefaultIdleTimeout), @@ -793,8 +793,8 @@ func (ts *TelemetryService) trackConfig() { "default_export_from_timestamp": *cfg.MessageExportSettings.ExportFromTimestamp, "batch_size": *cfg.MessageExportSettings.BatchSize, "global_relay_customer_type": *cfg.MessageExportSettings.GlobalRelaySettings.CustomerType, - "is_default_global_relay_smtp_username": isDefault(*cfg.MessageExportSettings.GlobalRelaySettings.SmtpUsername, ""), - "is_default_global_relay_smtp_password": isDefault(*cfg.MessageExportSettings.GlobalRelaySettings.SmtpPassword, ""), + "is_default_global_relay_smtp_username": isDefault(*cfg.MessageExportSettings.GlobalRelaySettings.SMTPUsername, ""), + "is_default_global_relay_smtp_password": isDefault(*cfg.MessageExportSettings.GlobalRelaySettings.SMTPPassword, ""), "is_default_global_relay_email_address": isDefault(*cfg.MessageExportSettings.GlobalRelaySettings.EmailAddress, ""), "global_relay_smtp_server_timeout": *cfg.MessageExportSettings.GlobalRelaySettings.SMTPServerTimeout, "download_export_results": *cfg.MessageExportSettings.DownloadExportResults, @@ -1384,7 +1384,7 @@ func (ts *TelemetryService) trackPluginConfig(cfg *model.Config, marketplaceURL func (ts *TelemetryService) getAllMarketplaceplugins(marketplaceURL string) ([]*model.BaseMarketplacePlugin, error) { marketplaceClient, err := marketplace.NewClient( marketplaceURL, - ts.srv.HttpService(), + ts.srv.HTTPService(), ) if err != nil { return nil, err diff --git a/services/telemetry/telemetry_test.go b/services/telemetry/telemetry_test.go index d8a46f9dbd..4fe293b934 100644 --- a/services/telemetry/telemetry_test.go +++ b/services/telemetry/telemetry_test.go @@ -73,7 +73,7 @@ func initializeMocks(cfg *model.Config) (*mocks.ServerIface, *storeMocks.Store, serverIfaceMock.On("GetRoleByName", context.Background(), "channel_user").Return(&model.Role{Permissions: []string{"cu-test1", "cu-test2"}}, nil) serverIfaceMock.On("GetRoleByName", context.Background(), "channel_guest").Return(&model.Role{Permissions: []string{"cg-test1", "cg-test2"}}, nil) serverIfaceMock.On("GetSchemes", "team", 0, 100).Return([]*model.Scheme{}, nil) - serverIfaceMock.On("HttpService").Return(httpservice.MakeHTTPService(configService)) + serverIfaceMock.On("HTTPService").Return(httpservice.MakeHTTPService(configService)) storeMock := &storeMocks.Store{} storeMock.On("GetDbVersion", false).Return("5.24.0", nil) diff --git a/shared/mlog/levels.go b/shared/mlog/levels.go index 24d29e0bee..872b129687 100644 --- a/shared/mlog/levels.go +++ b/shared/mlog/levels.go @@ -28,7 +28,7 @@ var ( LvlAuditCLI = LogLevel{ID: 103, Name: "audit-cli"} // used by the TCP log target - LvlTcpLogTarget = LogLevel{ID: 120, Name: "TcpLogTarget"} + LvlTCPLogTarget = LogLevel{ID: 120, Name: "TcpLogTarget"} // used by Remote Cluster Service LvlRemoteClusterServiceDebug = LogLevel{ID: 130, Name: "RemoteClusterServiceDebug"} diff --git a/shared/mlog/logr.go b/shared/mlog/logr.go index c44fafa0cd..b253dfbc6c 100644 --- a/shared/mlog/logr.go +++ b/shared/mlog/logr.go @@ -181,7 +181,7 @@ func newSyslogTarget(name string, t *LogTarget, filter logr.Filter, formatter lo } func newTCPTarget(name string, t *LogTarget, filter logr.Filter, formatter logr.Formatter) (logr.Target, error) { - options := &TcpParams{} + options := &TCPParams{} if err := json.Unmarshal(t.Options, options); err != nil { return nil, err } @@ -192,7 +192,7 @@ func newTCPTarget(name string, t *LogTarget, filter logr.Filter, formatter logr. if options.Port == 0 { return nil, fmt.Errorf("missing 'Port' option for target %s", name) } - return NewTcpTarget(filter, formatter, options, t.MaxQueueSize) + return NewTCPTarget(filter, formatter, options, t.MaxQueueSize) } func checkFileWritable(filename string) error { diff --git a/shared/mlog/tcp.go b/shared/mlog/tcp.go index d65b43ee8c..7a6e6d1327 100644 --- a/shared/mlog/tcp.go +++ b/shared/mlog/tcp.go @@ -24,11 +24,11 @@ const ( MaxRetryBackoffMillis int64 = 30 * 1000 // 30 seconds ) -// Tcp outputs log records to raw socket server. -type Tcp struct { +// TCP outputs log records to raw socket server. +type TCP struct { logr.Basic - params *TcpParams + params *TCPParams addy string mutex sync.Mutex @@ -37,8 +37,8 @@ type Tcp struct { shutdown chan struct{} } -// TcpParams provides parameters for dialing a socket server. -type TcpParams struct { +// TCPParams provides parameters for dialing a socket server. +type TCPParams struct { IP string `json:"IP"` Port int `json:"Port"` TLS bool `json:"TLS"` @@ -46,9 +46,9 @@ type TcpParams struct { Insecure bool `json:"Insecure"` } -// NewTcpTarget creates a target capable of outputting log records to a raw socket, with or without TLS. -func NewTcpTarget(filter logr.Filter, formatter logr.Formatter, params *TcpParams, maxQueue int) (*Tcp, error) { - tcp := &Tcp{ +// NewTPCTarget creates a target capable of outputting log records to a raw socket, with or without TLS. +func NewTCPTarget(filter logr.Filter, formatter logr.Formatter, params *TCPParams, maxQueue int) (*TCP, error) { + tcp := &TCP{ params: params, addy: fmt.Sprintf("%s:%d", params.IP, params.Port), monitor: make(chan struct{}), @@ -61,15 +61,15 @@ func NewTcpTarget(filter logr.Filter, formatter logr.Formatter, params *TcpParam // getConn provides a net.Conn. If a connection already exists, it is returned immediately, // otherwise this method blocks until a new connection is created, timeout or shutdown. -func (tcp *Tcp) getConn() (net.Conn, error) { +func (tcp *TCP) getConn() (net.Conn, error) { tcp.mutex.Lock() defer tcp.mutex.Unlock() - Log(LvlTcpLogTarget, "getConn enter", String("addy", tcp.addy)) - defer Log(LvlTcpLogTarget, "getConn exit", String("addy", tcp.addy)) + Log(LvlTCPLogTarget, "getConn enter", String("addy", tcp.addy)) + defer Log(LvlTCPLogTarget, "getConn exit", String("addy", tcp.addy)) if tcp.conn != nil { - Log(LvlTcpLogTarget, "reusing existing conn", String("addy", tcp.addy)) // use "With" once Zap is removed + Log(LvlTCPLogTarget, "reusing existing conn", String("addy", tcp.addy)) // use "With" once Zap is removed return tcp.conn, nil } @@ -83,7 +83,7 @@ func (tcp *Tcp) getConn() (net.Conn, error) { defer cancel() go func(ctx context.Context, ch chan result) { - Log(LvlTcpLogTarget, "dailing", String("addy", tcp.addy)) + Log(LvlTCPLogTarget, "dailing", String("addy", tcp.addy)) conn, err := tcp.dial(ctx) if err == nil { tcp.conn = conn @@ -103,7 +103,7 @@ func (tcp *Tcp) getConn() (net.Conn, error) { // dial connects to a TCP socket, and optionally performs a TLS handshake. // A non-nil context must be provided which can cancel the dial. -func (tcp *Tcp) dial(ctx context.Context) (net.Conn, error) { +func (tcp *TCP) dial(ctx context.Context) (net.Conn, error) { var dialer net.Dialer dialer.Timeout = time.Second * DialTimeoutSecs conn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("%s:%d", tcp.params.IP, tcp.params.Port)) @@ -115,7 +115,7 @@ func (tcp *Tcp) dial(ctx context.Context) (net.Conn, error) { return conn, nil } - Log(LvlTcpLogTarget, "TLS handshake", String("addy", tcp.addy)) + Log(LvlTCPLogTarget, "TLS handshake", String("addy", tcp.addy)) tlsconfig := &tls.Config{ ServerName: tcp.params.IP, @@ -136,13 +136,13 @@ func (tcp *Tcp) dial(ctx context.Context) (net.Conn, error) { return tlsConn, nil } -func (tcp *Tcp) close() error { +func (tcp *TCP) close() error { tcp.mutex.Lock() defer tcp.mutex.Unlock() var err error if tcp.conn != nil { - Log(LvlTcpLogTarget, "closing connection", String("addy", tcp.addy)) + Log(LvlTCPLogTarget, "closing connection", String("addy", tcp.addy)) close(tcp.monitor) err = tcp.conn.Close() tcp.conn = nil @@ -151,10 +151,10 @@ func (tcp *Tcp) close() error { } // Shutdown stops processing log records after making best effort to flush queue. -func (tcp *Tcp) Shutdown(ctx context.Context) error { +func (tcp *TCP) Shutdown(ctx context.Context) error { errs := &multierror.Error{} - Log(LvlTcpLogTarget, "shutting down", String("addy", tcp.addy)) + Log(LvlTCPLogTarget, "shutting down", String("addy", tcp.addy)) if err := tcp.Basic.Shutdown(ctx); err != nil { errs = multierror.Append(errs, err) @@ -170,7 +170,7 @@ func (tcp *Tcp) Shutdown(ctx context.Context) error { // Write converts the log record to bytes, via the Formatter, and outputs to the socket. // Called by dedicated target goroutine and will block until success or shutdown. -func (tcp *Tcp) Write(rec *logr.LogRec) error { +func (tcp *TCP) Write(rec *logr.LogRec) error { _, stacktrace := tcp.IsLevelEnabled(rec.Level()) buf := rec.Logger().Logr().BorrowBuffer() @@ -192,7 +192,7 @@ func (tcp *Tcp) Write(rec *logr.LogRec) error { conn, err := tcp.getConn() if err != nil { - Log(LvlTcpLogTarget, "failed getting connection", String("addy", tcp.addy), Err(err)) + Log(LvlTCPLogTarget, "failed getting connection", String("addy", tcp.addy), Err(err)) reporter := rec.Logger().Logr().ReportError reporter(fmt.Errorf("log target %s connection error: %w", tcp.String(), err)) backoff = tcp.sleep(backoff) @@ -205,7 +205,7 @@ func (tcp *Tcp) Write(rec *logr.LogRec) error { return nil } - Log(LvlTcpLogTarget, "write error", String("addy", tcp.addy), Err(err)) + Log(LvlTCPLogTarget, "write error", String("addy", tcp.addy), Err(err)) reporter := rec.Logger().Logr().ReportError reporter(fmt.Errorf("log target %s write error: %w", tcp.String(), err)) @@ -213,7 +213,7 @@ func (tcp *Tcp) Write(rec *logr.LogRec) error { backoff = tcp.sleep(backoff) try++ - Log(LvlTcpLogTarget, "retrying write", String("addy", tcp.addy), Int("try", try)) + Log(LvlTCPLogTarget, "retrying write", String("addy", tcp.addy), Int("try", try)) } } @@ -223,11 +223,11 @@ func (tcp *Tcp) Write(rec *logr.LogRec) error { // the writes simply fail without an error returned. func monitor(conn net.Conn, done <-chan struct{}, logFunc LogFuncCustom) { addy := conn.RemoteAddr().String() - defer logFunc(LvlTcpLogTarget, "monitor exiting", String("addy", addy)) + defer logFunc(LvlTCPLogTarget, "monitor exiting", String("addy", addy)) buf := make([]byte, 1) for { - logFunc(LvlTcpLogTarget, "monitor loop", String("addy", addy)) + logFunc(LvlTCPLogTarget, "monitor loop", String("addy", addy)) select { case <-done: @@ -248,18 +248,18 @@ func monitor(conn net.Conn, done <-chan struct{}, logFunc LogFuncCustom) { } // Any other error closes the connection, forcing a reconnect. - logFunc(LvlTcpLogTarget, "monitor closing connection", Err(err)) + logFunc(LvlTCPLogTarget, "monitor closing connection", Err(err)) conn.Close() return } } // String returns a string representation of this target. -func (tcp *Tcp) String() string { +func (tcp *TCP) String() string { return fmt.Sprintf("TcpTarget[%s:%d]", tcp.params.IP, tcp.params.Port) } -func (tcp *Tcp) sleep(backoff int64) int64 { +func (tcp *TCP) sleep(backoff int64) int64 { select { case <-tcp.shutdown: case <-time.After(time.Millisecond * time.Duration(backoff)): diff --git a/shared/mlog/tcp_test.go b/shared/mlog/tcp_test.go index 0eb689385b..99fe2274f7 100644 --- a/shared/mlog/tcp_test.go +++ b/shared/mlog/tcp_test.go @@ -21,7 +21,7 @@ const ( testPort = 18066 ) -func TestNewTcpTarget(t *testing.T) { +func TestNewTCPTarget(t *testing.T) { target := LogTarget{ Type: "tcp", Format: "json", diff --git a/tests/test-config.json b/tests/test-config.json index 96665d18fb..58920939c3 100644 --- a/tests/test-config.json +++ b/tests/test-config.json @@ -378,8 +378,8 @@ "BatchSize": 10000, "GlobalRelaySettings": { "CustomerType": "A9", - "SmtpUsername": "", - "SmtpPassword": "", + "SMTPUsername": "", + "SMTPPassword": "", "EmailAddress": "" } }, diff --git a/utils/subpath_test.go b/utils/subpath_test.go index 956653e730..efc9c383e3 100644 --- a/utils/subpath_test.go +++ b/utils/subpath_test.go @@ -84,62 +84,62 @@ func TestUpdateAssetsSubpath(t *testing.T) { }{ { "no changes required, empty subpath provided", - baseRootHtml, - baseCss, + baseRootHTML, + baseCSS, baseManifestJSON, "", nil, - baseRootHtml, - baseCss, + baseRootHTML, + baseCSS, baseManifestJSON, }, { "no changes required", - baseRootHtml, - baseCss, + baseRootHTML, + baseCSS, baseManifestJSON, "/", nil, - baseRootHtml, - baseCss, + baseRootHTML, + baseCSS, baseManifestJSON, }, { "content security policy not found (missing quotes)", contentSecurityPolicyNotFoundHTML, - baseCss, + baseCSS, baseManifestJSON, "/subpath", fmt.Errorf("failed to find 'Content-Security-Policy' meta tag to rewrite"), contentSecurityPolicyNotFoundHTML, - baseCss, + baseCSS, baseManifestJSON, }, { "content security policy not found (missing unsafe-eval)", - contentSecurityPolicyNotFound2Html, - baseCss, + contentSecurityPolicyNotFound2HTML, + baseCSS, baseManifestJSON, "/subpath", fmt.Errorf("failed to find 'Content-Security-Policy' meta tag to rewrite"), - contentSecurityPolicyNotFound2Html, - baseCss, + contentSecurityPolicyNotFound2HTML, + baseCSS, baseManifestJSON, }, { "subpath", - baseRootHtml, - baseCss, + baseRootHTML, + baseCSS, baseManifestJSON, "/subpath", nil, - subpathRootHtml, + subpathRootHTML, subpathCSS, subpathManifestJSON, }, { "new subpath from old", - subpathRootHtml, + subpathRootHTML, subpathCSS, subpathManifestJSON, "/nested/subpath", @@ -150,13 +150,13 @@ func TestUpdateAssetsSubpath(t *testing.T) { }, { "resetting to /", - subpathRootHtml, + subpathRootHTML, subpathCSS, baseManifestJSON, "/", nil, - baseRootHtml, - baseCss, + baseRootHTML, + baseCSS, baseManifestJSON, }, } @@ -270,13 +270,13 @@ func sToP(s string) *string { const contentSecurityPolicyNotFoundHTML = ` Mattermost

Cannot connect to Mattermost


We're having trouble connecting to Mattermost. If refreshing this page (Ctrl+R or Command+R) does not work, please verify that your computer is connected to the internet.


` -const contentSecurityPolicyNotFound2Html = ` Mattermost

Cannot connect to Mattermost


We're having trouble connecting to Mattermost. If refreshing this page (Ctrl+R or Command+R) does not work, please verify that your computer is connected to the internet.


` +const contentSecurityPolicyNotFound2HTML = ` Mattermost

Cannot connect to Mattermost


We're having trouble connecting to Mattermost. If refreshing this page (Ctrl+R or Command+R) does not work, please verify that your computer is connected to the internet.


` -const baseRootHtml = ` Mattermost

Cannot connect to Mattermost


We're having trouble connecting to Mattermost. If refreshing this page (Ctrl+R or Command+R) does not work, please verify that your computer is connected to the internet.


` +const baseRootHTML = ` Mattermost

Cannot connect to Mattermost


We're having trouble connecting to Mattermost. If refreshing this page (Ctrl+R or Command+R) does not work, please verify that your computer is connected to the internet.


` -const baseCss = `@font-face{font-family:FontAwesome;src:url(/static/files/674f50d287a8c48dc19ba404d20fe713.eot);src:url(/static/files/674f50d287a8c48dc19ba404d20fe713.eot?#iefix&v=4.7.0) format("embedded-opentype"),url(/static/files/af7ae505a9eed503f8b8e6982036873e.woff2) format("woff2"),url(/static/files/fee66e712a8a08eef5805a46892932ad.woff) format("woff"),url(/static/files/b06871f281fee6b241d60582ae9369b9.ttf) format("truetype"),url(/static/files/677433a0892aaed7b7d2628c313c9775.svg#fontawesomeregular) format("svg");font-weight:400;font-style:normal}` +const baseCSS = `@font-face{font-family:FontAwesome;src:url(/static/files/674f50d287a8c48dc19ba404d20fe713.eot);src:url(/static/files/674f50d287a8c48dc19ba404d20fe713.eot?#iefix&v=4.7.0) format("embedded-opentype"),url(/static/files/af7ae505a9eed503f8b8e6982036873e.woff2) format("woff2"),url(/static/files/fee66e712a8a08eef5805a46892932ad.woff) format("woff"),url(/static/files/b06871f281fee6b241d60582ae9369b9.ttf) format("truetype"),url(/static/files/677433a0892aaed7b7d2628c313c9775.svg#fontawesomeregular) format("svg");font-weight:400;font-style:normal}` -const subpathRootHtml = ` Mattermost

Cannot connect to Mattermost


We're having trouble connecting to Mattermost. If refreshing this page (Ctrl+R or Command+R) does not work, please verify that your computer is connected to the internet.


` +const subpathRootHTML = ` Mattermost

Cannot connect to Mattermost


We're having trouble connecting to Mattermost. If refreshing this page (Ctrl+R or Command+R) does not work, please verify that your computer is connected to the internet.


` const subpathCSS = `@font-face{font-family:FontAwesome;src:url(/subpath/static/files/674f50d287a8c48dc19ba404d20fe713.eot);src:url(/subpath/static/files/674f50d287a8c48dc19ba404d20fe713.eot?#iefix&v=4.7.0) format("embedded-opentype"),url(/subpath/static/files/af7ae505a9eed503f8b8e6982036873e.woff2) format("woff2"),url(/subpath/static/files/fee66e712a8a08eef5805a46892932ad.woff) format("woff"),url(/subpath/static/files/b06871f281fee6b241d60582ae9369b9.ttf) format("truetype"),url(/subpath/static/files/677433a0892aaed7b7d2628c313c9775.svg#fontawesomeregular) format("svg");font-weight:400;font-style:normal}` diff --git a/web/handlers.go b/web/handlers.go index eb77a27d4b..ca2a61a119 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -328,13 +328,13 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if c.App.Metrics() != nil { - c.App.Metrics().IncrementHttpError() + c.App.Metrics().IncrementHTTPError() } } statusCode = strconv.Itoa(w.(*responseWriterWrapper).StatusCode()) if c.App.Metrics() != nil { - c.App.Metrics().IncrementHttpRequest() + c.App.Metrics().IncrementHTTPRequest() if r.URL.Path != model.ApiUrlSuffix+"/websocket" { elapsed := float64(time.Since(now)) / float64(time.Second) @@ -354,7 +354,7 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke if csrfHeader == session.GetCSRF() { csrfCheckPassed = true - } else if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXml { + } else if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXML { // ToDo(DSchalla) 2019/01/04: Remove after deprecation period and only allow CSRF Header (MM-13657) csrfErrorMessage := "CSRF Header check failed for request - Please upgrade your web application or custom app to set a CSRF Header" diff --git a/web/handlers_test.go b/web/handlers_test.go index a45ac4849c..fbd3fbe137 100644 --- a/web/handlers_test.go +++ b/web/handlers_test.go @@ -196,7 +196,7 @@ func TestHandlerServeCSRFToken(t *testing.T) { request.AddCookie(cookie) request.AddCookie(cookie2) request.AddCookie(cookie3) - request.Header.Add(model.HeaderRequestedWith, model.HeaderRequestedWithXml) + request.Header.Add(model.HeaderRequestedWith, model.HeaderRequestedWithXML) response = httptest.NewRecorder() handler.ServeHTTP(response, request) @@ -458,7 +458,7 @@ func TestCheckCSRFToken(t *testing.T) { AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) - r.Header.Set(model.HeaderRequestedWith, model.HeaderRequestedWithXml) + r.Header.Set(model.HeaderRequestedWith, model.HeaderRequestedWithXML) session := &model.Session{ Props: map[string]string{ "csrf": token, @@ -508,7 +508,7 @@ func TestCheckCSRFToken(t *testing.T) { AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) - r.Header.Set(model.HeaderRequestedWith, model.HeaderRequestedWithXml) + r.Header.Set(model.HeaderRequestedWith, model.HeaderRequestedWithXML) session := &model.Session{ Props: map[string]string{ "csrf": token, diff --git a/web/oauth_test.go b/web/oauth_test.go index 2ad225905d..5d8080deb2 100644 --- a/web/oauth_test.go +++ b/web/oauth_test.go @@ -439,12 +439,12 @@ func TestOAuthComplete(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuthServiceProvider }) }() - r, err := HttpGet(ApiClient.Url+"/login/gitlab/complete?code=123", ApiClient.HttpClient, "", true) + r, err := HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123", ApiClient.HTTPClient, "", true) assert.NotNil(t, err) closeBody(r) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true }) - r, err = HttpGet(ApiClient.Url+"/login/gitlab/complete?code=123&state=!#$#F@#Yˆ&~ñ", ApiClient.HttpClient, "", true) + r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state=!#$#F@#Yˆ&~ñ", ApiClient.HTTPClient, "", true) assert.NotNil(t, err) closeBody(r) @@ -457,13 +457,13 @@ func TestOAuthComplete(t *testing.T) { stateProps["redirect_to"] = *th.App.Config().GitLabSettings.AuthEndpoint state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - r, err = HttpGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HttpClient, "", true) + r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", true) assert.NotNil(t, err) closeBody(r) stateProps["hash"] = utils.HashSha256(*th.App.Config().GitLabSettings.Id) state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - r, err = HttpGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HttpClient, "", true) + r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", true) assert.NotNil(t, err) closeBody(r) @@ -518,7 +518,7 @@ func TestOAuthComplete(t *testing.T) { stateProps["hash"] = utils.HashSha256(*th.App.Config().GitLabSettings.Id) stateProps["redirect_to"] = "/oauth/authorize" state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - r, err = HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false) + r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false) if err == nil { closeBody(r) } @@ -530,7 +530,7 @@ func TestOAuthComplete(t *testing.T) { rurl, _ = url.Parse(redirect) code = rurl.Query().Get("code") - r, err = HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false) + r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false) if err == nil { closeBody(r) } @@ -546,7 +546,7 @@ func TestOAuthComplete(t *testing.T) { code = rurl.Query().Get("code") stateProps["action"] = model.OAuthActionLogin state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err := HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { + if r, err := HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil { closeBody(r) } @@ -557,7 +557,7 @@ func TestOAuthComplete(t *testing.T) { code = rurl.Query().Get("code") delete(stateProps, "action") state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err := HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { + if r, err := HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil { closeBody(r) } @@ -568,7 +568,7 @@ func TestOAuthComplete(t *testing.T) { code = rurl.Query().Get("code") stateProps["action"] = model.OAuthActionSignup state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err := HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { + if r, err := HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil { closeBody(r) } } @@ -612,7 +612,7 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) { assert.Contains(t, responseWriter.Body.String(), "") } -func HttpGet(url string, httpClient *http.Client, authToken string, followRedirect bool) (*http.Response, *model.AppError) { +func HTTPGet(url string, httpClient *http.Client, authToken string, followRedirect bool) (*http.Response, *model.AppError) { rq, _ := http.NewRequest("GET", url, nil) rq.Close = true