From aad25be4e148a271287e1c730f88ffdb9c0f085b Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Fri, 6 Oct 2023 22:43:21 +0200 Subject: [PATCH] [MM-54434] Use job.Logger to capture ldap logs (#24493) --- server/channels/api4/command_test.go | 4 +- server/channels/api4/ldap.go | 2 +- server/channels/api4/saml.go | 2 +- server/channels/api4/system.go | 2 +- server/channels/api4/team_test.go | 7 +- server/channels/api4/user.go | 14 +-- server/channels/api4/user_test.go | 15 +-- server/channels/app/app_iface.go | 26 ++--- server/channels/app/channels.go | 4 +- server/channels/app/enterprise_test.go | 7 +- server/channels/app/import_test.go | 3 +- server/channels/app/job_test.go | 16 +-- server/channels/app/ldap.go | 20 ++-- server/channels/app/login.go | 6 +- server/channels/app/notify_admin_test.go | 37 +++--- server/channels/app/oauth.go | 32 +++--- server/channels/app/oauth_test.go | 40 +++---- .../app/oauthproviders/gitlab/gitlab.go | 16 +-- .../app/opentracing/opentracing_layer.go | 52 ++++----- server/channels/app/plugin_commands_test.go | 10 +- server/channels/app/plugin_test.go | 4 +- server/channels/app/saml.go | 5 +- server/channels/app/support_packet.go | 2 +- server/channels/app/support_packet_test.go | 33 +++--- server/channels/app/team_test.go | 11 +- server/channels/app/user.go | 14 +-- server/channels/app/user_test.go | 16 +-- server/channels/jobs/jobs_test.go | 2 +- .../channels/jobs/migrations/helper_test.go | 3 +- .../jobs/migrations/migrations_test.go | 3 +- server/channels/web/oauth.go | 8 +- server/channels/web/oauth_test.go | 9 +- server/channels/web/saml.go | 8 +- server/cmd/mmctl/commands/export_e2e_test.go | 24 ++-- server/cmd/mmctl/commands/extract_e2e_test.go | 13 +-- server/cmd/mmctl/commands/import_e2e_test.go | 13 +-- server/cmd/mmctl/commands/ldap_e2e_test.go | 8 +- server/einterfaces/account_migration.go | 2 +- server/einterfaces/ldap.go | 20 ++-- .../mocks/AccountMigrationInterface.go | 10 +- server/einterfaces/mocks/LdapInterface.go | 108 +++++++++--------- .../mocks/NotificationInterface.go | 19 +-- server/einterfaces/mocks/OAuthProvider.go | 66 +++++------ server/einterfaces/mocks/SamlInterface.go | 56 ++++----- server/einterfaces/notification.go | 3 +- server/einterfaces/oauthproviders.go | 9 +- server/einterfaces/saml.go | 8 +- .../services/slackimport/slackimport_test.go | 3 +- server/public/model/user.go | 4 +- server/public/model/user_test.go | 12 +- 50 files changed, 385 insertions(+), 426 deletions(-) diff --git a/server/channels/api4/command_test.go b/server/channels/api4/command_test.go index 48b865196f..d263be60ac 100644 --- a/server/channels/api4/command_test.go +++ b/server/channels/api4/command_test.go @@ -17,7 +17,6 @@ import ( "github.com/mattermost/mattermost/server/public/model" "github.com/mattermost/mattermost/server/public/shared/mlog" - "github.com/mattermost/mattermost/server/public/shared/request" ) func TestCreateCommand(t *testing.T) { @@ -1070,7 +1069,6 @@ func TestExecuteCommandInTeamUserIsNotOn(t *testing.T) { func TestExecuteCommandReadOnly(t *testing.T) { th := Setup(t).InitBasic() - ctx := request.EmptyContext(th.TestLogger) defer th.TearDown() client := th.Client @@ -1128,7 +1126,7 @@ func TestExecuteCommandReadOnly(t *testing.T) { th.App.SetPhase2PermissionsMigrationStatus(true) _, appErr = th.App.PatchChannelModerationsForChannel( - ctx, + th.Context, th.BasicChannel, []*model.ChannelModerationPatch{{ Name: &model.PermissionCreatePost.Id, diff --git a/server/channels/api4/ldap.go b/server/channels/api4/ldap.go index 7312802785..b22fa318f5 100644 --- a/server/channels/api4/ldap.go +++ b/server/channels/api4/ldap.go @@ -306,7 +306,7 @@ func migrateIdLdap(c *Context, w http.ResponseWriter, r *http.Request) { return } - if err := c.App.MigrateIdLDAP(toAttribute); err != nil { + if err := c.App.MigrateIdLDAP(c.AppContext, toAttribute); err != nil { c.Err = err return } diff --git a/server/channels/api4/saml.go b/server/channels/api4/saml.go index 4a2e4a2452..dc404c985d 100644 --- a/server/channels/api4/saml.go +++ b/server/channels/api4/saml.go @@ -38,7 +38,7 @@ func (api *API) InitSamlLocal() { } func getSamlMetadata(c *Context, w http.ResponseWriter, r *http.Request) { - metadata, err := c.App.GetSamlMetadata() + metadata, err := c.App.GetSamlMetadata(c.AppContext) if err != nil { c.Err = err return diff --git a/server/channels/api4/system.go b/server/channels/api4/system.go index 2ff8c80e75..ffca1df59e 100644 --- a/server/channels/api4/system.go +++ b/server/channels/api4/system.go @@ -661,7 +661,7 @@ func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) { return } - msg, appError := notificationInterface.GetNotificationMessage(&ack, c.AppContext.Session().UserId) + msg, appError := notificationInterface.GetNotificationMessage(c.AppContext, &ack, c.AppContext.Session().UserId) if appError != nil { c.Err = model.NewAppError("pushNotificationAck", "api.push_notification.id_loaded.fetch.app_error", nil, appError.Error(), http.StatusInternalServerError) return diff --git a/server/channels/api4/team_test.go b/server/channels/api4/team_test.go index 02bf1aca75..be7c6e2303 100644 --- a/server/channels/api4/team_test.go +++ b/server/channels/api4/team_test.go @@ -20,7 +20,6 @@ import ( "github.com/mattermost/mattermost/server/public/model" "github.com/mattermost/mattermost/server/public/plugin/plugintest/mock" "github.com/mattermost/mattermost/server/public/shared/i18n" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/app" "github.com/mattermost/mattermost/server/v8/channels/utils/testutils" "github.com/mattermost/mattermost/server/v8/einterfaces/mocks" @@ -3196,14 +3195,12 @@ func TestValidateUserPermissionsOnChannels(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) - t.Run("User WITH permissions on private channel CAN invite members to it", func(t *testing.T) { channelIds := []string{th.BasicChannel.Id, th.BasicPrivateChannel.Id} require.Len(t, channelIds, 2) - channelIds = th.App.ValidateUserPermissionsOnChannels(ctx, th.BasicUser.Id, channelIds) + channelIds = th.App.ValidateUserPermissionsOnChannels(th.Context, th.BasicUser.Id, channelIds) // basicUser has permission onBasicChannel and BasicPrivateChannel so he can invite to both channels require.Len(t, channelIds, 2) @@ -3215,7 +3212,7 @@ func TestValidateUserPermissionsOnChannels(t *testing.T) { require.Len(t, channelIds, 2) - channelIds = th.App.ValidateUserPermissionsOnChannels(ctx, th.BasicUser.Id, channelIds) + channelIds = th.App.ValidateUserPermissionsOnChannels(th.Context, th.BasicUser.Id, channelIds) // basicUser DOES NOT have permission on BasicPrivateChannel2 so he can only invite to BasicChannel require.Len(t, channelIds, 1) diff --git a/server/channels/api4/user.go b/server/channels/api4/user.go index 145070a471..900a85b7de 100644 --- a/server/channels/api4/user.go +++ b/server/channels/api4/user.go @@ -1287,7 +1287,7 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { } // Check that the fields being updated are not set by the login provider - conflictField := c.App.CheckProviderAttributes(ouser, user.ToPatch()) + conflictField := c.App.CheckProviderAttributes(c.AppContext, ouser, user.ToPatch()) if conflictField != "" { c.Err = model.NewAppError( "updateUser", "api.user.update_user.login_provider_attribute_set.app_error", @@ -1363,7 +1363,7 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { } } - conflictField := c.App.CheckProviderAttributes(ouser, &patch) + conflictField := c.App.CheckProviderAttributes(c.AppContext, ouser, &patch) if conflictField != "" { c.Err = model.NewAppError( "patchUser", "api.user.patch_user.login_provider_attribute_set.app_error", @@ -2347,7 +2347,7 @@ func sendVerificationEmail(c *Context, w http.ResponseWriter, r *http.Request) { audit.AddEventParameter(auditRec, "email", email) audit.AddEventParameter(auditRec, "redirect", redirect) - user, err := c.App.GetUserForLogin("", email) + user, err := c.App.GetUserForLogin(c.AppContext, "", email) if err != nil { // Don't want to leak whether the email is valid or not ReturnStatusOK(w) @@ -2381,7 +2381,7 @@ func switchAccountType(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError if switchRequest.EmailToOAuth() { - link, err = c.App.SwitchEmailToOAuth(w, r, switchRequest.Email, switchRequest.Password, switchRequest.MfaCode, switchRequest.NewService) + link, err = c.App.SwitchEmailToOAuth(c.AppContext, w, r, switchRequest.Email, switchRequest.Password, switchRequest.MfaCode, switchRequest.NewService) } else if switchRequest.OAuthToEmail() { c.SessionRequired() if c.Err != nil { @@ -2390,9 +2390,9 @@ func switchAccountType(c *Context, w http.ResponseWriter, r *http.Request) { link, err = c.App.SwitchOAuthToEmail(switchRequest.Email, switchRequest.NewPassword, c.AppContext.Session().UserId) } else if switchRequest.EmailToLdap() { - link, err = c.App.SwitchEmailToLdap(switchRequest.Email, switchRequest.Password, switchRequest.MfaCode, switchRequest.LdapLoginId, switchRequest.NewPassword) + link, err = c.App.SwitchEmailToLdap(c.AppContext, switchRequest.Email, switchRequest.Password, switchRequest.MfaCode, switchRequest.LdapLoginId, switchRequest.NewPassword) } else if switchRequest.LdapToEmail() { - link, err = c.App.SwitchLdapToEmail(switchRequest.Password, switchRequest.MfaCode, switchRequest.Email, switchRequest.NewPassword) + link, err = c.App.SwitchLdapToEmail(c.AppContext, switchRequest.Password, switchRequest.MfaCode, switchRequest.Email, switchRequest.NewPassword) } else { c.SetInvalidParam("switch_request") return @@ -3131,7 +3131,7 @@ func migrateAuthToSaml(c *Context, w http.ResponseWriter, r *http.Request) { } if migrate := c.App.AccountMigration(); migrate != nil { - if err := migrate.MigrateToSaml(from, usersMap, auto, false); err != nil { + if err := migrate.MigrateToSaml(c.AppContext, from, usersMap, auto, false); err != nil { c.Err = model.NewAppError("api.migrateAuthToSaml", "api.migrate_to_saml.error", nil, err.Error(), http.StatusInternalServerError) return } diff --git a/server/channels/api4/user_test.go b/server/channels/api4/user_test.go index e2e65cf7ac..a9c0520824 100644 --- a/server/channels/api4/user_test.go +++ b/server/channels/api4/user_test.go @@ -7328,9 +7328,10 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { ldapMock := &mocks.LdapInterface{} ldapMock.Mock.On( "CheckProviderAttributes", - mock.Anything, // app.AppIface - mock.Anything, // *model.User - mock.Anything, // *model.Patch + mock.AnythingOfType("*request.Context"), + mock.AnythingOfType("*model.LdapSettings"), + mock.AnythingOfType("*model.User"), + mock.AnythingOfType("*model.UserPatch"), ).Return("") th.App.Channels().Ldap = ldapMock // CheckProviderAttributes should be called for both Patch and Update @@ -7351,7 +7352,7 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { user := th.CreateUserWithAuth(model.UserAuthServiceSaml) ldapMock := &mocks.LdapInterface{} ldapMock.Mock.On( - "CheckProviderAttributes", mock.Anything, mock.Anything, mock.Anything, + "CheckProviderAttributes", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("*model.LdapSettings"), mock.AnythingOfType("*model.User"), mock.AnythingOfType("*model.UserPatch"), ).Return("") th.App.Channels().Ldap = ldapMock th.SystemAdminClient.PatchUser(context.Background(), user.Id, &model.UserPatch{}) @@ -7365,7 +7366,7 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { user := th.CreateUserWithAuth(model.UserAuthServiceSaml) samlMock := &mocks.SamlInterface{} samlMock.Mock.On( - "CheckProviderAttributes", mock.Anything, mock.Anything, mock.Anything, + "CheckProviderAttributes", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("*model.SamlSettings"), mock.AnythingOfType("*model.User"), mock.AnythingOfType("*model.UserPatch"), ).Return("") th.App.Channels().Saml = samlMock th.SystemAdminClient.PatchUser(context.Background(), user.Id, &model.UserPatch{}) @@ -7385,7 +7386,7 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { } { patch := user.ToPatch() patch.SetField(fieldName, "something new") - conflictField := th.App.CheckProviderAttributes(user, patch) + conflictField := th.App.CheckProviderAttributes(th.Context, user, patch) require.NotEqual(t, "", conflictField) } }) @@ -7400,7 +7401,7 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { } { user := th.CreateUserWithAuth(authService) patch := &model.UserPatch{Username: model.NewString("something new")} - conflictField := th.App.CheckProviderAttributes(user, patch) + conflictField := th.App.CheckProviderAttributes(th.Context, user, patch) require.NotEqual(t, "", conflictField) } }) diff --git a/server/channels/app/app_iface.go b/server/channels/app/app_iface.go index 4bffa50df6..9a822ab8cf 100644 --- a/server/channels/app/app_iface.go +++ b/server/channels/app/app_iface.go @@ -75,7 +75,7 @@ type AppIface interface { // CheckProviderAttributes returns the empty string if the patch can be applied without // overriding attributes set by the user's login provider; otherwise, the name of the offending // field is returned. - CheckProviderAttributes(user *model.User, patch *model.UserPatch) string + CheckProviderAttributes(c *request.Context, user *model.User, patch *model.UserPatch) string // CommandsForTeam returns all the plugin and product commands for the given team. CommandsForTeam(teamID string) []*model.Command // ComputeLastAccessibleFileTime updates cache with CreateAt time of the last accessible file as per the cloud plan's limit. @@ -431,7 +431,7 @@ type AppIface interface { AttachDeviceId(sessionID string, deviceID string, expiresAt int64) *model.AppError AttachSessionCookies(c *request.Context, w http.ResponseWriter, r *http.Request) AuthenticateUserForLogin(c *request.Context, id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) - AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) + AuthorizeOAuthUser(c *request.Context, w http.ResponseWriter, r *http.Request, service, code, state, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) AutocompleteChannels(c request.CTX, userID, term string) (model.ChannelListWithTeamData, *model.AppError) AutocompleteChannelsForSearch(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) AutocompleteChannelsForTeam(c request.CTX, teamID, userID, term string) (model.ChannelList, *model.AppError) @@ -474,7 +474,7 @@ type AppIface interface { CompareAndSetPluginKey(pluginID string, key string, oldValue, newValue []byte) (bool, *model.AppError) CompleteOAuth(c *request.Context, service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError) CompleteOnboarding(c *request.Context, request *model.CompleteOnboardingRequest) *model.AppError - CompleteSwitchWithOAuth(service string, userData io.Reader, email string, tokenUser *model.User) (*model.User, *model.AppError) + CompleteSwitchWithOAuth(c *request.Context, service string, userData io.Reader, email string, tokenUser *model.User) (*model.User, *model.AppError) Compliance() einterfaces.ComplianceInterface Config() *model.Config ConvertGroupMessageToChannel(c request.CTX, convertedByUserId string, gmConversionRequest *model.GroupMessageConversionRequestBody) (*model.Channel, *model.AppError) @@ -599,7 +599,7 @@ type AppIface interface { GetAppliedSchemaMigrations() ([]model.AppliedMigration, *model.AppError) GetAudits(userID string, limit int) (model.Audits, *model.AppError) GetAuditsPage(userID string, page int, perPage int) (model.Audits, *model.AppError) - GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) + GetAuthorizationCode(c *request.Context, w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) GetAuthorizedAppsForUser(userID string, page, perPage int) ([]*model.OAuthApp, *model.AppError) GetBrandImage() ([]byte, *model.AppError) GetBulkReactionsForPosts(postIDs []string) (map[string][]*model.Reaction, *model.AppError) @@ -703,8 +703,8 @@ type AppIface interface { GetOAuthAppsByCreator(userID string, page, perPage int) ([]*model.OAuthApp, *model.AppError) GetOAuthCodeRedirect(userID string, authRequest *model.AuthorizeRequest) (string, *model.AppError) GetOAuthImplicitRedirect(userID string, authRequest *model.AuthorizeRequest) (string, *model.AppError) - GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service, teamID, action, redirectTo, loginHint string, isMobile bool, desktopToken string) (string, *model.AppError) - GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamID string, desktopToken string) (string, *model.AppError) + GetOAuthLoginEndpoint(c *request.Context, w http.ResponseWriter, r *http.Request, service, teamID, action, redirectTo, loginHint string, isMobile bool, desktopToken string) (string, *model.AppError) + GetOAuthSignupEndpoint(c *request.Context, w http.ResponseWriter, r *http.Request, service, teamID string, desktopToken string) (string, *model.AppError) GetOAuthStateToken(token string) (*model.Token, *model.AppError) GetOnboarding() (*model.System, *model.AppError) GetOpenGraphMetadata(requestURL string) ([]byte, error) @@ -759,7 +759,7 @@ type AppIface interface { GetRoleByName(ctx context.Context, name string) (*model.Role, *model.AppError) GetRolesByNames(names []string) ([]*model.Role, *model.AppError) GetSamlCertificateStatus() *model.SamlCertificateStatus - GetSamlMetadata() (string, *model.AppError) + GetSamlMetadata(c *request.Context) (string, *model.AppError) GetSamlMetadataFromIdp(idpMetadataURL string) (*model.SamlMetadataResponse, *model.AppError) GetSanitizeOptions(asAdmin bool) map[string]bool GetScheme(id string) (*model.Scheme, *model.AppError) @@ -823,7 +823,7 @@ type AppIface interface { GetUserByEmail(email string) (*model.User, *model.AppError) GetUserByRemoteID(remoteID string) (*model.User, *model.AppError) GetUserByUsername(username string) (*model.User, *model.AppError) - GetUserForLogin(id, loginId string) (*model.User, *model.AppError) + GetUserForLogin(c *request.Context, id, loginId string) (*model.User, *model.AppError) GetUserTermsOfService(userID string) (*model.UserTermsOfService, *model.AppError) GetUsers(userIDs []string) ([]*model.User, *model.AppError) GetUsersByGroupChannelIds(c *request.Context, channelIDs []string, asAdmin bool) (map[string][]*model.User, *model.AppError) @@ -918,7 +918,7 @@ type AppIface interface { MaxPostSize() int MessageExport() einterfaces.MessageExportInterface Metrics() einterfaces.MetricsInterface - MigrateIdLDAP(toAttribute string) *model.AppError + MigrateIdLDAP(c *request.Context, toAttribute string) *model.AppError MoveCommand(team *model.Team, command *model.Command) *model.AppError MoveFile(oldPath, newPath string) *model.AppError NewPluginAPI(c *request.Context, manifest *model.Manifest) plugin.API @@ -1094,9 +1094,9 @@ type AppIface interface { SoftDeleteTeam(teamID string) *model.AppError Srv() *Server SubmitInteractiveDialog(c *request.Context, request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) - SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) - SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) - SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError) + SwitchEmailToLdap(c *request.Context, email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) + SwitchEmailToOAuth(c *request.Context, w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) + SwitchLdapToEmail(c *request.Context, ldapPassword, code, email, newPassword string) (string, *model.AppError) SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError) TeamMembersToRemove(teamID *string) ([]*model.TeamMember, *model.AppError) TelemetryId() string @@ -1129,7 +1129,7 @@ type AppIface interface { UpdateMfa(c request.CTX, activate bool, userID, token string) *model.AppError UpdateMobileAppBadge(userID string) UpdateOAuthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) - UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError + UpdateOAuthUserAttrs(c *request.Context, userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError UpdateOutgoingWebhook(c request.CTX, oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) UpdatePassword(user *model.User, newPassword string) *model.AppError UpdatePasswordAsUser(c request.CTX, userID, currentPassword, newPassword string) *model.AppError diff --git a/server/channels/app/channels.go b/server/channels/app/channels.go index b134adf888..1048b8614c 100644 --- a/server/channels/app/channels.go +++ b/server/channels/app/channels.go @@ -181,12 +181,12 @@ func NewChannels(services map[product.ServiceKey]any) (*Channels, error) { } if samlInterfaceNew != nil { ch.Saml = samlInterfaceNew(New(ServerConnector(ch))) - if err := ch.Saml.ConfigureSP(); err != nil { + if err := ch.Saml.ConfigureSP(request.EmptyContext(s.Log())); err != nil { s.Log().Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) } ch.AddConfigListener(func(_, _ *model.Config) { - if err := ch.Saml.ConfigureSP(); err != nil { + if err := ch.Saml.ConfigureSP(request.EmptyContext(s.Log())); err != nil { s.Log().Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) } }) diff --git a/server/channels/app/enterprise_test.go b/server/channels/app/enterprise_test.go index 1594ee2eb1..738d0c3e0b 100644 --- a/server/channels/app/enterprise_test.go +++ b/server/channels/app/enterprise_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/mattermost/mattermost/server/public/model" + "github.com/mattermost/mattermost/server/public/shared/request" storemocks "github.com/mattermost/mattermost/server/v8/channels/store/storetest/mocks" "github.com/mattermost/mattermost/server/v8/einterfaces" "github.com/mattermost/mattermost/server/v8/einterfaces/mocks" @@ -54,8 +55,8 @@ func TestSAMLSettings(t *testing.T) { for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { saml2 := &mocks.SamlInterface{} - saml2.Mock.On("ConfigureSP").Return(nil) - saml2.Mock.On("GetMetadata").Return("samlTwo", nil) + saml2.Mock.On("ConfigureSP", mock.AnythingOfType("*request.Context")).Return(nil) + saml2.Mock.On("GetMetadata", mock.AnythingOfType("*request.Context")).Return("samlTwo", nil) if tc.setNewInterface { RegisterNewSamlInterface(func(_ *App) einterfaces.SamlInterface { return saml2 @@ -93,7 +94,7 @@ func TestSAMLSettings(t *testing.T) { assert.Nil(t, th.App.Channels().Saml) } else { assert.NotNil(t, th.App.Channels().Saml) - metadata, err := th.App.Channels().Saml.GetMetadata() + metadata, err := th.App.Channels().Saml.GetMetadata(request.TestContext(t)) assert.Nil(t, err) assert.Equal(t, tc.metadata, metadata) } diff --git a/server/channels/app/import_test.go b/server/channels/app/import_test.go index df209fb8e0..caaa287b94 100644 --- a/server/channels/app/import_test.go +++ b/server/channels/app/import_test.go @@ -17,7 +17,6 @@ import ( "github.com/stretchr/testify/require" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/mlog" "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/app/imports" "github.com/mattermost/mattermost/server/v8/channels/utils" @@ -287,7 +286,7 @@ func AssertFileIdsInPost(files []*model.FileInfo, th *TestHelper, t *testing.T) } func TestProcessAttachments(t *testing.T) { - c := request.EmptyContext(mlog.CreateConsoleTestLogger(t)) + c := request.TestContext(t) genAttachments := func() *[]imports.AttachmentImportData { return &[]imports.AttachmentImportData{ diff --git a/server/channels/app/job_test.go b/server/channels/app/job_test.go index c7911a61f8..cb7edcddf8 100644 --- a/server/channels/app/job_test.go +++ b/server/channels/app/job_test.go @@ -11,14 +11,12 @@ import ( "github.com/stretchr/testify/require" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/store/sqlstore" ) func TestGetJob(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) status := &model.Job{ Id: model.NewId(), @@ -31,7 +29,7 @@ func TestGetJob(t *testing.T) { defer th.App.Srv().Store().Job().Delete(status.Id) - received, appErr := th.App.GetJob(ctx, status.Id) + received, appErr := th.App.GetJob(th.Context, status.Id) require.Nil(t, appErr) require.Equal(t, status, received, "incorrect job status received") } @@ -220,7 +218,6 @@ func TestSessionHasPermissionToReadJob(t *testing.T) { func TestGetJobByType(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) jobType := model.NewId() @@ -250,13 +247,13 @@ func TestGetJobByType(t *testing.T) { defer th.App.Srv().Store().Job().Delete(status.Id) } - received, err := th.App.GetJobsByType(ctx, jobType, 0, 2) + received, err := th.App.GetJobsByType(th.Context, jobType, 0, 2) require.Nil(t, err) require.Len(t, received, 2, "received wrong number of statuses") require.Equal(t, statuses[2], received[0], "should've received newest job first") require.Equal(t, statuses[0], received[1], "should've received second newest job second") - received, err = th.App.GetJobsByType(ctx, jobType, 2, 2) + received, err = th.App.GetJobsByType(th.Context, jobType, 2, 2) require.Nil(t, err) require.Len(t, received, 1, "received wrong number of statuses") require.Equal(t, statuses[1], received[0], "should've received oldest job last") @@ -265,7 +262,6 @@ func TestGetJobByType(t *testing.T) { func TestGetJobsByTypes(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) jobType := model.NewId() jobType1 := model.NewId() @@ -298,19 +294,19 @@ func TestGetJobsByTypes(t *testing.T) { } jobTypes := []string{jobType, jobType1, jobType2} - received, err := th.App.GetJobsByTypes(ctx, jobTypes, 0, 2) + received, err := th.App.GetJobsByTypes(th.Context, jobTypes, 0, 2) require.Nil(t, err) require.Len(t, received, 2, "received wrong number of jobs") require.Equal(t, statuses[2], received[0], "should've received newest job first") require.Equal(t, statuses[0], received[1], "should've received second newest job second") - received, err = th.App.GetJobsByTypes(ctx, jobTypes, 2, 2) + received, err = th.App.GetJobsByTypes(th.Context, jobTypes, 2, 2) require.Nil(t, err) require.Len(t, received, 1, "received wrong number of jobs") require.Equal(t, statuses[1], received[0], "should've received oldest job last") jobTypes = []string{jobType1, jobType2} - received, err = th.App.GetJobsByTypes(ctx, jobTypes, 0, 3) + received, err = th.App.GetJobsByTypes(th.Context, jobTypes, 0, 3) require.Nil(t, err) require.Len(t, received, 2, "received wrong number of jobs") require.Equal(t, statuses[2], received[0], "received wrong job type") diff --git a/server/channels/app/ldap.go b/server/channels/app/ldap.go index 74f27ce1fa..de76fd7971 100644 --- a/server/channels/app/ldap.go +++ b/server/channels/app/ldap.go @@ -22,13 +22,13 @@ func (a *App) SyncLdap(c *request.Context, includeRemovedMembers bool) { if license := a.Srv().License(); license != nil && *license.Features.LDAP { if !*a.Config().LdapSettings.EnableSync { - mlog.Error("LdapSettings.EnableSync is set to false. Skipping LDAP sync.") + c.Logger().Error("LdapSettings.EnableSync is set to false. Skipping LDAP sync.") return } ldapI := a.Ldap() if ldapI == nil { - mlog.Error("Not executing ldap sync because ldap is not available") + c.Logger().Error("Not executing ldap sync because ldap is not available") return } ldapI.StartSynchronizeJob(c, false, includeRemovedMembers) @@ -89,7 +89,7 @@ func (a *App) GetAllLdapGroupsPage(page int, perPage int, opts model.LdapGroupSe return groups, total, nil } -func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) { +func (a *App) SwitchEmailToLdap(c *request.Context, email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) { if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { return "", model.NewAppError("emailToLdap", "api.user.email_to_ldap.not_available.app_error", nil, "", http.StatusForbidden) } @@ -112,20 +112,20 @@ func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword return "", model.NewAppError("SwitchEmailToLdap", "api.user.email_to_ldap.not_available.app_error", nil, "", http.StatusNotImplemented) } - if err := ldapInterface.SwitchToLdap(user.Id, ldapLoginId, ldapPassword); err != nil { + if err := ldapInterface.SwitchToLdap(c, user.Id, ldapLoginId, ldapPassword); err != nil { return "", err } a.Srv().Go(func() { if err := a.Srv().EmailService.SendSignInChangeEmail(user.Email, "AD/LDAP", user.Locale, a.GetSiteURL()); err != nil { - mlog.Error("Could not send sign in method changed e-mail", mlog.Err(err)) + c.Logger().Error("Could not send sign in method changed e-mail", mlog.Err(err)) } }) return "/login?extra=signin_change", nil } -func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError) { +func (a *App) SwitchLdapToEmail(c *request.Context, ldapPassword, code, email, newPassword string) (string, *model.AppError) { if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { return "", model.NewAppError("ldapToEmail", "api.user.ldap_to_email.not_available.app_error", nil, "", http.StatusForbidden) } @@ -144,7 +144,7 @@ func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) ( return "", model.NewAppError("SwitchLdapToEmail", "api.user.ldap_to_email.not_available.app_error", nil, "", http.StatusNotImplemented) } - if err := ldapInterface.CheckPasswordAuthData(*user.AuthData, ldapPassword); err != nil { + if err := ldapInterface.CheckPasswordAuthData(c, *user.AuthData, ldapPassword); err != nil { return "", err } @@ -164,16 +164,16 @@ func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) ( a.Srv().Go(func() { if err := a.Srv().EmailService.SendSignInChangeEmail(user.Email, T("api.templates.signin_change_email.body.method_email"), user.Locale, a.GetSiteURL()); err != nil { - mlog.Error("Could not send sign in method changed e-mail", mlog.Err(err)) + c.Logger().Error("Could not send sign in method changed e-mail", mlog.Err(err)) } }) return "/login?extra=signin_change", nil } -func (a *App) MigrateIdLDAP(toAttribute string) *model.AppError { +func (a *App) MigrateIdLDAP(c *request.Context, toAttribute string) *model.AppError { if ldapI := a.Ldap(); ldapI != nil { - if err := ldapI.MigrateIDAttribute(toAttribute); err != nil { + if err := ldapI.MigrateIDAttribute(c, toAttribute); err != nil { switch err := err.(type) { case *model.AppError: return err diff --git a/server/channels/app/login.go b/server/channels/app/login.go index fec7bb2425..868c221f7e 100644 --- a/server/channels/app/login.go +++ b/server/channels/app/login.go @@ -60,7 +60,7 @@ func (a *App) AuthenticateUserForLogin(c *request.Context, id, loginId, password } // Get the MM user we are trying to login - if user, err = a.GetUserForLogin(id, loginId); err != nil { + if user, err = a.GetUserForLogin(c, id, loginId); err != nil { return nil, err } @@ -120,7 +120,7 @@ func (a *App) AuthenticateUserForLogin(c *request.Context, id, loginId, password return user, nil } -func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) { +func (a *App) GetUserForLogin(c *request.Context, id, loginId string) (*model.User, *model.AppError) { enableUsername := *a.Config().EmailSettings.EnableSignInWithUsername enableEmail := *a.Config().EmailSettings.EnableSignInWithEmail @@ -145,7 +145,7 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) // Try to get the user with LDAP if enabled if *a.Config().LdapSettings.Enable && a.Ldap() != nil { - if ldapUser, err := a.Ldap().GetUser(loginId); err == nil { + if ldapUser, err := a.Ldap().GetUser(c, loginId); err == nil { if user, err := a.GetUserByAuth(ldapUser.AuthData, model.UserAuthServiceLdap); err == nil { return user, nil } diff --git a/server/channels/app/notify_admin_test.go b/server/channels/app/notify_admin_test.go index 88271554e9..44dbea0ff3 100644 --- a/server/channels/app/notify_admin_test.go +++ b/server/channels/app/notify_admin_test.go @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/require" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/request" ) const PluginIdGithub = "github" @@ -21,29 +20,26 @@ func Test_SendNotifyAdminPosts(t *testing.T) { t.Run("no error sending non trial upgrade post when no notifications are available", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - err := th.App.SendNotifyAdminPosts(ctx, "", "", false) + err := th.App.SendNotifyAdminPosts(th.Context, "", "", false) require.Nil(t, err) }) t.Run("no error sending trial upgrade post when no notifications are available", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - err := th.App.SendNotifyAdminPosts(ctx, "", "", true) + err := th.App.SendNotifyAdminPosts(th.Context, "", "", true) require.Nil(t, err) }) t.Run("successfully send upgrade notification", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) @@ -62,7 +58,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "test", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "test", "", false) require.Nil(t, appErr) bot, appErr := th.App.GetSystemBot() @@ -97,7 +93,6 @@ func Test_SendNotifyAdminPosts(t *testing.T) { t.Run("successfully send trial upgrade notification", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) @@ -110,7 +105,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "test", "", true) + appErr = th.App.SendNotifyAdminPosts(th.Context, "test", "", true) require.Nil(t, appErr) bot, appErr := th.App.GetSystemBot() @@ -145,7 +140,6 @@ func Test_SendNotifyAdminPosts(t *testing.T) { t.Run("successfully send install plugin notification", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) // some notifications _, appErr := th.App.SaveAdminNotifyData(&model.NotifyAdminData{ @@ -156,7 +150,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "", "", false) require.Nil(t, appErr) bot, appErr := th.App.GetSystemBot() @@ -190,7 +184,6 @@ func Test_SendNotifyAdminPosts(t *testing.T) { t.Run("persist notify admin data after sending the install plugin notification", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) // some notifications _, appErr := th.App.SaveAdminNotifyData(&model.NotifyAdminData{ @@ -201,7 +194,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "", "", false) require.Nil(t, appErr) bot, appErr := th.App.GetSystemBot() @@ -260,7 +253,6 @@ func Test_SendNotifyAdminPosts(t *testing.T) { t.Run("error when trying to send upgrade post before end of cool off period", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) @@ -272,7 +264,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "", "", false) require.Nil(t, appErr) // add some more notifications while in cool off @@ -284,7 +276,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { require.Nil(t, appErr) // second time trying to notify is forbidden - appErr = th.App.SendNotifyAdminPosts(ctx, "", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "", "", false) require.NotNil(t, appErr) require.Equal(t, appErr.Error(), "SendNotifyAdminPosts: Unable to send notification post., Cannot notify yet") }) @@ -292,7 +284,6 @@ func Test_SendNotifyAdminPosts(t *testing.T) { t.Run("can send upgrade post at the end of cool off period", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) @@ -307,7 +298,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "", "", false) require.Nil(t, appErr) // add some more notifications while in cool off @@ -321,14 +312,13 @@ func Test_SendNotifyAdminPosts(t *testing.T) { time.Sleep(5 * time.Second) // no error sending second time - appErr = th.App.SendNotifyAdminPosts(ctx, "", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "", "", false) require.Nil(t, appErr) }) t.Run("can filter notifications when plan changes within cool off period", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) @@ -349,7 +339,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "test", model.LicenseShortSkuProfessional, false) // try and send notification but workspace currentSKU has since changed to cloud-professional + appErr = th.App.SendNotifyAdminPosts(th.Context, "test", model.LicenseShortSkuProfessional, false) // try and send notification but workspace currentSKU has since changed to cloud-professional require.Nil(t, appErr) bot, appErr := th.App.GetSystemBot() @@ -384,7 +374,6 @@ func Test_SendNotifyAdminPosts(t *testing.T) { t.Run("correctly send upgrade and install plugin post with the correct user request", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) os.Setenv("MM_NOTIFY_ADMIN_COOL_OFF_DAYS", "0") defer os.Unsetenv("MM_NOTIFY_ADMIN_COOL_OFF_DAYS") @@ -399,7 +388,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { Trial: false, }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "test", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "test", "", false) require.Nil(t, appErr) // some notifications @@ -410,7 +399,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { Trial: false, }) require.Nil(t, appErr) - appErr = th.App.SendNotifyAdminPosts(ctx, "test", "", false) + appErr = th.App.SendNotifyAdminPosts(th.Context, "test", "", false) require.Nil(t, appErr) bot, appErr := th.App.GetSystemBot() diff --git a/server/channels/app/oauth.go b/server/channels/app/oauth.go index 1be5908407..86d81abe21 100644 --- a/server/channels/app/oauth.go +++ b/server/channels/app/oauth.go @@ -431,7 +431,7 @@ func (a *App) newSessionUpdateToken(app *model.OAuthApp, accessData *model.Acces return accessRsp, nil } -func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service, teamID, action, redirectTo, loginHint string, isMobile bool, desktopToken string) (string, *model.AppError) { +func (a *App) GetOAuthLoginEndpoint(c *request.Context, w http.ResponseWriter, r *http.Request, service, teamID, action, redirectTo, loginHint string, isMobile bool, desktopToken string) (string, *model.AppError) { stateProps := map[string]string{} stateProps["action"] = action if teamID != "" { @@ -448,7 +448,7 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv stateProps[model.UserAuthServiceIsMobile] = strconv.FormatBool(isMobile) - authURL, err := a.GetAuthorizationCode(w, r, service, stateProps, loginHint) + authURL, err := a.GetAuthorizationCode(c, w, r, service, stateProps, loginHint) if err != nil { return "", err } @@ -456,7 +456,7 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv return authURL, nil } -func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamID string, desktopToken string) (string, *model.AppError) { +func (a *App) GetOAuthSignupEndpoint(c *request.Context, w http.ResponseWriter, r *http.Request, service, teamID string, desktopToken string) (string, *model.AppError) { stateProps := map[string]string{} stateProps["action"] = model.OAuthActionSignup if teamID != "" { @@ -467,7 +467,7 @@ func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, ser stateProps["desktop_token"] = desktopToken } - authURL, err := a.GetAuthorizationCode(w, r, service, stateProps, "") + authURL, err := a.GetAuthorizationCode(c, w, r, service, stateProps, "") if err != nil { return "", err } @@ -574,7 +574,7 @@ func (a *App) CompleteOAuth(c *request.Context, service string, body io.ReadClos case model.OAuthActionLogin: return a.LoginByOAuth(c, service, body, teamID, tokenUser) case model.OAuthActionEmailToSSO: - return a.CompleteSwitchWithOAuth(service, body, props["email"], tokenUser) + return a.CompleteSwitchWithOAuth(c, service, body, props["email"], tokenUser) case model.OAuthActionSSOToEmail: return a.LoginByOAuth(c, service, body, teamID, tokenUser) default: @@ -611,7 +611,7 @@ func (a *App) LoginByOAuth(c *request.Context, service string, userData io.Reade map[string]any{"Service": service}, "", http.StatusBadRequest) } - authUser, err1 := provider.GetUserFromJSON(bytes.NewReader(buf.Bytes()), tokenUser) + authUser, err1 := provider.GetUserFromJSON(c, bytes.NewReader(buf.Bytes()), tokenUser) if err1 != nil { return nil, model.NewAppError("LoginByOAuth", "api.user.login_by_oauth.parse.app_error", map[string]any{"Service": service}, "", http.StatusBadRequest).Wrap(err1) @@ -637,7 +637,7 @@ func (a *App) LoginByOAuth(c *request.Context, service string, userData io.Reade return nil, model.NewAppError("loginByOAuth", "api.user.login_by_oauth.bot_login_forbidden.app_error", nil, "", http.StatusForbidden) } - if err = a.UpdateOAuthUserAttrs(bytes.NewReader(buf.Bytes()), user, provider, service, tokenUser); err != nil { + if err = a.UpdateOAuthUserAttrs(c, bytes.NewReader(buf.Bytes()), user, provider, service, tokenUser); err != nil { return nil, err } if teamID != "" { @@ -652,7 +652,7 @@ func (a *App) LoginByOAuth(c *request.Context, service string, userData io.Reade return user, nil } -func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email string, tokenUser *model.User) (*model.User, *model.AppError) { +func (a *App) CompleteSwitchWithOAuth(c *request.Context, service string, userData io.Reader, email string, tokenUser *model.User) (*model.User, *model.AppError) { provider, e := a.getSSOProvider(service) if e != nil { return nil, e @@ -662,7 +662,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email return nil, model.NewAppError("CompleteSwitchWithOAuth", "api.user.complete_switch_with_oauth.blank_email.app_error", nil, "", http.StatusBadRequest) } - ssoUser, err1 := provider.GetUserFromJSON(userData, tokenUser) + ssoUser, err1 := provider.GetUserFromJSON(c, userData, tokenUser) if err1 != nil { return nil, model.NewAppError("CompleteSwitchWithOAuth", "api.user.complete_switch_with_oauth.parse.app_error", map[string]any{"Service": service}, "", http.StatusBadRequest).Wrap(err1) @@ -730,13 +730,13 @@ func (a *App) GetOAuthStateToken(token string) (*model.Token, *model.AppError) { return mToken, nil } -func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) { +func (a *App) GetAuthorizationCode(c *request.Context, w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) { provider, e := a.getSSOProvider(service) if e != nil { return "", e } - sso, e2 := provider.GetSSOSettings(a.Config(), service) + sso, e2 := provider.GetSSOSettings(c, a.Config(), service) if e2 != nil { return "", model.NewAppError("GetAuthorizationCode.GetSSOSettings", "api.user.get_authorization_code.endpoint.app_error", nil, "", http.StatusNotImplemented).Wrap(e2) } @@ -795,13 +795,13 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi return authURL, nil } -func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) { +func (a *App) AuthorizeOAuthUser(c *request.Context, w http.ResponseWriter, r *http.Request, service, code, state, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) { provider, e := a.getSSOProvider(service) if e != nil { return nil, "", nil, nil, e } - sso, e2 := provider.GetSSOSettings(a.Config(), service) + sso, e2 := provider.GetSSOSettings(c, a.Config(), service) if e2 != nil { return nil, "", nil, nil, model.NewAppError("AuthorizeOAuthUser.GetSSOSettings", "api.user.get_authorization_code.endpoint.app_error", nil, "", http.StatusNotImplemented).Wrap(e2) } @@ -896,7 +896,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service var userFromToken *model.User if ar.IdToken != "" { - userFromToken, err = provider.GetUserFromIdToken(ar.IdToken) + userFromToken, err = provider.GetUserFromIdToken(c, ar.IdToken) if err != nil { return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.token_failed.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -939,7 +939,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service return resp.Body, teamID, stateProps, userFromToken, nil } -func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) { +func (a *App) SwitchEmailToOAuth(c *request.Context, w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) { if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { return "", model.NewAppError("emailToOAuth", "api.user.email_to_oauth.not_available.app_error", nil, "", http.StatusForbidden) } @@ -961,7 +961,7 @@ func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, return a.GetSiteURL() + "/login/sso/saml?action=" + model.OAuthActionEmailToSSO + "&email=" + utils.URLEncode(email), nil } - authURL, err := a.GetAuthorizationCode(w, r, service, stateProps, "") + authURL, err := a.GetAuthorizationCode(c, w, r, service, stateProps, "") if err != nil { return "", err } diff --git a/server/channels/app/oauth_test.go b/server/channels/app/oauth_test.go index ff61f25664..b8345f707c 100644 --- a/server/channels/app/oauth_test.go +++ b/server/channels/app/oauth_test.go @@ -186,7 +186,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { th := setup(t, false, true, true, "") defer th.TearDown() - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", "", "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, nil, nil, model.ServiceGitlab, "", "", "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.unsupported.app_error", err.Id) }) @@ -197,7 +197,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { state := "!" - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, nil, nil, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id) }) @@ -210,7 +210,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { "token": model.NewId(), }))) - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, nil, nil, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.oauth.invalid_state_token.app_error", err.Id) assert.Error(t, err.Unwrap()) @@ -225,7 +225,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { state := makeState(token) - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, nil, nil, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.oauth.invalid_state_token.app_error", err.Id) assert.Equal(t, "", err.DetailedError) @@ -248,7 +248,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { "token": token.Token, }))) - _, _, _, _, err = th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "") + _, _, _, _, err = th.App.AuthorizeOAuthUser(th.Context, nil, nil, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id) }) @@ -261,7 +261,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest("") state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, nil, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id) }) @@ -278,7 +278,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(token) - _, _, _, _, err = th.App.AuthorizeOAuthUser(nil, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err = th.App.AuthorizeOAuthUser(th.Context, nil, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id) }) @@ -291,7 +291,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, &httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.token_failed.app_error", err.Id) }) @@ -309,7 +309,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, &httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.bad_response.app_error", err.Id) assert.Contains(t, err.DetailedError, "status_code=418") @@ -328,7 +328,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, &httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.bad_response.app_error", err.Id) assert.Contains(t, err.DetailedError, "response_body=invalid") @@ -350,7 +350,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, &httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.bad_token.app_error", err.Id) }) @@ -371,7 +371,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, &httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.missing.app_error", err.Id) }) @@ -392,7 +392,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, &httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.service.app_error", err.Id) }) @@ -420,7 +420,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, &httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.response.app_error", err.Id) }) @@ -449,7 +449,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, &httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "oauth.gitlab.tos.error", err.Id) }) @@ -463,10 +463,10 @@ func TestAuthorizeOAuthUser(t *testing.T) { }) providerMock := &mocks.OAuthProvider{} - providerMock.On("GetSSOSettings", mock.Anything, model.ServiceOpenid).Return(nil, errors.New("error")) + providerMock.On("GetSSOSettings", mock.AnythingOfType("*request.Context"), mock.Anything, model.ServiceOpenid).Return(nil, errors.New("error")) einterfaces.RegisterOAuthProvider(model.ServiceOpenid, providerMock) - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceOpenid, "", "", "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(th.Context, nil, nil, model.ServiceOpenid, "", "", "") require.NotNil(t, err) assert.Equal(t, "api.user.get_authorization_code.endpoint.app_error", err.Id) @@ -517,7 +517,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { state := base64.StdEncoding.EncodeToString([]byte(model.MapToJSON(stateProps))) recorder := httptest.ResponseRecorder{} - body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.ServiceGitlab, "", state, "") + body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(th.Context, &recorder, request, model.ServiceGitlab, "", state, "") require.NotNil(t, body) bodyBytes, bodyErr := io.ReadAll(body) @@ -544,7 +544,7 @@ func TestGetAuthorizationCode(t *testing.T) { *cfg.GitLabSettings.Enable = false }) - _, err := th.App.GetAuthorizationCode(nil, nil, model.ServiceGitlab, map[string]string{}, "") + _, err := th.App.GetAuthorizationCode(th.Context, nil, nil, model.ServiceGitlab, map[string]string{}, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.unsupported.app_error", err.Id) @@ -581,7 +581,7 @@ func TestGetAuthorizationCode(t *testing.T) { } recorder := httptest.ResponseRecorder{} - url, err := th.App.GetAuthorizationCode(&recorder, request, model.ServiceGitlab, stateProps, "") + url, err := th.App.GetAuthorizationCode(th.Context, &recorder, request, model.ServiceGitlab, stateProps, "") require.Nil(t, err) assert.NotEmpty(t, url) diff --git a/server/channels/app/oauthproviders/gitlab/gitlab.go b/server/channels/app/oauthproviders/gitlab/gitlab.go index 1f7155b16d..dc1dd070f5 100644 --- a/server/channels/app/oauthproviders/gitlab/gitlab.go +++ b/server/channels/app/oauthproviders/gitlab/gitlab.go @@ -11,6 +11,8 @@ import ( "strings" "github.com/mattermost/mattermost/server/public/model" + "github.com/mattermost/mattermost/server/public/shared/mlog" + "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/einterfaces" ) @@ -30,13 +32,13 @@ func init() { einterfaces.RegisterOAuthProvider(model.UserAuthServiceGitlab, provider) } -func userFromGitLabUser(glu *GitLabUser) *model.User { +func userFromGitLabUser(logger mlog.LoggerIFace, glu *GitLabUser) *model.User { user := &model.User{} username := glu.Username if username == "" { username = glu.Login } - user.Username = model.CleanUsername(username) + user.Username = model.CleanUsername(logger, username) splitName := strings.Split(glu.Name, " ") if len(splitName) == 2 { user.FirstName = splitName[0] @@ -82,7 +84,7 @@ func (glu *GitLabUser) getAuthData() string { return strconv.FormatInt(glu.Id, 10) } -func (m *GitLabProvider) GetUserFromJSON(data io.Reader, tokenUser *model.User) (*model.User, error) { +func (m *GitLabProvider) GetUserFromJSON(c *request.Context, data io.Reader, tokenUser *model.User) (*model.User, error) { glu, err := gitLabUserFromJSON(data) if err != nil { return nil, err @@ -91,17 +93,17 @@ func (m *GitLabProvider) GetUserFromJSON(data io.Reader, tokenUser *model.User) return nil, err } - return userFromGitLabUser(glu), nil + return userFromGitLabUser(c.Logger(), glu), nil } -func (m *GitLabProvider) GetSSOSettings(config *model.Config, service string) (*model.SSOSettings, error) { +func (m *GitLabProvider) GetSSOSettings(_ *request.Context, config *model.Config, service string) (*model.SSOSettings, error) { return &config.GitLabSettings, nil } -func (m *GitLabProvider) GetUserFromIdToken(idToken string) (*model.User, error) { +func (m *GitLabProvider) GetUserFromIdToken(_ *request.Context, idToken string) (*model.User, error) { return nil, nil } -func (m *GitLabProvider) IsSameUser(dbUser, oauthUser *model.User) bool { +func (m *GitLabProvider) IsSameUser(_ *request.Context, dbUser, oauthUser *model.User) bool { return dbUser.AuthData == oauthUser.AuthData } diff --git a/server/channels/app/opentracing/opentracing_layer.go b/server/channels/app/opentracing/opentracing_layer.go index 94a91d7c8b..52fcbf5886 100644 --- a/server/channels/app/opentracing/opentracing_layer.go +++ b/server/channels/app/opentracing/opentracing_layer.go @@ -794,7 +794,7 @@ func (a *OpenTracingAppLayer) AuthenticateUserForLogin(c *request.Context, id st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service string, code string, state string, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) { +func (a *OpenTracingAppLayer) AuthorizeOAuthUser(c *request.Context, w http.ResponseWriter, r *http.Request, service string, code string, state string, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AuthorizeOAuthUser") @@ -806,7 +806,7 @@ func (a *OpenTracingAppLayer) AuthorizeOAuthUser(w http.ResponseWriter, r *http. }() defer span.Finish() - resultVar0, resultVar1, resultVar2, resultVar3, resultVar4 := a.app.AuthorizeOAuthUser(w, r, service, code, state, redirectURI) + resultVar0, resultVar1, resultVar2, resultVar3, resultVar4 := a.app.AuthorizeOAuthUser(c, w, r, service, code, state, redirectURI) if resultVar4 != nil { span.LogFields(spanlog.Error(resultVar4)) @@ -1295,7 +1295,7 @@ func (a *OpenTracingAppLayer) CheckPostReminders() { a.app.CheckPostReminders() } -func (a *OpenTracingAppLayer) CheckProviderAttributes(user *model.User, patch *model.UserPatch) string { +func (a *OpenTracingAppLayer) CheckProviderAttributes(c *request.Context, user *model.User, patch *model.UserPatch) string { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckProviderAttributes") @@ -1307,7 +1307,7 @@ func (a *OpenTracingAppLayer) CheckProviderAttributes(user *model.User, patch *m }() defer span.Finish() - resultVar0 := a.app.CheckProviderAttributes(user, patch) + resultVar0 := a.app.CheckProviderAttributes(c, user, patch) return resultVar0 } @@ -1714,7 +1714,7 @@ func (a *OpenTracingAppLayer) CompleteOnboarding(c *request.Context, request *mo return resultVar0 } -func (a *OpenTracingAppLayer) CompleteSwitchWithOAuth(service string, userData io.Reader, email string, tokenUser *model.User) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CompleteSwitchWithOAuth(c *request.Context, service string, userData io.Reader, email string, tokenUser *model.User) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompleteSwitchWithOAuth") @@ -1726,7 +1726,7 @@ func (a *OpenTracingAppLayer) CompleteSwitchWithOAuth(service string, userData i }() defer span.Finish() - resultVar0, resultVar1 := a.app.CompleteSwitchWithOAuth(service, userData, email, tokenUser) + resultVar0, resultVar1 := a.app.CompleteSwitchWithOAuth(c, service, userData, email, tokenUser) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5036,7 +5036,7 @@ func (a *OpenTracingAppLayer) GetAuditsPage(userID string, page int, perPage int return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) { +func (a *OpenTracingAppLayer) GetAuthorizationCode(c *request.Context, w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAuthorizationCode") @@ -5048,7 +5048,7 @@ func (a *OpenTracingAppLayer) GetAuthorizationCode(w http.ResponseWriter, r *htt }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetAuthorizationCode(w, r, service, props, loginHint) + resultVar0, resultVar1 := a.app.GetAuthorizationCode(c, w, r, service, props, loginHint) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -7636,7 +7636,7 @@ func (a *OpenTracingAppLayer) GetOAuthImplicitRedirect(userID string, authReques return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service string, teamID string, action string, redirectTo string, loginHint string, isMobile bool, desktopToken string) (string, *model.AppError) { +func (a *OpenTracingAppLayer) GetOAuthLoginEndpoint(c *request.Context, w http.ResponseWriter, r *http.Request, service string, teamID string, action string, redirectTo string, loginHint string, isMobile bool, desktopToken string) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthLoginEndpoint") @@ -7648,7 +7648,7 @@ func (a *OpenTracingAppLayer) GetOAuthLoginEndpoint(w http.ResponseWriter, r *ht }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetOAuthLoginEndpoint(w, r, service, teamID, action, redirectTo, loginHint, isMobile, desktopToken) + resultVar0, resultVar1 := a.app.GetOAuthLoginEndpoint(c, w, r, service, teamID, action, redirectTo, loginHint, isMobile, desktopToken) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -7658,7 +7658,7 @@ func (a *OpenTracingAppLayer) GetOAuthLoginEndpoint(w http.ResponseWriter, r *ht return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service string, teamID string, desktopToken string) (string, *model.AppError) { +func (a *OpenTracingAppLayer) GetOAuthSignupEndpoint(c *request.Context, w http.ResponseWriter, r *http.Request, service string, teamID string, desktopToken string) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthSignupEndpoint") @@ -7670,7 +7670,7 @@ func (a *OpenTracingAppLayer) GetOAuthSignupEndpoint(w http.ResponseWriter, r *h }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetOAuthSignupEndpoint(w, r, service, teamID, desktopToken) + resultVar0, resultVar1 := a.app.GetOAuthSignupEndpoint(c, w, r, service, teamID, desktopToken) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -9002,7 +9002,7 @@ func (a *OpenTracingAppLayer) GetSamlCertificateStatus() *model.SamlCertificateS return resultVar0 } -func (a *OpenTracingAppLayer) GetSamlMetadata() (string, *model.AppError) { +func (a *OpenTracingAppLayer) GetSamlMetadata(c *request.Context) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSamlMetadata") @@ -9014,7 +9014,7 @@ func (a *OpenTracingAppLayer) GetSamlMetadata() (string, *model.AppError) { }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetSamlMetadata() + resultVar0, resultVar1 := a.app.GetSamlMetadata(c) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -10556,7 +10556,7 @@ func (a *OpenTracingAppLayer) GetUserByUsername(username string) (*model.User, * return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetUserForLogin(id string, loginId string) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) GetUserForLogin(c *request.Context, id string, loginId string) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserForLogin") @@ -10568,7 +10568,7 @@ func (a *OpenTracingAppLayer) GetUserForLogin(id string, loginId string) (*model }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetUserForLogin(id, loginId) + resultVar0, resultVar1 := a.app.GetUserForLogin(c, id, loginId) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -12614,7 +12614,7 @@ func (a *OpenTracingAppLayer) MigrateFilenamesToFileInfos(post *model.Post) []*m return resultVar0 } -func (a *OpenTracingAppLayer) MigrateIdLDAP(toAttribute string) *model.AppError { +func (a *OpenTracingAppLayer) MigrateIdLDAP(c *request.Context, toAttribute string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MigrateIdLDAP") @@ -12626,7 +12626,7 @@ func (a *OpenTracingAppLayer) MigrateIdLDAP(toAttribute string) *model.AppError }() defer span.Finish() - resultVar0 := a.app.MigrateIdLDAP(toAttribute) + resultVar0 := a.app.MigrateIdLDAP(c, toAttribute) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -16648,7 +16648,7 @@ func (a *OpenTracingAppLayer) SubmitInteractiveDialog(c *request.Context, reques return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SwitchEmailToLdap(email string, password string, code string, ldapLoginId string, ldapPassword string) (string, *model.AppError) { +func (a *OpenTracingAppLayer) SwitchEmailToLdap(c *request.Context, email string, password string, code string, ldapLoginId string, ldapPassword string) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SwitchEmailToLdap") @@ -16660,7 +16660,7 @@ func (a *OpenTracingAppLayer) SwitchEmailToLdap(email string, password string, c }() defer span.Finish() - resultVar0, resultVar1 := a.app.SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword) + resultVar0, resultVar1 := a.app.SwitchEmailToLdap(c, email, password, code, ldapLoginId, ldapPassword) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16670,7 +16670,7 @@ func (a *OpenTracingAppLayer) SwitchEmailToLdap(email string, password string, c return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email string, password string, code string, service string) (string, *model.AppError) { +func (a *OpenTracingAppLayer) SwitchEmailToOAuth(c *request.Context, w http.ResponseWriter, r *http.Request, email string, password string, code string, service string) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SwitchEmailToOAuth") @@ -16682,7 +16682,7 @@ func (a *OpenTracingAppLayer) SwitchEmailToOAuth(w http.ResponseWriter, r *http. }() defer span.Finish() - resultVar0, resultVar1 := a.app.SwitchEmailToOAuth(w, r, email, password, code, service) + resultVar0, resultVar1 := a.app.SwitchEmailToOAuth(c, w, r, email, password, code, service) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16692,7 +16692,7 @@ func (a *OpenTracingAppLayer) SwitchEmailToOAuth(w http.ResponseWriter, r *http. return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SwitchLdapToEmail(ldapPassword string, code string, email string, newPassword string) (string, *model.AppError) { +func (a *OpenTracingAppLayer) SwitchLdapToEmail(c *request.Context, ldapPassword string, code string, email string, newPassword string) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SwitchLdapToEmail") @@ -16704,7 +16704,7 @@ func (a *OpenTracingAppLayer) SwitchLdapToEmail(ldapPassword string, code string }() defer span.Finish() - resultVar0, resultVar1 := a.app.SwitchLdapToEmail(ldapPassword, code, email, newPassword) + resultVar0, resultVar1 := a.app.SwitchLdapToEmail(c, ldapPassword, code, email, newPassword) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -17574,7 +17574,7 @@ func (a *OpenTracingAppLayer) UpdateOAuthApp(oldApp *model.OAuthApp, updatedApp return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError { +func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(c *request.Context, userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOAuthUserAttrs") @@ -17586,7 +17586,7 @@ func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *mod }() defer span.Finish() - resultVar0 := a.app.UpdateOAuthUserAttrs(userData, user, provider, service, tokenUser) + resultVar0 := a.app.UpdateOAuthUserAttrs(c, userData, user, provider, service, tokenUser) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) diff --git a/server/channels/app/plugin_commands_test.go b/server/channels/app/plugin_commands_test.go index 015d1bfd2d..c86a3433a9 100644 --- a/server/channels/app/plugin_commands_test.go +++ b/server/channels/app/plugin_commands_test.go @@ -13,7 +13,6 @@ import ( "github.com/mattermost/mattermost/server/public/model" "github.com/mattermost/mattermost/server/public/plugin" "github.com/mattermost/mattermost/server/public/shared/i18n" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/product" ) @@ -491,8 +490,7 @@ func TestProductCommands(t *testing.T) { }) require.NoError(t, err) - ctx := request.EmptyContext(th.TestLogger) - resp, err2 := th.App.ExecuteCommand(ctx, &model.CommandArgs{ + resp, err2 := th.App.ExecuteCommand(th.Context, &model.CommandArgs{ TeamId: th.BasicTeam.Id, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, @@ -522,8 +520,7 @@ func TestProductCommands(t *testing.T) { }) require.NoError(t, err) - ctx := request.EmptyContext(th.TestLogger) - resp, err2 := th.App.ExecuteCommand(ctx, &model.CommandArgs{ + resp, err2 := th.App.ExecuteCommand(th.Context, &model.CommandArgs{ TeamId: th.BasicTeam.Id, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, @@ -615,8 +612,7 @@ func TestProductCommands(t *testing.T) { }) require.NoError(t, err) - ctx := request.EmptyContext(th.TestLogger) - resp, err2 := th.App.ExecuteCommand(ctx, &model.CommandArgs{ + resp, err2 := th.App.ExecuteCommand(th.Context, &model.CommandArgs{ TeamId: th.BasicTeam.Id, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, diff --git a/server/channels/app/plugin_test.go b/server/channels/app/plugin_test.go index b95ae7e9cc..56d0c07a14 100644 --- a/server/channels/app/plugin_test.go +++ b/server/channels/app/plugin_test.go @@ -27,7 +27,6 @@ import ( "github.com/mattermost/mattermost/server/public/model" "github.com/mattermost/mattermost/server/public/plugin" "github.com/mattermost/mattermost/server/public/shared/mlog" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/testlib" "github.com/mattermost/mattermost/server/v8/channels/utils/fileutils" ) @@ -639,11 +638,10 @@ func TestChannelsPluginsInit(t *testing.T) { defer th.TearDown() runNoPanicTest := func(t *testing.T) { - ctx := request.EmptyContext(th.TestLogger) path, _ := fileutils.FindDir("tests") require.NotPanics(t, func() { - th.Server.Channels().initPlugins(ctx, path, path) + th.Server.Channels().initPlugins(th.Context, path, path) }) } diff --git a/server/channels/app/saml.go b/server/channels/app/saml.go index 93b765cd75..5fc10b5f11 100644 --- a/server/channels/app/saml.go +++ b/server/channels/app/saml.go @@ -14,6 +14,7 @@ import ( "strings" "github.com/mattermost/mattermost/server/public/model" + "github.com/mattermost/mattermost/server/public/shared/request" ) const ( @@ -22,13 +23,13 @@ const ( SamlIdpCertificateName = "saml-idp.crt" ) -func (a *App) GetSamlMetadata() (string, *model.AppError) { +func (a *App) GetSamlMetadata(c *request.Context) (string, *model.AppError) { if a.Saml() == nil { err := model.NewAppError("GetSamlMetadata", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented) return "", err } - result, err := a.Saml().GetMetadata() + result, err := a.Saml().GetMetadata(c) if err != nil { return "", model.NewAppError("GetSamlMetadata", "api.admin.saml.metadata.app_error", nil, "err="+err.Message, err.StatusCode) } diff --git a/server/channels/app/support_packet.go b/server/channels/app/support_packet.go index ca979ec8b4..f17b2d7eec 100644 --- a/server/channels/app/support_packet.go +++ b/server/channels/app/support_packet.go @@ -48,7 +48,7 @@ func (a *App) GenerateSupportPacket(c *request.Context) []model.FileData { for name, fn := range functions { fileData, err := fn(c) if err != nil { - mlog.Error("Failed to generate file for support package", mlog.Err(err), mlog.String("file", name)) + c.Logger().Error("Failed to generate file for support package", mlog.Err(err), mlog.String("file", name)) warnings = append(warnings, err.Error()) } else if fileData != nil { fileDatas = append(fileDatas, *fileData) diff --git a/server/channels/app/support_packet_test.go b/server/channels/app/support_packet_test.go index d025ba2e77..6b543924f2 100644 --- a/server/channels/app/support_packet_test.go +++ b/server/channels/app/support_packet_test.go @@ -13,7 +13,6 @@ import ( "gopkg.in/yaml.v2" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/app/platform" fmocks "github.com/mattermost/mattermost/server/v8/platform/shared/filestore/mocks" ) @@ -21,10 +20,9 @@ import ( func TestCreatePluginsFile(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) // Happy path where we have a plugins file with no err - fileData, err := th.App.createPluginsFile(ctx) + fileData, err := th.App.createPluginsFile(th.Context) require.NotNil(t, fileData) assert.Equal(t, "plugins.json", fileData.Filename) assert.Positive(t, len(fileData.Body)) @@ -36,7 +34,7 @@ func TestCreatePluginsFile(t *testing.T) { }) // Plugins off in settings so no fileData and we get a warning instead - fileData, err = th.App.createPluginsFile(ctx) + fileData, err = th.App.createPluginsFile(th.Context) assert.Nil(t, fileData) assert.ErrorContains(t, err, "failed to get plugin list for support package") } @@ -44,7 +42,6 @@ func TestCreatePluginsFile(t *testing.T) { func TestGenerateSupportPacketYaml(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) licenseUsers := 100 license := model.NewTestLicense() @@ -54,7 +51,7 @@ func TestGenerateSupportPacketYaml(t *testing.T) { t.Run("Happy path", func(t *testing.T) { // Happy path where we have a support packet yaml file without any warnings - fileData, err := th.App.generateSupportPacketYaml(ctx) + fileData, err := th.App.generateSupportPacketYaml(th.Context) require.NotNil(t, fileData) assert.Equal(t, "support_packet.yaml", fileData.Filename) assert.Positive(t, len(fileData.Body)) @@ -75,7 +72,7 @@ func TestGenerateSupportPacketYaml(t *testing.T) { fb.On("DriverName").Return("mock") fb.On("TestConnection").Return(errors.New("all broken")) - fileData, err := th.App.generateSupportPacketYaml(ctx) + fileData, err := th.App.generateSupportPacketYaml(th.Context) require.NotNil(t, fileData) assert.Equal(t, "support_packet.yaml", fileData.Filename) assert.Positive(t, len(fileData.Body)) @@ -92,7 +89,6 @@ func TestGenerateSupportPacketYaml(t *testing.T) { func TestGenerateSupportPacket(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) d1 := []byte("hello\ngo\n") err := os.WriteFile("mattermost.log", d1, 0777) @@ -100,7 +96,7 @@ func TestGenerateSupportPacket(t *testing.T) { err = os.WriteFile("notifications.log", d1, 0777) require.NoError(t, err) - fileDatas := th.App.GenerateSupportPacket(ctx) + fileDatas := th.App.GenerateSupportPacket(th.Context) var rFileNames []string testFiles := []string{ "support_packet.yaml", @@ -125,7 +121,7 @@ func TestGenerateSupportPacket(t *testing.T) { require.NoError(t, err) err = os.Remove("mattermost.log") require.NoError(t, err) - fileDatas = th.App.GenerateSupportPacket(ctx) + fileDatas = th.App.GenerateSupportPacket(th.Context) testFiles = []string{ "support_packet.yaml", "plugins.json", @@ -148,14 +144,13 @@ func TestGenerateSupportPacket(t *testing.T) { func TestGetNotificationsLog(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) // Disable notifications file to get an error th.App.UpdateConfig(func(cfg *model.Config) { *cfg.NotificationLogSettings.EnableFile = false }) - fileData, err := th.App.getNotificationsLog(ctx) + fileData, err := th.App.getNotificationsLog(th.Context) assert.Nil(t, fileData) assert.ErrorContains(t, err, "Unable to retrieve notifications.log because LogSettings: EnableFile is set to false") @@ -167,7 +162,7 @@ func TestGetNotificationsLog(t *testing.T) { // If any previous notifications.log file, lets delete it os.Remove("notifications.log") - fileData, err = th.App.getNotificationsLog(ctx) + fileData, err = th.App.getNotificationsLog(th.Context) assert.Nil(t, fileData) assert.ErrorContains(t, err, "failed read notifcation log file at path") @@ -177,7 +172,7 @@ func TestGetNotificationsLog(t *testing.T) { defer os.Remove("notifications.log") require.NoError(t, err) - fileData, err = th.App.getNotificationsLog(ctx) + fileData, err = th.App.getNotificationsLog(th.Context) require.NotNil(t, fileData) assert.Equal(t, "notifications.log", fileData.Filename) assert.Positive(t, len(fileData.Body)) @@ -187,14 +182,13 @@ func TestGetNotificationsLog(t *testing.T) { func TestGetMattermostLog(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) // disable mattermost log file setting in config so we should get an warning th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableFile = false }) - fileData, err := th.App.getMattermostLog(ctx) + fileData, err := th.App.getMattermostLog(th.Context) assert.Nil(t, fileData) assert.ErrorContains(t, err, "Unable to retrieve mattermost.log because LogSettings: EnableFile is set to false") @@ -206,7 +200,7 @@ func TestGetMattermostLog(t *testing.T) { // If any previous mattermost.log file, lets delete it os.Remove("mattermost.log") - fileData, err = th.App.getMattermostLog(ctx) + fileData, err = th.App.getMattermostLog(th.Context) assert.Nil(t, fileData) assert.ErrorContains(t, err, "failed read mattermost log file at path mattermost.log") @@ -216,7 +210,7 @@ func TestGetMattermostLog(t *testing.T) { defer os.Remove("mattermost.log") require.NoError(t, err) - fileData, err = th.App.getMattermostLog(ctx) + fileData, err = th.App.getMattermostLog(th.Context) require.NotNil(t, fileData) assert.Equal(t, "mattermost.log", fileData.Filename) assert.Positive(t, len(fileData.Body)) @@ -226,10 +220,9 @@ func TestGetMattermostLog(t *testing.T) { func TestCreateSanitizedConfigFile(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) // Happy path where we have a sanitized config file with no err - fileData, err := th.App.createSanitizedConfigFile(ctx) + fileData, err := th.App.createSanitizedConfigFile(th.Context) require.NotNil(t, fileData) assert.Equal(t, "sanitized_config.json", fileData.Filename) assert.Positive(t, len(fileData.Body)) diff --git a/server/channels/app/team_test.go b/server/channels/app/team_test.go index e869e03f9f..92cdd81c6c 100644 --- a/server/channels/app/team_test.go +++ b/server/channels/app/team_test.go @@ -19,7 +19,6 @@ import ( "github.com/stretchr/testify/require" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/app/email" emailmocks "github.com/mattermost/mattermost/server/v8/channels/app/email/mocks" "github.com/mattermost/mattermost/server/v8/channels/app/teams" @@ -1358,19 +1357,18 @@ func TestUpdateTeamMemberRolesChangingGuest(t *testing.T) { func TestInvalidateAllResendInviteEmailJobs(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) - job, err := th.App.Srv().Jobs.CreateJob(ctx, model.JobTypeResendInvitationEmail, map[string]string{}) + job, err := th.App.Srv().Jobs.CreateJob(th.Context, model.JobTypeResendInvitationEmail, map[string]string{}) require.Nil(t, err) sysVar := &model.System{Name: job.Id, Value: "0"} e := th.App.Srv().Store().System().SaveOrUpdate(sysVar) require.NoError(t, e) - appErr := th.App.InvalidateAllResendInviteEmailJobs(ctx) + appErr := th.App.InvalidateAllResendInviteEmailJobs(th.Context) require.Nil(t, appErr) - j, e := th.App.Srv().Store().Job().Get(ctx, job.Id) + j, e := th.App.Srv().Store().Job().Get(th.Context, job.Id) require.NoError(t, e) require.Equal(t, j.Status, model.JobStatusCanceled) @@ -1382,7 +1380,6 @@ func TestInvalidateAllResendInviteEmailJobs(t *testing.T) { func TestInvalidateAllEmailInvites(t *testing.T) { th := Setup(t) defer th.TearDown() - ctx := request.EmptyContext(th.TestLogger) t1 := model.Token{ Token: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", @@ -1411,7 +1408,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) { err = th.App.Srv().Store().Token().Save(&t3) require.NoError(t, err) - appErr := th.App.InvalidateAllEmailInvites(ctx) + appErr := th.App.InvalidateAllEmailInvites(th.Context) require.Nil(t, appErr) _, err = th.App.Srv().Store().Token().GetByToken(t1.Token) diff --git a/server/channels/app/user.go b/server/channels/app/user.go index 335f6eed31..77469e5a21 100644 --- a/server/channels/app/user.go +++ b/server/channels/app/user.go @@ -330,7 +330,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re if e != nil { return nil, e } - user, err1 := provider.GetUserFromJSON(userData, tokenUser) + user, err1 := provider.GetUserFromJSON(c, userData, tokenUser) if err1 != nil { return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.create.app_error", map[string]any{"Service": service}, "", http.StatusInternalServerError).Wrap(err1) } @@ -357,7 +357,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re if userByEmail.AuthService == "" { return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]any{"Service": service, "Auth": model.UserAuthServiceEmail}, "email="+user.Email, http.StatusBadRequest) } - if provider.IsSameUser(userByEmail, user) { + if provider.IsSameUser(c, userByEmail, user) { if _, err := a.Srv().Store().User().UpdateAuthData(userByEmail.Id, user.AuthService, user.AuthData, "", false); err != nil { // if the user is not updated, write a warning to the log, but don't prevent user login c.Logger().Warn("Error attempting to update user AuthData", mlog.Err(err)) @@ -1066,7 +1066,7 @@ func (a *App) UpdateUserAsUser(c request.CTX, user *model.User, asAdmin bool) (* // CheckProviderAttributes returns the empty string if the patch can be applied without // overriding attributes set by the user's login provider; otherwise, the name of the offending // field is returned. -func (a *App) CheckProviderAttributes(user *model.User, patch *model.UserPatch) string { +func (a *App) CheckProviderAttributes(c *request.Context, user *model.User, patch *model.UserPatch) string { tryingToChange := func(userValue *string, patchValue *string) bool { return patchValue != nil && *patchValue != *userValue } @@ -1082,9 +1082,9 @@ func (a *App) CheckProviderAttributes(user *model.User, patch *model.UserPatch) conflictField := "" if a.Ldap() != nil && (user.IsLDAPUser() || (user.IsSAMLUser() && *SamlSettings.EnableSyncWithLdap)) { - conflictField = a.Ldap().CheckProviderAttributes(LdapSettings, user, patch) + conflictField = a.Ldap().CheckProviderAttributes(c, LdapSettings, user, patch) } else if a.Saml() != nil && user.IsSAMLUser() { - conflictField = a.Saml().CheckProviderAttributes(SamlSettings, user, patch) + conflictField = a.Saml().CheckProviderAttributes(c, SamlSettings, user, patch) } else if user.IsOAuthUser() { if tryingToChange(&user.FirstName, patch.FirstName) || tryingToChange(&user.LastName, patch.LastName) { conflictField = "full name" @@ -2101,8 +2101,8 @@ func (a *App) AutocompleteUsersInTeam(teamID string, term string, options *model return autocomplete, nil } -func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError { - oauthUser, err1 := provider.GetUserFromJSON(userData, tokenUser) +func (a *App) UpdateOAuthUserAttrs(c *request.Context, userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError { + oauthUser, err1 := provider.GetUserFromJSON(c, userData, tokenUser) if err1 != nil { return model.NewAppError("UpdateOAuthUserAttrs", "api.user.update_oauth_user_attrs.get_user.app_error", map[string]any{"Service": service}, "", http.StatusBadRequest).Wrap(err1) } diff --git a/server/channels/app/user_test.go b/server/channels/app/user_test.go index 5540af2e54..b9daabc0bc 100644 --- a/server/channels/app/user_test.go +++ b/server/channels/app/user_test.go @@ -60,8 +60,8 @@ func TestCreateOAuthUser(t *testing.T) { // mock oAuth Provider, return data mockUser := &model.User{Id: "abcdef", AuthData: model.NewString("e7110007-64be-43d8-9840-4a7e9c26b710"), Email: dbUser.Email} providerMock := &mocks.OAuthProvider{} - providerMock.On("IsSameUser", mock.Anything, mock.Anything).Return(true) - providerMock.On("GetUserFromJSON", mock.Anything, mock.Anything).Return(mockUser, nil) + providerMock.On("IsSameUser", mock.AnythingOfType("*request.Context"), mock.Anything, mock.Anything).Return(true) + providerMock.On("GetUserFromJSON", mock.AnythingOfType("*request.Context"), mock.Anything, mock.Anything).Return(mockUser, nil) einterfaces.RegisterOAuthProvider(model.ServiceOffice365, providerMock) // Update user to be OAuth, formatting to match Office365 OAuth data @@ -417,7 +417,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(th.App, user.Id, t) - th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab", nil) + th.App.UpdateOAuthUserAttrs(th.Context, data, user, gitlabProvider, "gitlab", nil) user = getUserFromDB(th.App, user.Id, t) require.Equal(t, gitlabUserObj.Username, user.Username, "user's username is not updated") @@ -430,7 +430,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(th.App, user.Id, t) - th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab", nil) + th.App.UpdateOAuthUserAttrs(th.Context, data, user, gitlabProvider, "gitlab", nil) user = getUserFromDB(th.App, user.Id, t) require.NotEqual(t, gitlabUserObj.Username, user.Username, "user's username is updated though there already exists another user with the same username") @@ -444,7 +444,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(th.App, user.Id, t) - th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab", nil) + th.App.UpdateOAuthUserAttrs(th.Context, data, user, gitlabProvider, "gitlab", nil) user = getUserFromDB(th.App, user.Id, t) require.Equal(t, gitlabUserObj.Email, user.Email, "user's email is not updated") @@ -459,7 +459,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(th.App, user.Id, t) - th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab", nil) + th.App.UpdateOAuthUserAttrs(th.Context, data, user, gitlabProvider, "gitlab", nil) user = getUserFromDB(th.App, user.Id, t) require.NotEqual(t, gitlabUserObj.Email, user.Email, "user's email is updated though there already exists another user with the same email") @@ -472,7 +472,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(th.App, user.Id, t) - th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab", nil) + th.App.UpdateOAuthUserAttrs(th.Context, data, user, gitlabProvider, "gitlab", nil) user = getUserFromDB(th.App, user.Id, t) require.Equal(t, "Updated", user.FirstName, "user's first name is not updated") @@ -484,7 +484,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(th.App, user.Id, t) - th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab", nil) + th.App.UpdateOAuthUserAttrs(th.Context, data, user, gitlabProvider, "gitlab", nil) user = getUserFromDB(th.App, user.Id, t) require.Equal(t, "Lastname", user.LastName, "user's last name is not updated") diff --git a/server/channels/jobs/jobs_test.go b/server/channels/jobs/jobs_test.go index 8bc4621dde..710ffd6fb4 100644 --- a/server/channels/jobs/jobs_test.go +++ b/server/channels/jobs/jobs_test.go @@ -565,7 +565,7 @@ func TestHandleJobPanic(t *testing.T) { } func TestRequestCancellation(t *testing.T) { - ctx := request.EmptyContext(mlog.CreateConsoleTestLogger(t)) + ctx := request.TestContext(t) t.Run("error cancelling", func(t *testing.T) { jobServer, mockStore, _ := makeJobServer(t) diff --git a/server/channels/jobs/migrations/helper_test.go b/server/channels/jobs/migrations/helper_test.go index f1a1fedb5d..19b0537322 100644 --- a/server/channels/jobs/migrations/helper_test.go +++ b/server/channels/jobs/migrations/helper_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/mlog" "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/store" "github.com/stretchr/testify/require" @@ -20,7 +19,7 @@ func Setup(tb testing.TB) store.Store { } func deleteAllJobsByTypeAndMigrationKey(t *testing.T, store store.Store, jobType string, migrationKey string) { - ctx := request.EmptyContext(mlog.CreateConsoleTestLogger(t)) + ctx := request.TestContext(t) jobs, err := store.Job().GetAllByType(ctx, model.JobTypeMigrations) require.NoError(t, err) diff --git a/server/channels/jobs/migrations/migrations_test.go b/server/channels/jobs/migrations/migrations_test.go index d30664369b..091b1629f5 100644 --- a/server/channels/jobs/migrations/migrations_test.go +++ b/server/channels/jobs/migrations/migrations_test.go @@ -10,7 +10,6 @@ import ( "github.com/stretchr/testify/require" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/mlog" "github.com/mattermost/mattermost/server/public/shared/request" ) @@ -19,7 +18,7 @@ func TestGetMigrationState(t *testing.T) { t.SkipNow() } store := Setup(t) - ctx := request.EmptyContext(mlog.CreateConsoleTestLogger(t)) + ctx := request.TestContext(t) migrationKey := model.NewId() diff --git a/server/channels/web/oauth.go b/server/channels/web/oauth.go index e80ab016c0..3323e4cccd 100644 --- a/server/channels/web/oauth.go +++ b/server/channels/web/oauth.go @@ -277,7 +277,7 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) { uri := c.GetSiteURLHeader() + "/signup/" + service + "/complete" - body, teamId, props, tokenUser, err := c.App.AuthorizeOAuthUser(w, r, service, code, state, uri) + body, teamId, props, tokenUser, err := c.App.AuthorizeOAuthUser(c.AppContext, w, r, service, code, state, uri) action := "" hasRedirectURL := false @@ -400,7 +400,7 @@ func loginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - authURL, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionLogin, redirectURL, loginHint, false, desktopToken) + authURL, err := c.App.GetOAuthLoginEndpoint(c.AppContext, w, r, c.Params.Service, teamId, model.OAuthActionLogin, redirectURL, loginHint, false, desktopToken) if err != nil { c.Err = err return @@ -429,7 +429,7 @@ func mobileLoginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - authURL, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionMobile, redirectURL, "", true, "") + authURL, err := c.App.GetOAuthLoginEndpoint(c.AppContext, w, r, c.Params.Service, teamId, model.OAuthActionMobile, redirectURL, "", true, "") if err != nil { c.Err = err return @@ -459,7 +459,7 @@ func signupWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { desktopToken := r.URL.Query().Get("desktop_token") - authURL, err := c.App.GetOAuthSignupEndpoint(w, r, c.Params.Service, teamId, desktopToken) + authURL, err := c.App.GetOAuthSignupEndpoint(c.AppContext, w, r, c.Params.Service, teamId, desktopToken) if err != nil { c.Err = err return diff --git a/server/channels/web/oauth_test.go b/server/channels/web/oauth_test.go index 1d0cde142f..a632512d03 100644 --- a/server/channels/web/oauth_test.go +++ b/server/channels/web/oauth_test.go @@ -20,6 +20,7 @@ import ( "github.com/mattermost/mattermost/server/public/model" "github.com/mattermost/mattermost/server/public/shared/i18n" "github.com/mattermost/mattermost/server/public/shared/mlog" + "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/utils" "github.com/mattermost/mattermost/server/v8/einterfaces" ) @@ -686,7 +687,7 @@ func closeBody(r *http.Response) { type MattermostTestProvider struct { } -func (m *MattermostTestProvider) GetUserFromJSON(data io.Reader, tokenUser *model.User) (*model.User, error) { +func (m *MattermostTestProvider) GetUserFromJSON(_ *request.Context, data io.Reader, tokenUser *model.User) (*model.User, error) { var user model.User if err := json.NewDecoder(data).Decode(&user); err != nil { return nil, err @@ -695,15 +696,15 @@ func (m *MattermostTestProvider) GetUserFromJSON(data io.Reader, tokenUser *mode return &user, nil } -func (m *MattermostTestProvider) GetSSOSettings(config *model.Config, service string) (*model.SSOSettings, error) { +func (m *MattermostTestProvider) GetSSOSettings(_ *request.Context, config *model.Config, service string) (*model.SSOSettings, error) { return &config.GitLabSettings, nil } -func (m *MattermostTestProvider) GetUserFromIdToken(token string) (*model.User, error) { +func (m *MattermostTestProvider) GetUserFromIdToken(_ *request.Context, token string) (*model.User, error) { return nil, nil } -func (m *MattermostTestProvider) IsSameUser(dbUser, oauthUser *model.User) bool { +func (m *MattermostTestProvider) IsSameUser(_ *request.Context, dbUser, oauthUser *model.User) bool { return dbUser.AuthData == oauthUser.AuthData } diff --git a/server/channels/web/saml.go b/server/channels/web/saml.go index 3d9c8b65e2..139bd124af 100644 --- a/server/channels/web/saml.go +++ b/server/channels/web/saml.go @@ -71,7 +71,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { relayState = b64.StdEncoding.EncodeToString([]byte(model.MapToJSON(relayProps))) } - data, err := samlInterface.BuildRequest(relayState) + data, err := samlInterface.BuildRequest(c.AppContext, relayState) if err != nil { c.Err = err return @@ -128,11 +128,12 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { c.Err = err c.Err.StatusCode = http.StatusFound } + + c.Logger.Error("Failed to complete SAML login", mlog.Err(err)) } if len(encodedXML) > maxSAMLResponseSize { err := model.NewAppError("completeSaml", "api.user.authorize_oauth_user.saml_response_too_long.app_error", nil, "SAML response is too long", http.StatusBadRequest) - mlog.Error(err.Error()) handleError(err) return } @@ -140,13 +141,11 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { user, err := samlInterface.DoLogin(c.AppContext, encodedXML, relayProps) if err != nil { c.LogAudit("fail") - mlog.Error(err.Error()) handleError(err) return } if err = c.App.CheckUserAllAuthenticationCriteria(user, ""); err != nil { - mlog.Error(err.Error()) handleError(err) return } @@ -181,7 +180,6 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { err = c.App.DoLogin(c.AppContext, w, r, user, "", isMobile, false, true) if err != nil { - mlog.Error(err.Error()) handleError(err) return } diff --git a/server/cmd/mmctl/commands/export_e2e_test.go b/server/cmd/mmctl/commands/export_e2e_test.go index 4257ecc04d..372a1494f8 100644 --- a/server/cmd/mmctl/commands/export_e2e_test.go +++ b/server/cmd/mmctl/commands/export_e2e_test.go @@ -10,7 +10,6 @@ import ( "path/filepath" "time" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/cmd/mmctl/client" "github.com/mattermost/mattermost/server/v8/cmd/mmctl/printer" @@ -276,9 +275,8 @@ func (s *MmctlE2ETestSuite) TestExportDownloadCmdF() { func (s *MmctlE2ETestSuite) TestExportJobShowCmdF() { s.SetupTestHelper().InitBasic() - ctx := request.EmptyContext(s.th.App.Log()) - job, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExportProcess, }) s.Require().Nil(appErr) @@ -289,7 +287,7 @@ func (s *MmctlE2ETestSuite) TestExportJobShowCmdF() { s.Run("MM-T3885 - no permissions", func() { printer.Clean() - job1, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job1, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExportProcess, }) s.Require().Nil(appErr) @@ -322,7 +320,6 @@ func (s *MmctlE2ETestSuite) TestExportJobShowCmdF() { func (s *MmctlE2ETestSuite) TestExportJobListCmdF() { s.SetupTestHelper().InitBasic() - ctx := request.EmptyContext(s.th.App.Log()) s.Run("MM-T3887 - no permissions", func() { printer.Clean() @@ -362,14 +359,14 @@ func (s *MmctlE2ETestSuite) TestExportJobListCmdF() { cmd.Flags().Int("per-page", perPage, "") cmd.Flags().Bool("all", false, "") - _, appErr := s.th.App.CreateJob(ctx, &model.Job{ + _, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExportProcess, }) s.Require().Nil(appErr) time.Sleep(time.Millisecond) - job2, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job2, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExportProcess, }) s.Require().Nil(appErr) @@ -377,7 +374,7 @@ func (s *MmctlE2ETestSuite) TestExportJobListCmdF() { time.Sleep(time.Millisecond) - job3, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job3, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExportProcess, }) s.Require().Nil(appErr) @@ -394,14 +391,13 @@ func (s *MmctlE2ETestSuite) TestExportJobListCmdF() { func (s *MmctlE2ETestSuite) TestExportJobCancelCmdF() { s.SetupTestHelper().InitBasic() - ctx := request.EmptyContext(s.th.App.Log()) s.Run("Cancel an export job without permissions", func() { printer.Clean() cmd := &cobra.Command{} - job, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExportProcess, }) s.Require().Nil(appErr) @@ -430,14 +426,14 @@ func (s *MmctlE2ETestSuite) TestExportJobCancelCmdF() { cmd := &cobra.Command{} - job1, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job1, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExportProcess, }) s.Require().Nil(appErr) time.Sleep(time.Millisecond) - job2, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job2, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExportProcess, }) s.Require().Nil(appErr) @@ -448,11 +444,11 @@ func (s *MmctlE2ETestSuite) TestExportJobCancelCmdF() { s.Require().Empty(printer.GetErrorLines()) // Get job1 again to refresh its status - job1, appErr = s.th.App.GetJob(ctx, job1.Id) + job1, appErr = s.th.App.GetJob(s.th.Context, job1.Id) s.Require().Nil(appErr) // Get job2 again to ensure its status did not change - job2, _ = s.th.App.GetJob(ctx, job2.Id) + job2, _ = s.th.App.GetJob(s.th.Context, job2.Id) s.Require().Nil(appErr) s.Require().Equal(job1.Status, model.JobStatusCanceled) diff --git a/server/cmd/mmctl/commands/extract_e2e_test.go b/server/cmd/mmctl/commands/extract_e2e_test.go index 2b69b16a4e..5839b91b6c 100644 --- a/server/cmd/mmctl/commands/extract_e2e_test.go +++ b/server/cmd/mmctl/commands/extract_e2e_test.go @@ -9,7 +9,6 @@ import ( "path/filepath" "time" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/cmd/mmctl/client" "github.com/mattermost/mattermost/server/v8/cmd/mmctl/printer" @@ -71,9 +70,8 @@ func (s *MmctlE2ETestSuite) TestExtractRunCmdF() { func (s *MmctlE2ETestSuite) TestExtractJobShowCmdF() { s.SetupTestHelper().InitBasic() - ctx := request.EmptyContext(s.th.App.Log()) - job, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExtractContent, Data: map[string]string{}, }) @@ -83,7 +81,7 @@ func (s *MmctlE2ETestSuite) TestExtractJobShowCmdF() { s.Run("no permissions", func() { printer.Clean() - job1, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job1, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExtractContent, Data: map[string]string{}, }) @@ -119,7 +117,6 @@ func (s *MmctlE2ETestSuite) TestExtractJobShowCmdF() { func (s *MmctlE2ETestSuite) TestExtractJobListCmdF() { s.SetupTestHelper().InitBasic() - ctx := request.EmptyContext(s.th.App.Log()) s.Run("no permissions", func() { printer.Clean() @@ -160,7 +157,7 @@ func (s *MmctlE2ETestSuite) TestExtractJobListCmdF() { cmd.Flags().Int("per-page", perPage, "") cmd.Flags().Bool("all", false, "") - _, appErr := s.th.App.CreateJob(ctx, &model.Job{ + _, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExtractContent, Data: map[string]string{}, }) @@ -168,7 +165,7 @@ func (s *MmctlE2ETestSuite) TestExtractJobListCmdF() { time.Sleep(time.Millisecond) - job2, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job2, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExtractContent, Data: map[string]string{}, }) @@ -177,7 +174,7 @@ func (s *MmctlE2ETestSuite) TestExtractJobListCmdF() { time.Sleep(time.Millisecond) - job3, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job3, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeExtractContent, Data: map[string]string{}, }) diff --git a/server/cmd/mmctl/commands/import_e2e_test.go b/server/cmd/mmctl/commands/import_e2e_test.go index 428e1f645c..aebb42e59c 100644 --- a/server/cmd/mmctl/commands/import_e2e_test.go +++ b/server/cmd/mmctl/commands/import_e2e_test.go @@ -9,7 +9,6 @@ import ( "path/filepath" "time" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/cmd/mmctl/client" "github.com/mattermost/mattermost/server/v8/cmd/mmctl/printer" @@ -251,9 +250,8 @@ func (s *MmctlE2ETestSuite) TestImportListIncompleteCmdF() { func (s *MmctlE2ETestSuite) TestImportJobShowCmdF() { s.SetupTestHelper().InitBasic() - ctx := request.EmptyContext(s.th.App.Log()) - job, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeImportProcess, Data: map[string]string{"import_file": "import1.zip"}, }) @@ -263,7 +261,7 @@ func (s *MmctlE2ETestSuite) TestImportJobShowCmdF() { s.Run("no permissions", func() { printer.Clean() - job1, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job1, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeImportProcess, Data: map[string]string{"import_file": "import1.zip"}, }) @@ -299,7 +297,6 @@ func (s *MmctlE2ETestSuite) TestImportJobShowCmdF() { func (s *MmctlE2ETestSuite) TestImportJobListCmdF() { s.SetupTestHelper().InitBasic() - ctx := request.EmptyContext(s.th.App.Log()) s.Run("no permissions", func() { printer.Clean() @@ -340,7 +337,7 @@ func (s *MmctlE2ETestSuite) TestImportJobListCmdF() { cmd.Flags().Int("per-page", perPage, "") cmd.Flags().Bool("all", false, "") - _, appErr := s.th.App.CreateJob(ctx, &model.Job{ + _, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeImportProcess, Data: map[string]string{"import_file": "import1.zip"}, }) @@ -348,7 +345,7 @@ func (s *MmctlE2ETestSuite) TestImportJobListCmdF() { time.Sleep(time.Millisecond) - job2, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job2, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeImportProcess, Data: map[string]string{"import_file": "import2.zip"}, }) @@ -357,7 +354,7 @@ func (s *MmctlE2ETestSuite) TestImportJobListCmdF() { time.Sleep(time.Millisecond) - job3, appErr := s.th.App.CreateJob(ctx, &model.Job{ + job3, appErr := s.th.App.CreateJob(s.th.Context, &model.Job{ Type: model.JobTypeImportProcess, Data: map[string]string{"import_file": "import3.zip"}, }) diff --git a/server/cmd/mmctl/commands/ldap_e2e_test.go b/server/cmd/mmctl/commands/ldap_e2e_test.go index 1c91338db7..be221199c4 100644 --- a/server/cmd/mmctl/commands/ldap_e2e_test.go +++ b/server/cmd/mmctl/commands/ldap_e2e_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/api4" "github.com/mattermost/mattermost/server/v8/channels/utils/testutils" "github.com/spf13/cobra" @@ -52,7 +51,6 @@ func configForLdap(th *api4.TestHelper) { func (s *MmctlE2ETestSuite) TestLdapSyncCmd() { s.SetupEnterpriseTestHelper().InitBasic() configForLdap(s.th) - ctx := request.EmptyContext(s.th.App.Log()) s.Run("MM-T3971 Should not allow regular user to sync LDAP groups", func() { printer.Clean() @@ -66,7 +64,7 @@ func (s *MmctlE2ETestSuite) TestLdapSyncCmd() { s.RunForSystemAdminAndLocal("MM-T2529 Should sync LDAP groups", func(c client.Client) { printer.Clean() - jobs, appErr := s.th.App.GetJobsByTypePage(ctx, model.JobTypeLdapSync, 0, 100) + jobs, appErr := s.th.App.GetJobsByTypePage(s.th.Context, model.JobTypeLdapSync, 0, 100) s.Require().Nil(appErr) initialNumJobs := len(jobs) @@ -80,7 +78,7 @@ func (s *MmctlE2ETestSuite) TestLdapSyncCmd() { // we need to wait a bit for job creation time.Sleep(time.Second) - jobs, appErr = s.th.App.GetJobsByTypePage(ctx, model.JobTypeLdapSync, 0, 100) + jobs, appErr = s.th.App.GetJobsByTypePage(s.th.Context, model.JobTypeLdapSync, 0, 100) s.Require().Nil(appErr) s.Require().NotEmpty(jobs) s.Assert().Equal(initialNumJobs+1, len(jobs)) @@ -117,7 +115,7 @@ func (s *MmctlE2ETestSuite) TestLdapIDMigrateCmd() { err := ldapIDMigrateCmdF(c, &cobra.Command{}, []string{"cn"}) s.Require().NoError(err) defer func() { - s.Require().Nil(s.th.App.MigrateIdLDAP("uid")) + s.Require().Nil(s.th.App.MigrateIdLDAP(s.th.Context, "uid")) }() s.Require().NotEmpty(printer.GetLines()) diff --git a/server/einterfaces/account_migration.go b/server/einterfaces/account_migration.go index e142660b64..44416a41e3 100644 --- a/server/einterfaces/account_migration.go +++ b/server/einterfaces/account_migration.go @@ -10,5 +10,5 @@ import ( type AccountMigrationInterface interface { MigrateToLdap(c *request.Context, fromAuthService string, foreignUserFieldNameToMatch string, force bool, dryRun bool) *model.AppError - MigrateToSaml(fromAuthService string, usersMap map[string]string, auto bool, dryRun bool) *model.AppError + MigrateToSaml(c *request.Context, fromAuthService string, usersMap map[string]string, auto bool, dryRun bool) *model.AppError } diff --git a/server/einterfaces/ldap.go b/server/einterfaces/ldap.go index 48f5e6bd59..7a91f80009 100644 --- a/server/einterfaces/ldap.go +++ b/server/einterfaces/ldap.go @@ -10,21 +10,21 @@ import ( type LdapInterface interface { DoLogin(c *request.Context, id string, password string) (*model.User, *model.AppError) - GetUser(id string) (*model.User, *model.AppError) + GetUser(c *request.Context, id string) (*model.User, *model.AppError) GetUserAttributes(id string, attributes []string) (map[string]string, *model.AppError) - CheckPassword(id string, password string) *model.AppError - CheckPasswordAuthData(authData string, password string) *model.AppError - CheckProviderAttributes(LS *model.LdapSettings, ouser *model.User, patch *model.UserPatch) string - SwitchToLdap(userID, ldapID, ldapPassword string) *model.AppError + CheckPassword(c *request.Context, id string, password string) *model.AppError + CheckPasswordAuthData(c *request.Context, authData string, password string) *model.AppError + CheckProviderAttributes(c *request.Context, LS *model.LdapSettings, ouser *model.User, patch *model.UserPatch) string + SwitchToLdap(c *request.Context, userID, ldapID, ldapPassword string) *model.AppError StartSynchronizeJob(c *request.Context, waitForJobToFinish bool, includeRemovedMembers bool) (*model.Job, *model.AppError) RunTest() *model.AppError - GetAllLdapUsers() ([]*model.User, *model.AppError) - MigrateIDAttribute(toAttribute string) error + GetAllLdapUsers(c *request.Context) ([]*model.User, *model.AppError) + MigrateIDAttribute(c *request.Context, toAttribute string) error GetGroup(groupUID string) (*model.Group, *model.AppError) GetAllGroupsPage(page int, perPage int, opts model.LdapGroupSearchOpts) ([]*model.Group, int, *model.AppError) FirstLoginSync(c *request.Context, user *model.User, userAuthService, userAuthData, email string) *model.AppError - UpdateProfilePictureIfNecessary(request.CTX, model.User, model.Session) - GetADLdapIdFromSAMLId(authData string) string - GetSAMLIdFromADLdapId(authData string) string + UpdateProfilePictureIfNecessary(*request.Context, model.User, model.Session) + GetADLdapIdFromSAMLId(c *request.Context, authData string) string + GetSAMLIdFromADLdapId(c *request.Context, authData string) string GetVendorNameAndVendorVersion() (string, string) } diff --git a/server/einterfaces/mocks/AccountMigrationInterface.go b/server/einterfaces/mocks/AccountMigrationInterface.go index c5f50a64fa..7ae23a12ab 100644 --- a/server/einterfaces/mocks/AccountMigrationInterface.go +++ b/server/einterfaces/mocks/AccountMigrationInterface.go @@ -31,13 +31,13 @@ func (_m *AccountMigrationInterface) MigrateToLdap(c *request.Context, fromAuthS return r0 } -// MigrateToSaml provides a mock function with given fields: fromAuthService, usersMap, auto, dryRun -func (_m *AccountMigrationInterface) MigrateToSaml(fromAuthService string, usersMap map[string]string, auto bool, dryRun bool) *model.AppError { - ret := _m.Called(fromAuthService, usersMap, auto, dryRun) +// MigrateToSaml provides a mock function with given fields: c, fromAuthService, usersMap, auto, dryRun +func (_m *AccountMigrationInterface) MigrateToSaml(c *request.Context, fromAuthService string, usersMap map[string]string, auto bool, dryRun bool) *model.AppError { + ret := _m.Called(c, fromAuthService, usersMap, auto, dryRun) var r0 *model.AppError - if rf, ok := ret.Get(0).(func(string, map[string]string, bool, bool) *model.AppError); ok { - r0 = rf(fromAuthService, usersMap, auto, dryRun) + if rf, ok := ret.Get(0).(func(*request.Context, string, map[string]string, bool, bool) *model.AppError); ok { + r0 = rf(c, fromAuthService, usersMap, auto, dryRun) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.AppError) diff --git a/server/einterfaces/mocks/LdapInterface.go b/server/einterfaces/mocks/LdapInterface.go index c266abdc75..35c238bb31 100644 --- a/server/einterfaces/mocks/LdapInterface.go +++ b/server/einterfaces/mocks/LdapInterface.go @@ -15,13 +15,13 @@ type LdapInterface struct { mock.Mock } -// CheckPassword provides a mock function with given fields: id, password -func (_m *LdapInterface) CheckPassword(id string, password string) *model.AppError { - ret := _m.Called(id, password) +// CheckPassword provides a mock function with given fields: c, id, password +func (_m *LdapInterface) CheckPassword(c *request.Context, id string, password string) *model.AppError { + ret := _m.Called(c, id, password) var r0 *model.AppError - if rf, ok := ret.Get(0).(func(string, string) *model.AppError); ok { - r0 = rf(id, password) + if rf, ok := ret.Get(0).(func(*request.Context, string, string) *model.AppError); ok { + r0 = rf(c, id, password) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.AppError) @@ -31,13 +31,13 @@ func (_m *LdapInterface) CheckPassword(id string, password string) *model.AppErr return r0 } -// CheckPasswordAuthData provides a mock function with given fields: authData, password -func (_m *LdapInterface) CheckPasswordAuthData(authData string, password string) *model.AppError { - ret := _m.Called(authData, password) +// CheckPasswordAuthData provides a mock function with given fields: c, authData, password +func (_m *LdapInterface) CheckPasswordAuthData(c *request.Context, authData string, password string) *model.AppError { + ret := _m.Called(c, authData, password) var r0 *model.AppError - if rf, ok := ret.Get(0).(func(string, string) *model.AppError); ok { - r0 = rf(authData, password) + if rf, ok := ret.Get(0).(func(*request.Context, string, string) *model.AppError); ok { + r0 = rf(c, authData, password) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.AppError) @@ -47,13 +47,13 @@ func (_m *LdapInterface) CheckPasswordAuthData(authData string, password string) return r0 } -// CheckProviderAttributes provides a mock function with given fields: LS, ouser, patch -func (_m *LdapInterface) CheckProviderAttributes(LS *model.LdapSettings, ouser *model.User, patch *model.UserPatch) string { - ret := _m.Called(LS, ouser, patch) +// CheckProviderAttributes provides a mock function with given fields: c, LS, ouser, patch +func (_m *LdapInterface) CheckProviderAttributes(c *request.Context, LS *model.LdapSettings, ouser *model.User, patch *model.UserPatch) string { + ret := _m.Called(c, LS, ouser, patch) var r0 string - if rf, ok := ret.Get(0).(func(*model.LdapSettings, *model.User, *model.UserPatch) string); ok { - r0 = rf(LS, ouser, patch) + if rf, ok := ret.Get(0).(func(*request.Context, *model.LdapSettings, *model.User, *model.UserPatch) string); ok { + r0 = rf(c, LS, ouser, patch) } else { r0 = ret.Get(0).(string) } @@ -105,13 +105,13 @@ func (_m *LdapInterface) FirstLoginSync(c *request.Context, user *model.User, us return r0 } -// GetADLdapIdFromSAMLId provides a mock function with given fields: authData -func (_m *LdapInterface) GetADLdapIdFromSAMLId(authData string) string { - ret := _m.Called(authData) +// GetADLdapIdFromSAMLId provides a mock function with given fields: c, authData +func (_m *LdapInterface) GetADLdapIdFromSAMLId(c *request.Context, authData string) string { + ret := _m.Called(c, authData) var r0 string - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(authData) + if rf, ok := ret.Get(0).(func(*request.Context, string) string); ok { + r0 = rf(c, authData) } else { r0 = ret.Get(0).(string) } @@ -154,25 +154,25 @@ func (_m *LdapInterface) GetAllGroupsPage(page int, perPage int, opts model.Ldap return r0, r1, r2 } -// GetAllLdapUsers provides a mock function with given fields: -func (_m *LdapInterface) GetAllLdapUsers() ([]*model.User, *model.AppError) { - ret := _m.Called() +// GetAllLdapUsers provides a mock function with given fields: c +func (_m *LdapInterface) GetAllLdapUsers(c *request.Context) ([]*model.User, *model.AppError) { + ret := _m.Called(c) var r0 []*model.User var r1 *model.AppError - if rf, ok := ret.Get(0).(func() ([]*model.User, *model.AppError)); ok { - return rf() + if rf, ok := ret.Get(0).(func(*request.Context) ([]*model.User, *model.AppError)); ok { + return rf(c) } - if rf, ok := ret.Get(0).(func() []*model.User); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(*request.Context) []*model.User); ok { + r0 = rf(c) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*model.User) } } - if rf, ok := ret.Get(1).(func() *model.AppError); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(*request.Context) *model.AppError); ok { + r1 = rf(c) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -210,13 +210,13 @@ func (_m *LdapInterface) GetGroup(groupUID string) (*model.Group, *model.AppErro return r0, r1 } -// GetSAMLIdFromADLdapId provides a mock function with given fields: authData -func (_m *LdapInterface) GetSAMLIdFromADLdapId(authData string) string { - ret := _m.Called(authData) +// GetSAMLIdFromADLdapId provides a mock function with given fields: c, authData +func (_m *LdapInterface) GetSAMLIdFromADLdapId(c *request.Context, authData string) string { + ret := _m.Called(c, authData) var r0 string - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(authData) + if rf, ok := ret.Get(0).(func(*request.Context, string) string); ok { + r0 = rf(c, authData) } else { r0 = ret.Get(0).(string) } @@ -224,25 +224,25 @@ func (_m *LdapInterface) GetSAMLIdFromADLdapId(authData string) string { return r0 } -// GetUser provides a mock function with given fields: id -func (_m *LdapInterface) GetUser(id string) (*model.User, *model.AppError) { - ret := _m.Called(id) +// GetUser provides a mock function with given fields: c, id +func (_m *LdapInterface) GetUser(c *request.Context, id string) (*model.User, *model.AppError) { + ret := _m.Called(c, id) var r0 *model.User var r1 *model.AppError - if rf, ok := ret.Get(0).(func(string) (*model.User, *model.AppError)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(*request.Context, string) (*model.User, *model.AppError)); ok { + return rf(c, id) } - if rf, ok := ret.Get(0).(func(string) *model.User); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(*request.Context, string) *model.User); ok { + r0 = rf(c, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.User) } } - if rf, ok := ret.Get(1).(func(string) *model.AppError); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(*request.Context, string) *model.AppError); ok { + r1 = rf(c, id) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -304,13 +304,13 @@ func (_m *LdapInterface) GetVendorNameAndVendorVersion() (string, string) { return r0, r1 } -// MigrateIDAttribute provides a mock function with given fields: toAttribute -func (_m *LdapInterface) MigrateIDAttribute(toAttribute string) error { - ret := _m.Called(toAttribute) +// MigrateIDAttribute provides a mock function with given fields: c, toAttribute +func (_m *LdapInterface) MigrateIDAttribute(c *request.Context, toAttribute string) error { + ret := _m.Called(c, toAttribute) var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(toAttribute) + if rf, ok := ret.Get(0).(func(*request.Context, string) error); ok { + r0 = rf(c, toAttribute) } else { r0 = ret.Error(0) } @@ -362,13 +362,13 @@ func (_m *LdapInterface) StartSynchronizeJob(c *request.Context, waitForJobToFin return r0, r1 } -// SwitchToLdap provides a mock function with given fields: userID, ldapID, ldapPassword -func (_m *LdapInterface) SwitchToLdap(userID string, ldapID string, ldapPassword string) *model.AppError { - ret := _m.Called(userID, ldapID, ldapPassword) +// SwitchToLdap provides a mock function with given fields: c, userID, ldapID, ldapPassword +func (_m *LdapInterface) SwitchToLdap(c *request.Context, userID string, ldapID string, ldapPassword string) *model.AppError { + ret := _m.Called(c, userID, ldapID, ldapPassword) var r0 *model.AppError - if rf, ok := ret.Get(0).(func(string, string, string) *model.AppError); ok { - r0 = rf(userID, ldapID, ldapPassword) + if rf, ok := ret.Get(0).(func(*request.Context, string, string, string) *model.AppError); ok { + r0 = rf(c, userID, ldapID, ldapPassword) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.AppError) @@ -379,7 +379,7 @@ func (_m *LdapInterface) SwitchToLdap(userID string, ldapID string, ldapPassword } // UpdateProfilePictureIfNecessary provides a mock function with given fields: _a0, _a1, _a2 -func (_m *LdapInterface) UpdateProfilePictureIfNecessary(_a0 request.CTX, _a1 model.User, _a2 model.Session) { +func (_m *LdapInterface) UpdateProfilePictureIfNecessary(_a0 *request.Context, _a1 model.User, _a2 model.Session) { _m.Called(_a0, _a1, _a2) } diff --git a/server/einterfaces/mocks/NotificationInterface.go b/server/einterfaces/mocks/NotificationInterface.go index 267acd6eb2..44c32d8205 100644 --- a/server/einterfaces/mocks/NotificationInterface.go +++ b/server/einterfaces/mocks/NotificationInterface.go @@ -6,6 +6,7 @@ package mocks import ( model "github.com/mattermost/mattermost/server/public/model" + request "github.com/mattermost/mattermost/server/public/shared/request" mock "github.com/stretchr/testify/mock" ) @@ -30,25 +31,25 @@ func (_m *NotificationInterface) CheckLicense() *model.AppError { return r0 } -// GetNotificationMessage provides a mock function with given fields: ack, userID -func (_m *NotificationInterface) GetNotificationMessage(ack *model.PushNotificationAck, userID string) (*model.PushNotification, *model.AppError) { - ret := _m.Called(ack, userID) +// GetNotificationMessage provides a mock function with given fields: c, ack, userID +func (_m *NotificationInterface) GetNotificationMessage(c *request.Context, ack *model.PushNotificationAck, userID string) (*model.PushNotification, *model.AppError) { + ret := _m.Called(c, ack, userID) var r0 *model.PushNotification var r1 *model.AppError - if rf, ok := ret.Get(0).(func(*model.PushNotificationAck, string) (*model.PushNotification, *model.AppError)); ok { - return rf(ack, userID) + if rf, ok := ret.Get(0).(func(*request.Context, *model.PushNotificationAck, string) (*model.PushNotification, *model.AppError)); ok { + return rf(c, ack, userID) } - if rf, ok := ret.Get(0).(func(*model.PushNotificationAck, string) *model.PushNotification); ok { - r0 = rf(ack, userID) + if rf, ok := ret.Get(0).(func(*request.Context, *model.PushNotificationAck, string) *model.PushNotification); ok { + r0 = rf(c, ack, userID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.PushNotification) } } - if rf, ok := ret.Get(1).(func(*model.PushNotificationAck, string) *model.AppError); ok { - r1 = rf(ack, userID) + if rf, ok := ret.Get(1).(func(*request.Context, *model.PushNotificationAck, string) *model.AppError); ok { + r1 = rf(c, ack, userID) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) diff --git a/server/einterfaces/mocks/OAuthProvider.go b/server/einterfaces/mocks/OAuthProvider.go index c46d7be8e6..b913191f24 100644 --- a/server/einterfaces/mocks/OAuthProvider.go +++ b/server/einterfaces/mocks/OAuthProvider.go @@ -9,6 +9,8 @@ import ( model "github.com/mattermost/mattermost/server/public/model" mock "github.com/stretchr/testify/mock" + + request "github.com/mattermost/mattermost/server/public/shared/request" ) // OAuthProvider is an autogenerated mock type for the OAuthProvider type @@ -16,25 +18,25 @@ type OAuthProvider struct { mock.Mock } -// GetSSOSettings provides a mock function with given fields: config, service -func (_m *OAuthProvider) GetSSOSettings(config *model.Config, service string) (*model.SSOSettings, error) { - ret := _m.Called(config, service) +// GetSSOSettings provides a mock function with given fields: c, config, service +func (_m *OAuthProvider) GetSSOSettings(c *request.Context, config *model.Config, service string) (*model.SSOSettings, error) { + ret := _m.Called(c, config, service) var r0 *model.SSOSettings var r1 error - if rf, ok := ret.Get(0).(func(*model.Config, string) (*model.SSOSettings, error)); ok { - return rf(config, service) + if rf, ok := ret.Get(0).(func(*request.Context, *model.Config, string) (*model.SSOSettings, error)); ok { + return rf(c, config, service) } - if rf, ok := ret.Get(0).(func(*model.Config, string) *model.SSOSettings); ok { - r0 = rf(config, service) + if rf, ok := ret.Get(0).(func(*request.Context, *model.Config, string) *model.SSOSettings); ok { + r0 = rf(c, config, service) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.SSOSettings) } } - if rf, ok := ret.Get(1).(func(*model.Config, string) error); ok { - r1 = rf(config, service) + if rf, ok := ret.Get(1).(func(*request.Context, *model.Config, string) error); ok { + r1 = rf(c, config, service) } else { r1 = ret.Error(1) } @@ -42,25 +44,25 @@ func (_m *OAuthProvider) GetSSOSettings(config *model.Config, service string) (* return r0, r1 } -// GetUserFromIdToken provides a mock function with given fields: idToken -func (_m *OAuthProvider) GetUserFromIdToken(idToken string) (*model.User, error) { - ret := _m.Called(idToken) +// GetUserFromIdToken provides a mock function with given fields: c, idToken +func (_m *OAuthProvider) GetUserFromIdToken(c *request.Context, idToken string) (*model.User, error) { + ret := _m.Called(c, idToken) var r0 *model.User var r1 error - if rf, ok := ret.Get(0).(func(string) (*model.User, error)); ok { - return rf(idToken) + if rf, ok := ret.Get(0).(func(*request.Context, string) (*model.User, error)); ok { + return rf(c, idToken) } - if rf, ok := ret.Get(0).(func(string) *model.User); ok { - r0 = rf(idToken) + if rf, ok := ret.Get(0).(func(*request.Context, string) *model.User); ok { + r0 = rf(c, idToken) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.User) } } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(idToken) + if rf, ok := ret.Get(1).(func(*request.Context, string) error); ok { + r1 = rf(c, idToken) } else { r1 = ret.Error(1) } @@ -68,25 +70,25 @@ func (_m *OAuthProvider) GetUserFromIdToken(idToken string) (*model.User, error) return r0, r1 } -// GetUserFromJSON provides a mock function with given fields: data, tokenUser -func (_m *OAuthProvider) GetUserFromJSON(data io.Reader, tokenUser *model.User) (*model.User, error) { - ret := _m.Called(data, tokenUser) +// GetUserFromJSON provides a mock function with given fields: c, data, tokenUser +func (_m *OAuthProvider) GetUserFromJSON(c *request.Context, data io.Reader, tokenUser *model.User) (*model.User, error) { + ret := _m.Called(c, data, tokenUser) var r0 *model.User var r1 error - if rf, ok := ret.Get(0).(func(io.Reader, *model.User) (*model.User, error)); ok { - return rf(data, tokenUser) + if rf, ok := ret.Get(0).(func(*request.Context, io.Reader, *model.User) (*model.User, error)); ok { + return rf(c, data, tokenUser) } - if rf, ok := ret.Get(0).(func(io.Reader, *model.User) *model.User); ok { - r0 = rf(data, tokenUser) + if rf, ok := ret.Get(0).(func(*request.Context, io.Reader, *model.User) *model.User); ok { + r0 = rf(c, data, tokenUser) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.User) } } - if rf, ok := ret.Get(1).(func(io.Reader, *model.User) error); ok { - r1 = rf(data, tokenUser) + if rf, ok := ret.Get(1).(func(*request.Context, io.Reader, *model.User) error); ok { + r1 = rf(c, data, tokenUser) } else { r1 = ret.Error(1) } @@ -94,13 +96,13 @@ func (_m *OAuthProvider) GetUserFromJSON(data io.Reader, tokenUser *model.User) return r0, r1 } -// IsSameUser provides a mock function with given fields: dbUser, oAuthUser -func (_m *OAuthProvider) IsSameUser(dbUser *model.User, oAuthUser *model.User) bool { - ret := _m.Called(dbUser, oAuthUser) +// IsSameUser provides a mock function with given fields: c, dbUser, oAuthUser +func (_m *OAuthProvider) IsSameUser(c *request.Context, dbUser *model.User, oAuthUser *model.User) bool { + ret := _m.Called(c, dbUser, oAuthUser) var r0 bool - if rf, ok := ret.Get(0).(func(*model.User, *model.User) bool); ok { - r0 = rf(dbUser, oAuthUser) + if rf, ok := ret.Get(0).(func(*request.Context, *model.User, *model.User) bool); ok { + r0 = rf(c, dbUser, oAuthUser) } else { r0 = ret.Get(0).(bool) } diff --git a/server/einterfaces/mocks/SamlInterface.go b/server/einterfaces/mocks/SamlInterface.go index 8ea64e85df..d7d66106b6 100644 --- a/server/einterfaces/mocks/SamlInterface.go +++ b/server/einterfaces/mocks/SamlInterface.go @@ -15,25 +15,25 @@ type SamlInterface struct { mock.Mock } -// BuildRequest provides a mock function with given fields: relayState -func (_m *SamlInterface) BuildRequest(relayState string) (*model.SamlAuthRequest, *model.AppError) { - ret := _m.Called(relayState) +// BuildRequest provides a mock function with given fields: c, relayState +func (_m *SamlInterface) BuildRequest(c *request.Context, relayState string) (*model.SamlAuthRequest, *model.AppError) { + ret := _m.Called(c, relayState) var r0 *model.SamlAuthRequest var r1 *model.AppError - if rf, ok := ret.Get(0).(func(string) (*model.SamlAuthRequest, *model.AppError)); ok { - return rf(relayState) + if rf, ok := ret.Get(0).(func(*request.Context, string) (*model.SamlAuthRequest, *model.AppError)); ok { + return rf(c, relayState) } - if rf, ok := ret.Get(0).(func(string) *model.SamlAuthRequest); ok { - r0 = rf(relayState) + if rf, ok := ret.Get(0).(func(*request.Context, string) *model.SamlAuthRequest); ok { + r0 = rf(c, relayState) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.SamlAuthRequest) } } - if rf, ok := ret.Get(1).(func(string) *model.AppError); ok { - r1 = rf(relayState) + if rf, ok := ret.Get(1).(func(*request.Context, string) *model.AppError); ok { + r1 = rf(c, relayState) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -43,13 +43,13 @@ func (_m *SamlInterface) BuildRequest(relayState string) (*model.SamlAuthRequest return r0, r1 } -// CheckProviderAttributes provides a mock function with given fields: SS, ouser, patch -func (_m *SamlInterface) CheckProviderAttributes(SS *model.SamlSettings, ouser *model.User, patch *model.UserPatch) string { - ret := _m.Called(SS, ouser, patch) +// CheckProviderAttributes provides a mock function with given fields: c, SS, ouser, patch +func (_m *SamlInterface) CheckProviderAttributes(c *request.Context, SS *model.SamlSettings, ouser *model.User, patch *model.UserPatch) string { + ret := _m.Called(c, SS, ouser, patch) var r0 string - if rf, ok := ret.Get(0).(func(*model.SamlSettings, *model.User, *model.UserPatch) string); ok { - r0 = rf(SS, ouser, patch) + if rf, ok := ret.Get(0).(func(*request.Context, *model.SamlSettings, *model.User, *model.UserPatch) string); ok { + r0 = rf(c, SS, ouser, patch) } else { r0 = ret.Get(0).(string) } @@ -57,13 +57,13 @@ func (_m *SamlInterface) CheckProviderAttributes(SS *model.SamlSettings, ouser * return r0 } -// ConfigureSP provides a mock function with given fields: -func (_m *SamlInterface) ConfigureSP() error { - ret := _m.Called() +// ConfigureSP provides a mock function with given fields: c +func (_m *SamlInterface) ConfigureSP(c *request.Context) error { + ret := _m.Called(c) var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(*request.Context) error); ok { + r0 = rf(c) } else { r0 = ret.Error(0) } @@ -99,23 +99,23 @@ func (_m *SamlInterface) DoLogin(c *request.Context, encodedXML string, relaySta return r0, r1 } -// GetMetadata provides a mock function with given fields: -func (_m *SamlInterface) GetMetadata() (string, *model.AppError) { - ret := _m.Called() +// GetMetadata provides a mock function with given fields: c +func (_m *SamlInterface) GetMetadata(c *request.Context) (string, *model.AppError) { + ret := _m.Called(c) var r0 string var r1 *model.AppError - if rf, ok := ret.Get(0).(func() (string, *model.AppError)); ok { - return rf() + if rf, ok := ret.Get(0).(func(*request.Context) (string, *model.AppError)); ok { + return rf(c) } - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(*request.Context) string); ok { + r0 = rf(c) } else { r0 = ret.Get(0).(string) } - if rf, ok := ret.Get(1).(func() *model.AppError); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(*request.Context) *model.AppError); ok { + r1 = rf(c) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) diff --git a/server/einterfaces/notification.go b/server/einterfaces/notification.go index 421713be4f..0bfd1e455e 100644 --- a/server/einterfaces/notification.go +++ b/server/einterfaces/notification.go @@ -5,9 +5,10 @@ package einterfaces import ( "github.com/mattermost/mattermost/server/public/model" + "github.com/mattermost/mattermost/server/public/shared/request" ) type NotificationInterface interface { - GetNotificationMessage(ack *model.PushNotificationAck, userID string) (*model.PushNotification, *model.AppError) + GetNotificationMessage(c *request.Context, ack *model.PushNotificationAck, userID string) (*model.PushNotification, *model.AppError) CheckLicense() *model.AppError } diff --git a/server/einterfaces/oauthproviders.go b/server/einterfaces/oauthproviders.go index 1e74d87aa5..79ad1bc537 100644 --- a/server/einterfaces/oauthproviders.go +++ b/server/einterfaces/oauthproviders.go @@ -7,13 +7,14 @@ import ( "io" "github.com/mattermost/mattermost/server/public/model" + "github.com/mattermost/mattermost/server/public/shared/request" ) type OAuthProvider interface { - GetUserFromJSON(data io.Reader, tokenUser *model.User) (*model.User, error) - GetSSOSettings(config *model.Config, service string) (*model.SSOSettings, error) - GetUserFromIdToken(idToken string) (*model.User, error) - IsSameUser(dbUser, oAuthUser *model.User) bool + GetUserFromJSON(c *request.Context, data io.Reader, tokenUser *model.User) (*model.User, error) + GetSSOSettings(c *request.Context, config *model.Config, service string) (*model.SSOSettings, error) + GetUserFromIdToken(c *request.Context, idToken string) (*model.User, error) + IsSameUser(c *request.Context, dbUser, oAuthUser *model.User) bool } var oauthProviders = make(map[string]OAuthProvider) diff --git a/server/einterfaces/saml.go b/server/einterfaces/saml.go index 1417a07ad1..e2cf8cfced 100644 --- a/server/einterfaces/saml.go +++ b/server/einterfaces/saml.go @@ -9,9 +9,9 @@ import ( ) type SamlInterface interface { - ConfigureSP() error - BuildRequest(relayState string) (*model.SamlAuthRequest, *model.AppError) + ConfigureSP(c *request.Context) error + BuildRequest(c *request.Context, relayState string) (*model.SamlAuthRequest, *model.AppError) DoLogin(c *request.Context, encodedXML string, relayState map[string]string) (*model.User, *model.AppError) - GetMetadata() (string, *model.AppError) - CheckProviderAttributes(SS *model.SamlSettings, ouser *model.User, patch *model.UserPatch) string + GetMetadata(c *request.Context) (string, *model.AppError) + CheckProviderAttributes(c *request.Context, SS *model.SamlSettings, ouser *model.User, patch *model.UserPatch) string } diff --git a/server/platform/services/slackimport/slackimport_test.go b/server/platform/services/slackimport/slackimport_test.go index 553b6b1a68..9ba7f4c624 100644 --- a/server/platform/services/slackimport/slackimport_test.go +++ b/server/platform/services/slackimport/slackimport_test.go @@ -13,7 +13,6 @@ import ( "github.com/stretchr/testify/require" "github.com/mattermost/mattermost/server/public/model" - "github.com/mattermost/mattermost/server/public/shared/mlog" "github.com/mattermost/mattermost/server/public/shared/request" "github.com/mattermost/mattermost/server/v8/channels/store/storetest/mocks" ) @@ -339,7 +338,7 @@ func TestOldImportChannel(t *testing.T) { store := &mocks.Store{} config := &model.Config{} config.SetDefaults() - ctx := request.EmptyContext(mlog.CreateConsoleTestLogger(t)) + ctx := request.TestContext(t) t.Run("No panic on direct channel", func(t *testing.T) { // ch := th.CreateDmChannel(u1) diff --git a/server/public/model/user.go b/server/public/model/user.go index b474d515cc..2eb2c2db92 100644 --- a/server/public/model/user.go +++ b/server/public/model/user.go @@ -975,7 +975,7 @@ func IsValidUsernameAllowRemote(s string) bool { return !found } -func CleanUsername(username string) string { +func CleanUsername(logger mlog.LoggerIFace, username string) string { s := NormalizeUsername(strings.Replace(username, " ", "-", -1)) for _, value := range reservedName { @@ -997,7 +997,7 @@ func CleanUsername(username string) string { if !IsValidUsername(s) { s = "a" + NewId() - mlog.Warn("Generating new username since provided username was invalid", + logger.Warn("Generating new username since provided username was invalid", mlog.String("provided_username", username), mlog.String("new_username", s)) } diff --git a/server/public/model/user_test.go b/server/public/model/user_test.go index a99d36da47..68b495fd19 100644 --- a/server/public/model/user_test.go +++ b/server/public/model/user_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/mattermost/mattermost/server/public/shared/mlog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -257,11 +258,12 @@ func TestNormalizeEmail(t *testing.T) { } func TestCleanUsername(t *testing.T) { - assert.Equal(t, CleanUsername("Spin-punch"), "spin-punch", "didn't clean name properly") - assert.Equal(t, CleanUsername("PUNCH"), "punch", "didn't clean name properly") - assert.Equal(t, CleanUsername("spin'punch"), "spin-punch", "didn't clean name properly") - assert.Equal(t, CleanUsername("spin"), "spin", "didn't clean name properly") - assert.Len(t, CleanUsername("all"), 27, "didn't clean name properly") + logger := mlog.CreateConsoleTestLogger(t) + assert.Equal(t, CleanUsername(logger, "Spin-punch"), "spin-punch", "didn't clean name properly") + assert.Equal(t, CleanUsername(logger, "PUNCH"), "punch", "didn't clean name properly") + assert.Equal(t, CleanUsername(logger, "spin'punch"), "spin-punch", "didn't clean name properly") + assert.Equal(t, CleanUsername(logger, "spin"), "spin", "didn't clean name properly") + assert.Len(t, CleanUsername(logger, "all"), 27, "didn't clean name properly") } func TestRoles(t *testing.T) {