[MM-61074] Fix errcheck issues in oauth_test.go and web_test.go (#30707)

Co-authored-by: Claude <noreply@anthropic.com>
Этот коммит содержится в:
Ben Schumacher
2025-05-07 12:41:10 +02:00
коммит произвёл GitHub
родитель b8b3efda48
Коммит bfb15ab179
18 изменённых файлов: 288 добавлений и 303 удалений

Просмотреть файл

@@ -36,7 +36,6 @@ func TestRequireHookId(t *testing.T) {
func TestCloudKeyRequired(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
th.App.Srv().SetLicense(model.NewTestLicense("cloud"))
@@ -52,7 +51,6 @@ func TestCloudKeyRequired(t *testing.T) {
func TestMfaRequired(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
mockStore := th.App.Srv().Store().(*mocks.Store)
mockUserStore := mocks.UserStore{}

Просмотреть файл

@@ -27,7 +27,6 @@ func handlerForHTTPErrors(c *Context, w http.ResponseWriter, r *http.Request) {
func TestHandlerServeHTTPErrors(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
web := New(th.Server)
handler := web.NewHandler(handlerForHTTPErrors)
@@ -67,7 +66,6 @@ func handlerForServeDefaultSecurityHeaders(c *Context, w http.ResponseWriter, r
func TestHandlerServeDefaultSecurityHeaders(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
web := New(th.Server)
handler := web.NewHandler(handlerForServeDefaultSecurityHeaders)
@@ -105,7 +103,6 @@ func handlerForHTTPSecureTransport(c *Context, w http.ResponseWriter, r *http.Re
func TestHandlerServeHTTPSecureTransport(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
mockStore := th.App.Srv().Store().(*mocks.Store)
mockUserStore := mocks.UserStore{}
@@ -163,8 +160,7 @@ func handlerForCSRFToken(c *Context, w http.ResponseWriter, r *http.Request) {
}
func TestHandlerServeCSRFToken(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th := Setup(t).InitBasic(t)
session := &model.Session{
UserId: th.BasicUser.Id,
@@ -175,9 +171,7 @@ func TestHandlerServeCSRFToken(t *testing.T) {
session.GenerateCSRF()
th.App.SetSessionExpireInHours(session, 24)
session, err := th.App.CreateSession(th.Context, session)
if err != nil {
t.Errorf("Expected nil, got %s", err)
}
require.Nil(t, err)
web := New(th.Server)
@@ -304,7 +298,6 @@ func handlerForCSPHeader(c *Context, w http.ResponseWriter, r *http.Request) {
func TestHandlerServeCSPHeader(t *testing.T) {
t.Run("non-static", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
web := New(th.Server)
@@ -326,7 +319,6 @@ func TestHandlerServeCSPHeader(t *testing.T) {
t.Run("static, without subpath", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
web := New(th.Server)
@@ -348,7 +340,6 @@ func TestHandlerServeCSPHeader(t *testing.T) {
t.Run("static, with subpath and frame ancestors", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
mockStore := th.App.Srv().Store().(*mocks.Store)
mockUserStore := mocks.UserStore{}
@@ -407,7 +398,6 @@ func TestHandlerServeCSPHeader(t *testing.T) {
t.Run("dev mode", func(t *testing.T) {
th := Setup(t)
defer th.TearDown()
oldBuildNumber := model.BuildNumber
model.BuildNumber = "dev"
@@ -437,7 +427,6 @@ func TestHandlerServeCSPHeader(t *testing.T) {
func TestGenerateDevCSP(t *testing.T) {
t.Run("dev mode", func(t *testing.T) {
th := Setup(t)
defer th.TearDown()
oldBuildNumber := model.BuildNumber
model.BuildNumber = "dev"
@@ -457,7 +446,6 @@ func TestGenerateDevCSP(t *testing.T) {
t.Run("allowed dev flags", func(t *testing.T) {
th := Setup(t)
defer th.TearDown()
oldBuildNumber := model.BuildNumber
model.BuildNumber = "0"
@@ -482,7 +470,6 @@ func TestGenerateDevCSP(t *testing.T) {
t.Run("partial dev flags", func(t *testing.T) {
th := Setup(t)
defer th.TearDown()
oldBuildNumber := model.BuildNumber
model.BuildNumber = "0"
@@ -507,7 +494,6 @@ func TestGenerateDevCSP(t *testing.T) {
t.Run("unknown dev flags", func(t *testing.T) {
th := Setup(t)
defer th.TearDown()
oldBuildNumber := model.BuildNumber
model.BuildNumber = "0"
@@ -532,7 +518,6 @@ func TestGenerateDevCSP(t *testing.T) {
t.Run("empty dev flags", func(t *testing.T) {
th := Setup(t)
defer th.TearDown()
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.DeveloperFlags = ""
@@ -567,7 +552,6 @@ func TestHandlerServeInvalidToken(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.Description, func(t *testing.T) {
th := Setup(t)
defer th.TearDown()
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.SiteURL = tc.SiteURL
@@ -604,7 +588,6 @@ func TestHandlerServeInvalidToken(t *testing.T) {
func TestCheckCSRFToken(t *testing.T) {
t.Run("should allow a POST request with a valid CSRF token header", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
h := &Handler{
RequireSession: true,
@@ -635,7 +618,6 @@ func TestCheckCSRFToken(t *testing.T) {
t.Run("should allow a POST request with an X-Requested-With header", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
h := &Handler{
RequireSession: true,
@@ -667,7 +649,6 @@ func TestCheckCSRFToken(t *testing.T) {
t.Run("should not allow a POST request with an X-Requested-With header with strict CSRF enforcement enabled", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
mockStore := th.App.Srv().Store().(*mocks.Store)
mockUserStore := mocks.UserStore{}
@@ -718,7 +699,6 @@ func TestCheckCSRFToken(t *testing.T) {
t.Run("should not allow a POST request without either header", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
h := &Handler{
RequireSession: true,
@@ -748,7 +728,6 @@ func TestCheckCSRFToken(t *testing.T) {
t.Run("should not check GET requests", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
h := &Handler{
RequireSession: true,
@@ -778,7 +757,6 @@ func TestCheckCSRFToken(t *testing.T) {
t.Run("should not check a request passing the auth token in a header", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
h := &Handler{
RequireSession: true,
@@ -808,7 +786,6 @@ func TestCheckCSRFToken(t *testing.T) {
t.Run("should not check a request passing a nil session", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
h := &Handler{
RequireSession: false,
@@ -834,7 +811,6 @@ func TestCheckCSRFToken(t *testing.T) {
t.Run("should check requests for handlers that don't require a session but have one", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
h := &Handler{
RequireSession: false,
@@ -939,7 +915,6 @@ func noOpHandler(_ *Context, _ http.ResponseWriter, _ *http.Request) {
func TestHandlerServeHTTPBasicSecurityChecks(t *testing.T) {
t.Run("Should not cause 414 error if url is smaller than configured limit", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
web := New(th.Server)
handler := web.NewHandler(noOpHandler)
@@ -953,7 +928,6 @@ func TestHandlerServeHTTPBasicSecurityChecks(t *testing.T) {
t.Run("Should cause 414 error if url is longer than configured limit", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
mockStore := th.App.Srv().Store().(*mocks.Store)
mockUserStore := mocks.UserStore{}
@@ -985,7 +959,6 @@ func TestHandlerServeHTTPBasicSecurityChecks(t *testing.T) {
t.Run("414 error should include query params in computing URL length", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
mockStore := th.App.Srv().Store().(*mocks.Store)
mockUserStore := mocks.UserStore{}
@@ -1034,7 +1007,6 @@ func TestHandlerServeHTTPRequestPayloadLimit(t *testing.T) {
t.Run("should allow payload smaller than set limit", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
web := New(th.Server)
handler := web.NewHandler(jsonReaderHandler)
@@ -1049,7 +1021,6 @@ func TestHandlerServeHTTPRequestPayloadLimit(t *testing.T) {
t.Run("Should error out when request body is larger than set limit", func(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
mockStore := th.App.Srv().Store().(*mocks.Store)
mockUserStore := mocks.UserStore{}

Просмотреть файл

@@ -24,8 +24,7 @@ import (
)
func TestOAuthComplete_AccessDenied(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th := Setup(t).InitBasic(t)
c := &Context{
App: th.App,
@@ -35,7 +34,8 @@ func TestOAuthComplete_AccessDenied(t *testing.T) {
AppContext: request.EmptyContext(th.TestLogger),
}
responseWriter := httptest.NewRecorder()
request, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/signup/TestService/complete?error=access_denied", nil)
request, err := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/signup/TestService/complete?error=access_denied", nil)
require.NoError(t, err)
completeOAuth(c, responseWriter, request)
@@ -43,15 +43,15 @@ func TestOAuthComplete_AccessDenied(t *testing.T) {
assert.Equal(t, http.StatusTemporaryRedirect, response.StatusCode)
location, _ := url.Parse(response.Header.Get("Location"))
location, err := url.Parse(response.Header.Get("Location"))
require.NoError(t, err)
assert.Equal(t, "oauth_access_denied", location.Query().Get("type"))
assert.Equal(t, "TestService", location.Query().Get("service"))
}
func TestAuthorizeOAuthApp(t *testing.T) {
th := Setup(t).InitBasic()
th.Login(apiClient, th.SystemAdminUser)
defer th.TearDown()
th := Setup(t).InitBasic(t)
th.Login(t, apiClient, th.SystemAdminUser)
enableOAuth := *th.App.Config().ServiceSettings.EnableOAuthServiceProvider
defer func() {
@@ -85,7 +85,8 @@ func TestAuthorizeOAuthApp(t *testing.T) {
require.NotEmpty(t, ruri, "redirect url should be set")
ru, _ := url.Parse(ruri)
ru, err := url.Parse(ruri)
require.NoError(t, err)
require.NotNil(t, ru, "redirect url unparseable")
require.NotEmpty(t, ru.Query().Get("code"), "authorization code not returned")
require.Equal(t, ru.Query().Get("state"), authRequest.State, "returned state doesn't match")
@@ -96,7 +97,8 @@ func TestAuthorizeOAuthApp(t *testing.T) {
require.NoError(t, err)
require.False(t, ruri == "", "redirect url should be set")
ru, _ = url.Parse(ruri)
ru, err = url.Parse(ruri)
require.NoError(t, err)
require.NotNil(t, ru, "redirect url unparseable")
values, err := url.ParseQuery(ru.Fragment)
require.NoError(t, err)
@@ -159,7 +161,8 @@ func TestAuthorizeOAuthApp(t *testing.T) {
}
uriResponse, _, err := apiClient.AuthorizeOAuthApp(context.Background(), authRequest)
require.NoError(t, err)
ru, _ = url.Parse(uriResponse)
ru, err = url.Parse(uriResponse)
require.NoError(t, err)
require.NotEmpty(t, uriResponse, "redirect url should be set")
require.NotNil(t, ru, "redirect url unparseable")
// require no query parameter to have "?"
@@ -173,9 +176,8 @@ func TestAuthorizeOAuthApp(t *testing.T) {
}
func TestDeauthorizeOAuthApp(t *testing.T) {
th := Setup(t).InitBasic()
th.Login(apiClient, th.SystemAdminUser)
defer th.TearDown()
th := Setup(t).InitBasic(t)
th.Login(t, apiClient, th.SystemAdminUser)
enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
defer func() {
@@ -226,9 +228,8 @@ func TestOAuthAccessToken(t *testing.T) {
t.SkipNow()
}
th := Setup(t).InitBasic()
th.Login(apiClient, th.SystemAdminUser)
defer th.TearDown()
th := Setup(t).InitBasic(t)
th.Login(t, apiClient, th.SystemAdminUser)
enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
defer func() {
@@ -270,14 +271,13 @@ func TestOAuthAccessToken(t *testing.T) {
redirect, _, err := apiClient.AuthorizeOAuthApp(context.Background(), authRequest)
require.NoError(t, err)
rurl, _ := url.Parse(redirect)
apiClient.Logout(context.Background())
rurl, err := url.Parse(redirect)
require.NoError(t, err)
data = url.Values{"grant_type": []string{"junk"}, "client_id": []string{oauthApp.Id}, "client_secret": []string{oauthApp.ClientSecret}, "code": []string{rurl.Query().Get("code")}, "redirect_uri": []string{oauthApp.CallbackUrls[0]}}
_, _, err = apiClient.GetOAuthAccessToken(context.Background(), data)
_, resp, err := apiClient.GetOAuthAccessToken(context.Background(), data)
require.Error(t, err, "should have failed - bad grant type")
CheckBadRequestStatus(t, resp)
data.Set("grant_type", model.AccessTokenGrantType)
data.Set("client_id", "")
@@ -395,8 +395,8 @@ func TestOAuthAccessToken(t *testing.T) {
}
func TestMobileLoginWithOAuth(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th := Setup(t).InitBasic(t)
c := &Context{
App: th.App,
AppContext: th.Context,
@@ -417,7 +417,8 @@ func TestMobileLoginWithOAuth(t *testing.T) {
t.Run("Should redirect to the SSO login page when valid URL Scheme is passed as redirect_to parameter", func(t *testing.T) {
responseWriter := httptest.NewRecorder()
request, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/oauth/gitlab/mobile_login?redirect_to="+url.QueryEscape("mmauth://"), nil)
request, err := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/oauth/gitlab/mobile_login?redirect_to="+url.QueryEscape("mmauth://"), nil)
require.NoError(t, err)
mobileLoginWithOAuth(c, responseWriter, request)
assert.Equal(t, responseWriter.Code, 302)
assert.NotContains(t, responseWriter.Body.String(), siteURL)
@@ -426,7 +427,8 @@ func TestMobileLoginWithOAuth(t *testing.T) {
t.Run("Should include SiteURL in the output when invalid URL Scheme is passed", func(t *testing.T) {
einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider)
responseWriter := httptest.NewRecorder()
request, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/oauth/gitlab/mobile_login?redirect_to="+url.QueryEscape("randomScheme://"), nil)
request, err := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/oauth/gitlab/mobile_login?redirect_to="+url.QueryEscape("randomScheme://"), nil)
require.NoError(t, err)
mobileLoginWithOAuth(c, responseWriter, request)
body := responseWriter.Body.String()
assert.NotContains(t, body, "randomScheme://")
@@ -435,7 +437,8 @@ func TestMobileLoginWithOAuth(t *testing.T) {
t.Run("Should not include the redirect URL consisting of javascript protocol", func(t *testing.T) {
responseWriter := httptest.NewRecorder()
request, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/oauth/gitlab/mobile_login?redirect_to="+url.QueryEscape("javascript:alert('hello')"), nil)
request, err := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/oauth/gitlab/mobile_login?redirect_to="+url.QueryEscape("javascript:alert('hello')"), nil)
require.NoError(t, err)
mobileLoginWithOAuth(c, responseWriter, request)
body := responseWriter.Body.String()
assert.NotContains(t, body, "javascript:alert('hello')")
@@ -444,7 +447,8 @@ func TestMobileLoginWithOAuth(t *testing.T) {
t.Run("Should not include the redirect URL consisting of javascript protocol in mixed case", func(t *testing.T) {
responseWriter := httptest.NewRecorder()
request, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/oauth/gitlab/mobile_login?redirect_to="+url.QueryEscape("JaVasCript:alert('hello')"), nil)
request, err := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/oauth/gitlab/mobile_login?redirect_to="+url.QueryEscape("JaVasCript:alert('hello')"), nil)
require.NoError(t, err)
mobileLoginWithOAuth(c, responseWriter, request)
body := responseWriter.Body.String()
assert.NotContains(t, body, "JaVasCript:alert('hello')")
@@ -457,9 +461,8 @@ func TestOAuthComplete(t *testing.T) {
t.SkipNow()
}
th := Setup(t).InitBasic()
th.Login(apiClient, th.SystemAdminUser)
defer th.TearDown()
th := Setup(t).InitBasic(t)
th.Login(t, apiClient, th.SystemAdminUser)
gitLabSettingsEnable := th.App.Config().GitLabSettings.Enable
gitLabSettingsAuthEndpoint := th.App.Config().GitLabSettings.AuthEndpoint
@@ -548,7 +551,8 @@ func TestOAuthComplete(t *testing.T) {
redirect, _, err := apiClient.AuthorizeOAuthApp(context.Background(), authRequest)
require.NoError(t, err)
rurl, _ := url.Parse(redirect)
rurl, err := url.Parse(redirect)
require.NoError(t, err)
code := rurl.Query().Get("code")
stateProps["action"] = model.OAuthActionEmailToSSO
@@ -613,8 +617,8 @@ func TestOAuthComplete(t *testing.T) {
}
func TestOAuthComplete_ErrorMessages(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th := Setup(t).InitBasic(t)
c := &Context{
App: th.App,
AppContext: th.Context,
@@ -632,7 +636,8 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) {
responseWriter := httptest.NewRecorder()
// Renders for web & mobile app with webview
request, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/signup/gitlab/complete?code=1234", nil)
request, err := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/signup/gitlab/complete?code=1234", nil)
require.NoError(t, err)
completeOAuth(c, responseWriter, request)
assert.Contains(t, responseWriter.Body.String(), "<!-- web error message -->")
@@ -642,14 +647,18 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) {
stateProps["action"] = model.OAuthActionMobile
stateProps["redirect_to"] = th.App.Config().NativeAppSettings.AppCustomURLSchemes[0]
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJSON(stateProps)))
request2, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/signup/gitlab/complete?code=1234&state="+url.QueryEscape(state), nil)
request2, err := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/signup/gitlab/complete?code=1234&state="+url.QueryEscape(state), nil)
require.NoError(t, err)
completeOAuth(c, responseWriter, request2)
assert.Contains(t, responseWriter.Body.String(), "<!-- mobile app message -->")
}
func HTTPGet(url string, httpClient *http.Client, authToken string, followRedirect bool) (*http.Response, error) {
rq, _ := http.NewRequest("GET", url, nil)
rq, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
rq.Close = true
if authToken != "" {
@@ -678,7 +687,7 @@ func HTTPGet(url string, httpClient *http.Client, authToken string, followRedire
func closeBody(r *http.Response) {
if r != nil && r.Body != nil {
io.ReadAll(r.Body)
_, _ = io.ReadAll(r.Body) // Discard and ignore errors - just draining the body
r.Body.Close()
}
}
@@ -739,13 +748,16 @@ func CheckBadRequestStatus(t *testing.T, resp *model.Response) {
checkHTTPStatus(t, resp, http.StatusBadRequest)
}
func (th *TestHelper) Login(client *model.Client4, user *model.User) {
func (th *TestHelper) Login(tb testing.TB, client *model.Client4, user *model.User) {
tb.Helper()
session := &model.Session{
UserId: user.Id,
Roles: user.GetRawRoles(),
IsOAuth: false,
}
session, _ = th.App.CreateSession(th.Context, session)
session, appErr := th.App.CreateSession(th.Context, session)
require.Nil(tb, appErr)
client.AuthToken = session.Token
client.AuthType = model.HeaderBearer
}

Просмотреть файл

@@ -89,27 +89,24 @@ func setupTestHelper(tb testing.TB, includeCacheLayer bool, options []app.Option
options = append(options, app.StoreOverride(mainHelper.Store))
}
testLogger, _ := mlog.NewLogger()
logCfg, _ := config.MloggerConfigFromLoggerConfig(&newConfig.LogSettings, nil, config.GetLogFileLocation)
if errCfg := testLogger.ConfigureTargets(logCfg, nil); errCfg != nil {
panic("failed to configure test logger: " + errCfg.Error())
}
testLogger, err := mlog.NewLogger()
require.NoError(tb, err)
logCfg, err := config.MloggerConfigFromLoggerConfig(&newConfig.LogSettings, nil, config.GetLogFileLocation)
require.NoError(tb, err)
err = testLogger.ConfigureTargets(logCfg, nil)
require.NoError(tb, err, "failed to configure test logger")
// lock logger config so server init cannot override it during testing.
testLogger.LockConfiguration()
options = append(options, app.SetLogger(testLogger))
s, err := app.NewServer(options...)
if err != nil {
panic(err)
}
require.NoError(tb, err)
a := app.New(app.ServerConnector(s.Channels()))
prevListenAddress := *s.Config().ServiceSettings.ListenAddress
a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = "localhost:0" })
serverErr := s.Start()
if serverErr != nil {
panic(serverErr)
}
err = s.Start()
require.NoError(tb, err)
a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress })
// Disable strict password requirements for test
@@ -140,6 +137,15 @@ func setupTestHelper(tb testing.TB, includeCacheLayer bool, options []app.Option
TestLogger: testLogger,
}
tb.Cleanup(func() {
if th.IncludeCacheLayer {
// Clean all the caches
appErr := th.App.Srv().InvalidateAllCaches()
require.Nil(tb, appErr)
}
th.Server.Shutdown()
})
return th
}
@@ -156,35 +162,30 @@ func (th *TestHelper) NewPluginAPI(manifest *model.Manifest) plugin.API {
return th.App.NewPluginAPI(th.Context, manifest)
}
func (th *TestHelper) InitBasic() *TestHelper {
th.SystemAdminUser, _ = th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SystemAdminRoleId})
func (th *TestHelper) InitBasic(tb testing.TB) *TestHelper {
tb.Helper()
user, _ := th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SystemUserRoleId})
var appErr *model.AppError
th.SystemAdminUser, appErr = th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SystemAdminRoleId})
require.Nil(tb, appErr)
team, _ := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: user.Email, Type: model.TeamOpen})
th.BasicUser, appErr = th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SystemUserRoleId})
require.Nil(tb, appErr)
th.App.JoinUserToTeam(th.Context, team, user, "")
th.BasicTeam, appErr = th.App.CreateTeam(th.Context, &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: th.BasicUser.Email, Type: model.TeamOpen})
require.Nil(tb, appErr)
channel, _ := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id, CreatorId: user.Id}, true)
_, appErr = th.App.JoinUserToTeam(th.Context, th.BasicTeam, th.BasicUser, "")
require.Nil(tb, appErr)
th.BasicUser = user
th.BasicChannel = channel
th.BasicTeam = team
th.BasicChannel, appErr = th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id}, true)
require.Nil(tb, appErr)
return th
}
func (th *TestHelper) TearDown() {
if th.IncludeCacheLayer {
// Clean all the caches
th.App.Srv().InvalidateAllCaches()
}
th.Server.Shutdown()
}
func TestStaticFilesRequest(t *testing.T) {
th := Setup(t).InitPlugins()
defer th.TearDown()
pluginID := "com.mattermost.sample"
@@ -223,7 +224,8 @@ func TestStaticFilesRequest(t *testing.T) {
// Write the plugin.json manifest
pluginManifest := `{"id": "com.mattermost.sample", "server": {"executable": "backend.exe"}, "webapp": {"bundle_path":"main.js"}, "settings_schema": {"settings": []}}`
os.WriteFile(filepath.Join(pluginDir, "plugin.json"), []byte(pluginManifest), 0600)
err = os.WriteFile(filepath.Join(pluginDir, "plugin.json"), []byte(pluginManifest), 0600)
require.NoError(t, err)
// Activate the plugin
manifest, activated, reterr := th.App.GetPluginsEnvironment().Activate(pluginID)
@@ -232,7 +234,8 @@ func TestStaticFilesRequest(t *testing.T) {
require.True(t, activated)
// Verify access to the bundle with requisite headers
req, _ := http.NewRequest("GET", "/static/plugins/com.mattermost.sample/com.mattermost.sample_724ed0e2ebb2b841_bundle.js", nil)
req, err := http.NewRequest("GET", "/static/plugins/com.mattermost.sample/com.mattermost.sample_724ed0e2ebb2b841_bundle.js", nil)
require.NoError(t, err)
res := httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
assert.Equal(t, http.StatusOK, res.Code)
@@ -241,7 +244,8 @@ func TestStaticFilesRequest(t *testing.T) {
// Verify cached access to the bundle with an If-Modified-Since timestamp in the future
future := time.Now().Add(24 * time.Hour)
req, _ = http.NewRequest("GET", "/static/plugins/com.mattermost.sample/com.mattermost.sample_724ed0e2ebb2b841_bundle.js", nil)
req, err = http.NewRequest("GET", "/static/plugins/com.mattermost.sample/com.mattermost.sample_724ed0e2ebb2b841_bundle.js", nil)
require.NoError(t, err)
req.Header.Add("If-Modified-Since", future.Format(time.RFC850))
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
@@ -251,7 +255,8 @@ func TestStaticFilesRequest(t *testing.T) {
// Verify access to the bundle with an If-Modified-Since timestamp in the past
past := time.Now().Add(-24 * time.Hour)
req, _ = http.NewRequest("GET", "/static/plugins/com.mattermost.sample/com.mattermost.sample_724ed0e2ebb2b841_bundle.js", nil)
req, err = http.NewRequest("GET", "/static/plugins/com.mattermost.sample/com.mattermost.sample_724ed0e2ebb2b841_bundle.js", nil)
require.NoError(t, err)
req.Header.Add("If-Modified-Since", past.Format(time.RFC850))
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
@@ -260,7 +265,8 @@ func TestStaticFilesRequest(t *testing.T) {
assert.Equal(t, []string{"max-age=31556926, public"}, res.Result().Header[http.CanonicalHeaderKey("Cache-Control")])
// Verify handling of 404.
req, _ = http.NewRequest("GET", "/static/plugins/com.mattermost.sample/404.js", nil)
req, err = http.NewRequest("GET", "/static/plugins/com.mattermost.sample/404.js", nil)
require.NoError(t, err)
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
assert.Equal(t, http.StatusNotFound, res.Code)
@@ -270,7 +276,6 @@ func TestStaticFilesRequest(t *testing.T) {
func TestPublicFilesRequest(t *testing.T) {
th := Setup(t).InitPlugins()
defer th.TearDown()
pluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err)
@@ -306,12 +311,14 @@ func TestPublicFilesRequest(t *testing.T) {
// Write the plugin.json manifest
pluginManifest := `{"id": "com.mattermost.sample", "server": {"executable": "backend.exe"}, "settings_schema": {"settings": []}}`
os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(pluginManifest), 0600)
err = os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(pluginManifest), 0600)
require.NoError(t, err)
// Write the test public file
helloHTML := `Hello from the static files public folder for the com.mattermost.sample plugin!`
htmlFolderPath := filepath.Join(pluginDir, pluginID, "public")
os.MkdirAll(htmlFolderPath, os.ModePerm)
err = os.MkdirAll(htmlFolderPath, os.ModePerm)
require.NoError(t, err)
htmlFilePath := filepath.Join(htmlFolderPath, "hello.html")
htmlFileErr := os.WriteFile(htmlFilePath, []byte(helloHTML), 0600)
@@ -328,17 +335,20 @@ func TestPublicFilesRequest(t *testing.T) {
th.App.Channels().SetPluginsEnvironment(env)
req, _ := http.NewRequest("GET", "/plugins/com.mattermost.sample/public/hello.html", nil)
req, err := http.NewRequest("GET", "/plugins/com.mattermost.sample/public/hello.html", nil)
require.NoError(t, err)
res := httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
assert.Equal(t, helloHTML, res.Body.String())
req, _ = http.NewRequest("GET", "/plugins/com.mattermost.sample/nefarious-file-access.html", nil)
req, err = http.NewRequest("GET", "/plugins/com.mattermost.sample/nefarious-file-access.html", nil)
require.NoError(t, err)
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
assert.Equal(t, 404, res.Code)
req, _ = http.NewRequest("GET", "/plugins/com.mattermost.sample/public/../nefarious-file-access.html", nil)
req, err = http.NewRequest("GET", "/plugins/com.mattermost.sample/public/../nefarious-file-access.html", nil)
require.NoError(t, err)
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
assert.Equal(t, 301, res.Code)
@@ -360,9 +370,9 @@ func TestStatic(t *testing.T) {
func TestStaticFilesCaching(t *testing.T) {
th := Setup(t).InitPlugins()
defer th.TearDown()
wd, _ := os.Getwd()
wd, err := os.Getwd()
require.NoError(t, err)
cmd := exec.Command("ls", path.Join(wd, "client", "plugins"))
cmd.Stdout = os.Stdout
cmd.Run()
@@ -376,7 +386,7 @@ func TestStaticFilesCaching(t *testing.T) {
fakeMainBundle := `module.exports = 'main';`
fakeRemoteEntry := `module.exports = 'remote';`
err := os.WriteFile("./client/root.html", []byte(fakeRootHTML), 0600)
err = os.WriteFile("./client/root.html", []byte(fakeRootHTML), 0600)
require.NoError(t, err)
err = os.WriteFile("./client/"+fakeMainBundleName, []byte(fakeMainBundle), 0600)
require.NoError(t, err)
@@ -388,7 +398,8 @@ func TestStaticFilesCaching(t *testing.T) {
err = os.WriteFile("./client/products/boards/remote_entry.js", []byte(fakeRemoteEntry), 0600)
require.NoError(t, err)
req, _ := http.NewRequest("GET", "/", nil)
req, err := http.NewRequest("GET", "/", nil)
require.NoError(t, err)
res := httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
require.Equal(t, http.StatusOK, res.Code)
@@ -396,28 +407,32 @@ func TestStaticFilesCaching(t *testing.T) {
require.Equal(t, []string{"no-cache, max-age=31556926, public"}, res.Result().Header[http.CanonicalHeaderKey("Cache-Control")])
// Checking for HEAD method as well.
req, _ = http.NewRequest(http.MethodHead, "/", nil)
req, err = http.NewRequest(http.MethodHead, "/", nil)
require.NoError(t, err)
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
require.Equal(t, http.StatusOK, res.Code)
require.Equal(t, fakeRootHTML, res.Body.String())
require.Equal(t, []string{"no-cache, max-age=31556926, public"}, res.Result().Header[http.CanonicalHeaderKey("Cache-Control")])
req, _ = http.NewRequest("GET", "/static/"+fakeMainBundleName, nil)
req, err = http.NewRequest("GET", "/static/"+fakeMainBundleName, nil)
require.NoError(t, err)
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
require.Equal(t, http.StatusOK, res.Code)
require.Equal(t, fakeMainBundle, res.Body.String())
require.Equal(t, []string{"max-age=31556926, public"}, res.Result().Header[http.CanonicalHeaderKey("Cache-Control")])
req, _ = http.NewRequest("GET", "/static/remote_entry.js", nil)
req, err = http.NewRequest("GET", "/static/remote_entry.js", nil)
require.NoError(t, err)
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
require.Equal(t, http.StatusOK, res.Code)
require.Equal(t, fakeRemoteEntry, res.Body.String())
require.Equal(t, []string{"no-cache, max-age=31556926, public"}, res.Result().Header[http.CanonicalHeaderKey("Cache-Control")])
req, _ = http.NewRequest("GET", "/static/products/boards/remote_entry.js", nil)
req, err = http.NewRequest("GET", "/static/products/boards/remote_entry.js", nil)
require.NoError(t, err)
res = httptest.NewRecorder()
th.Web.MainRouter.ServeHTTP(res, req)
require.Equal(t, http.StatusOK, res.Code)

Просмотреть файл

@@ -17,8 +17,7 @@ import (
)
func TestIncomingWebhook(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th := Setup(t).InitBasic(t)
if !*th.App.Config().ServiceSettings.EnableIncomingWebhooks {
_, err := http.Post(apiClient.URL+"/hooks/123", "", strings.NewReader("123"))
@@ -238,8 +237,7 @@ func TestIncomingWebhook(t *testing.T) {
}
func TestCommandWebhooks(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th := Setup(t).InitBasic(t)
cmd, appErr := th.App.CreateCommand(&model.Command{
CreatorId: th.BasicUser.Id,