[GH-21565]-Add the request context and logger to all public methods in server/channels/app/audit.go (#25368)

This commit is contained in:
KIMBOH LOVETTE 2023-11-14 13:34:47 +01:00 committed by GitHub
parent 5f8133254d
commit 29cd6177c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 64 additions and 51 deletions

View File

@ -270,7 +270,7 @@ func getAudits(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
audits, appErr := c.App.GetAuditsPage("", c.Params.Page, c.Params.PerPage)
audits, appErr := c.App.GetAuditsPage(c.AppContext, "", c.Params.Page, c.Params.PerPage)
if appErr != nil {
c.Err = appErr
return

View File

@ -2298,7 +2298,7 @@ func getUserAudits(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
audits, err := c.App.GetAuditsPage(c.Params.UserId, c.Params.Page, c.Params.PerPage)
audits, err := c.App.GetAuditsPage(c.AppContext, c.Params.UserId, c.Params.Page, c.Params.PerPage)
if err != nil {
c.Err = err
return

View File

@ -151,7 +151,7 @@ type AppIface interface {
// ExtendSessionExpiryIfNeeded extends Session.ExpiresAt based on session lengths in config.
// A new ExpiresAt is only written if enough time has elapsed since last update.
// Returns true only if the session was extended.
ExtendSessionExpiryIfNeeded(session *model.Session) bool
ExtendSessionExpiryIfNeeded(rctx request.CTX, session *model.Session) bool
// FillInPostProps should be invoked before saving posts to fill in properties such as
// channel_mentions.
//
@ -251,11 +251,11 @@ type AppIface interface {
// plugin was already enabled.
InstallPlugin(pluginFile io.ReadSeeker, replace bool) (*model.Manifest, *model.AppError)
// LogAuditRec logs an audit record using default LvlAuditCLI.
LogAuditRec(rec *audit.Record, err error)
LogAuditRec(rctx request.CTX, rec *audit.Record, err error)
// LogAuditRecWithLevel logs an audit record using specified Level.
LogAuditRecWithLevel(rec *audit.Record, level mlog.Level, err error)
LogAuditRecWithLevel(rctx request.CTX, rec *audit.Record, level mlog.Level, err error)
// MakeAuditRecord creates a audit record pre-populated with defaults.
MakeAuditRecord(event string, initialStatus string) *audit.Record
MakeAuditRecord(rctx request.CTX, event string, initialStatus string) *audit.Record
// MarkChanelAsUnreadFromPost will take a post and set the channel as unread from that one.
MarkChannelAsUnreadFromPost(c request.CTX, postID string, userID string, collapsedThreadsSupported bool) (*model.ChannelUnreadAt, *model.AppError)
// MentionsToPublicChannels returns all the mentions to public channels,
@ -596,8 +596,8 @@ type AppIface interface {
GetAllTeamsPageWithCount(offset int, limit int, opts *model.TeamSearch) (*model.TeamsWithCount, *model.AppError)
GetAnalytics(name string, teamID string) (model.AnalyticsRows, *model.AppError)
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)
GetAudits(rctx request.CTX, userID string, limit int) (model.Audits, *model.AppError)
GetAuditsPage(rctx request.CTX, userID string, page int, perPage int) (model.Audits, *model.AppError)
GetAuthorizationCode(c request.CTX, 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)

View File

@ -11,6 +11,7 @@ import (
"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/public/utils"
"github.com/mattermost/mattermost/server/v8/channels/audit"
"github.com/mattermost/mattermost/server/v8/channels/store"
@ -24,7 +25,7 @@ var (
LevelCLI = mlog.LvlAuditCLI
)
func (a *App) GetAudits(userID string, limit int) (model.Audits, *model.AppError) {
func (a *App) GetAudits(rctx request.CTX, userID string, limit int) (model.Audits, *model.AppError) {
audits, err := a.Srv().Store().Audit().Get(userID, 0, limit)
if err != nil {
var outErr *store.ErrOutOfBounds
@ -38,7 +39,7 @@ func (a *App) GetAudits(userID string, limit int) (model.Audits, *model.AppError
return audits, nil
}
func (a *App) GetAuditsPage(userID string, page int, perPage int) (model.Audits, *model.AppError) {
func (a *App) GetAuditsPage(rctx request.CTX, userID string, page int, perPage int) (model.Audits, *model.AppError) {
audits, err := a.Srv().Store().Audit().Get(userID, page*perPage, perPage)
if err != nil {
var outErr *store.ErrOutOfBounds
@ -53,12 +54,12 @@ func (a *App) GetAuditsPage(userID string, page int, perPage int) (model.Audits,
}
// LogAuditRec logs an audit record using default LvlAuditCLI.
func (a *App) LogAuditRec(rec *audit.Record, err error) {
a.LogAuditRecWithLevel(rec, mlog.LvlAuditCLI, err)
func (a *App) LogAuditRec(rctx request.CTX, rec *audit.Record, err error) {
a.LogAuditRecWithLevel(rctx, rec, mlog.LvlAuditCLI, err)
}
// LogAuditRecWithLevel logs an audit record using specified Level.
func (a *App) LogAuditRecWithLevel(rec *audit.Record, level mlog.Level, err error) {
func (a *App) LogAuditRecWithLevel(rctx request.CTX, rec *audit.Record, level mlog.Level, err error) {
if rec == nil {
return
}
@ -74,7 +75,7 @@ func (a *App) LogAuditRecWithLevel(rec *audit.Record, level mlog.Level, err erro
}
// MakeAuditRecord creates a audit record pre-populated with defaults.
func (a *App) MakeAuditRecord(event string, initialStatus string) *audit.Record {
func (a *App) MakeAuditRecord(rctx request.CTX, event string, initialStatus string) *audit.Record {
var userID string
user, err := user.Current()
if err == nil {

View File

@ -4231,7 +4231,7 @@ func (a *OpenTracingAppLayer) ExportPermissions(w io.Writer) error {
return resultVar0
}
func (a *OpenTracingAppLayer) ExtendSessionExpiryIfNeeded(session *model.Session) bool {
func (a *OpenTracingAppLayer) ExtendSessionExpiryIfNeeded(rctx request.CTX, session *model.Session) bool {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ExtendSessionExpiryIfNeeded")
@ -4243,7 +4243,7 @@ func (a *OpenTracingAppLayer) ExtendSessionExpiryIfNeeded(session *model.Session
}()
defer span.Finish()
resultVar0 := a.app.ExtendSessionExpiryIfNeeded(session)
resultVar0 := a.app.ExtendSessionExpiryIfNeeded(rctx, session)
return resultVar0
}
@ -4991,7 +4991,7 @@ func (a *OpenTracingAppLayer) GetAppliedSchemaMigrations() ([]model.AppliedMigra
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) GetAudits(userID string, limit int) (model.Audits, *model.AppError) {
func (a *OpenTracingAppLayer) GetAudits(rctx request.CTX, userID string, limit int) (model.Audits, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAudits")
@ -5003,7 +5003,7 @@ func (a *OpenTracingAppLayer) GetAudits(userID string, limit int) (model.Audits,
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.GetAudits(userID, limit)
resultVar0, resultVar1 := a.app.GetAudits(rctx, userID, limit)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@ -5013,7 +5013,7 @@ func (a *OpenTracingAppLayer) GetAudits(userID string, limit int) (model.Audits,
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) GetAuditsPage(userID string, page int, perPage int) (model.Audits, *model.AppError) {
func (a *OpenTracingAppLayer) GetAuditsPage(rctx request.CTX, userID string, page int, perPage int) (model.Audits, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAuditsPage")
@ -5025,7 +5025,7 @@ func (a *OpenTracingAppLayer) GetAuditsPage(userID string, page int, perPage int
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.GetAuditsPage(userID, page, perPage)
resultVar0, resultVar1 := a.app.GetAuditsPage(rctx, userID, page, perPage)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@ -12356,7 +12356,7 @@ func (a *OpenTracingAppLayer) ListTeamCommands(teamID string) ([]*model.Command,
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) LogAuditRec(rec *audit.Record, err error) {
func (a *OpenTracingAppLayer) LogAuditRec(rctx request.CTX, rec *audit.Record, err error) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LogAuditRec")
@ -12368,10 +12368,10 @@ func (a *OpenTracingAppLayer) LogAuditRec(rec *audit.Record, err error) {
}()
defer span.Finish()
a.app.LogAuditRec(rec, err)
a.app.LogAuditRec(rctx, rec, err)
}
func (a *OpenTracingAppLayer) LogAuditRecWithLevel(rec *audit.Record, level mlog.Level, err error) {
func (a *OpenTracingAppLayer) LogAuditRecWithLevel(rctx request.CTX, rec *audit.Record, level mlog.Level, err error) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LogAuditRecWithLevel")
@ -12383,7 +12383,7 @@ func (a *OpenTracingAppLayer) LogAuditRecWithLevel(rec *audit.Record, level mlog
}()
defer span.Finish()
a.app.LogAuditRecWithLevel(rec, level, err)
a.app.LogAuditRecWithLevel(rctx, rec, level, err)
}
func (a *OpenTracingAppLayer) LoginByOAuth(c request.CTX, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) {
@ -12408,7 +12408,7 @@ func (a *OpenTracingAppLayer) LoginByOAuth(c request.CTX, service string, userDa
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) MakeAuditRecord(event string, initialStatus string) *audit.Record {
func (a *OpenTracingAppLayer) MakeAuditRecord(rctx request.CTX, event string, initialStatus string) *audit.Record {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MakeAuditRecord")
@ -12420,7 +12420,7 @@ func (a *OpenTracingAppLayer) MakeAuditRecord(event string, initialStatus string
}()
defer span.Finish()
resultVar0 := a.app.MakeAuditRecord(event, initialStatus)
resultVar0 := a.app.MakeAuditRecord(rctx, event, initialStatus)
return resultVar0
}

View File

@ -241,7 +241,7 @@ func (a *App) AttachDeviceId(sessionID string, deviceID string, expiresAt int64)
// ExtendSessionExpiryIfNeeded extends Session.ExpiresAt based on session lengths in config.
// A new ExpiresAt is only written if enough time has elapsed since last update.
// Returns true only if the session was extended.
func (a *App) ExtendSessionExpiryIfNeeded(session *model.Session) bool {
func (a *App) ExtendSessionExpiryIfNeeded(rctx request.CTX, session *model.Session) bool {
if !*a.Config().ServiceSettings.ExtendSessionLengthWithActivity {
return false
}
@ -268,8 +268,8 @@ func (a *App) ExtendSessionExpiryIfNeeded(session *model.Session) bool {
return false
}
auditRec := a.MakeAuditRecord("extendSessionExpiry", audit.Fail)
defer a.LogAuditRec(auditRec, nil)
auditRec := a.MakeAuditRecord(rctx, "extendSessionExpiry", audit.Fail)
defer a.LogAuditRec(rctx, auditRec, nil)
auditRec.AddEventPriorState(session)
newExpiry := now + sessionLength

View File

@ -256,7 +256,7 @@ func TestApp_ExtendExpiryIfNeeded(t *testing.T) {
session, err := th.App.CreateSession(th.Context, session)
require.Nil(t, err)
ok := th.App.ExtendSessionExpiryIfNeeded(session)
ok := th.App.ExtendSessionExpiryIfNeeded(th.Context, session)
require.False(t, ok)
require.Equal(t, expires, session.ExpiresAt)
@ -273,7 +273,7 @@ func TestApp_ExtendExpiryIfNeeded(t *testing.T) {
expires := model.GetMillis() + th.App.GetSessionLengthInMillis(session)
session.ExpiresAt = expires
ok := th.App.ExtendSessionExpiryIfNeeded(session)
ok := th.App.ExtendSessionExpiryIfNeeded(th.Context, session)
require.False(t, ok)
require.Equal(t, expires, session.ExpiresAt)
@ -303,7 +303,7 @@ func TestApp_ExtendExpiryIfNeeded(t *testing.T) {
expires := model.GetMillis() + th.App.GetSessionLengthInMillis(session) - hourMillis
session.ExpiresAt = expires
ok := th.App.ExtendSessionExpiryIfNeeded(session)
ok := th.App.ExtendSessionExpiryIfNeeded(th.Context, session)
if !test.enabled {
require.False(t, ok)

View File

@ -195,7 +195,7 @@ func (c *Context) MfaRequired() {
// ExtendSessionExpiryIfNeeded will update Session.ExpiresAt based on session lengths in config.
// Session cookies will be resent to the client with updated max age.
func (c *Context) ExtendSessionExpiryIfNeeded(w http.ResponseWriter, r *http.Request) {
if ok := c.App.ExtendSessionExpiryIfNeeded(c.AppContext.Session()); ok {
if ok := c.App.ExtendSessionExpiryIfNeeded(c.AppContext, c.AppContext.Session()); ok {
c.App.AttachSessionCookies(c.AppContext, w, r)
}
}

View File

@ -14,7 +14,7 @@ func (api *API) InitUser() {
}
func (api *API) userTyping(req *model.WebSocketRequest) (map[string]any, *model.AppError) {
api.App.ExtendSessionExpiryIfNeeded(&req.Session)
api.App.ExtendSessionExpiryIfNeeded(request.EmptyContext(api.App.Log()), &req.Session)
if api.App.Srv().Platform().Busy.IsBusy() {
// this is considered a non-critical service and will be disabled when server busy.

View File

@ -105,6 +105,8 @@ func scheduleExportCmdF(command *cobra.Command, args []string) error {
return errors.New("ERROR: The message export feature is not enabled")
}
var rctx request.CTX = request.EmptyContext(a.Log())
// for now, format is hard-coded to actiance. In time, we'll have to support other formats and inject them into job data
format, err := command.Flags().GetString("format")
if err != nil {
@ -138,7 +140,6 @@ func scheduleExportCmdF(command *cobra.Command, args []string) error {
defer cancel()
}
var rctx request.CTX = request.EmptyContext(a.Log())
rctx = rctx.WithContext(ctx)
job, err := messageExportI.StartSynchronizeJob(rctx, startTime)
@ -147,10 +148,10 @@ func scheduleExportCmdF(command *cobra.Command, args []string) error {
} else {
CommandPrettyPrintln("SUCCESS: Message export job complete")
auditRec := a.MakeAuditRecord("scheduleExport", audit.Success)
auditRec := a.MakeAuditRecord(rctx, "scheduleExport", audit.Success)
auditRec.AddMeta("format", format)
auditRec.AddMeta("start", startTime)
a.LogAuditRec(auditRec, nil)
a.LogAuditRec(rctx, auditRec, nil)
}
}
return nil
@ -165,6 +166,8 @@ func buildExportCmdF(format string) func(command *cobra.Command, args []string)
}
defer a.Srv().Shutdown()
rctx := request.EmptyContext(a.Log())
startTime, err := command.Flags().GetInt64("exportFrom")
if err != nil {
return errors.New("exportFrom flag error")
@ -182,7 +185,7 @@ func buildExportCmdF(format string) func(command *cobra.Command, args []string)
return errors.New("message export feature not available")
}
warningsCount, appErr := a.MessageExport().RunExport(request.EmptyContext(a.Log()), format, startTime, limit)
warningsCount, appErr := a.MessageExport().RunExport(rctx, format, startTime, limit)
if appErr != nil {
return appErr
}
@ -196,10 +199,10 @@ func buildExportCmdF(format string) func(command *cobra.Command, args []string)
}
}
auditRec := a.MakeAuditRecord("buildExport", audit.Success)
auditRec := a.MakeAuditRecord(rctx, "buildExport", audit.Success)
auditRec.AddMeta("format", format)
auditRec.AddMeta("start", startTime)
a.LogAuditRec(auditRec, nil)
a.LogAuditRec(rctx, auditRec, nil)
return nil
}
@ -212,6 +215,8 @@ func bulkExportCmdF(command *cobra.Command, args []string) error {
}
defer a.Srv().Shutdown()
rctx := request.EmptyContext(a.Log())
allTeams, err := command.Flags().GetBool("all-teams")
if err != nil {
return errors.Wrap(err, "all-teams flag error")
@ -250,15 +255,15 @@ func bulkExportCmdF(command *cobra.Command, args []string) error {
opts.IncludeAttachments = attachments
opts.CreateArchive = archive
opts.IncludeArchivedChannels = withArchivedChannels
if err := a.BulkExport(request.EmptyContext(a.Log()), fileWriter, filepath.Dir(outPath), nil /* nil job since it's spawned from CLI */, opts); err != nil {
if err := a.BulkExport(rctx, fileWriter, filepath.Dir(outPath), nil /* nil job since it's spawned from CLI */, opts); err != nil {
CommandPrintErrorln(err.Error())
return err
}
auditRec := a.MakeAuditRecord("bulkExport", audit.Success)
auditRec := a.MakeAuditRecord(rctx, "bulkExport", audit.Success)
auditRec.AddMeta("all_teams", allTeams)
auditRec.AddMeta("file", args[0])
a.LogAuditRec(auditRec, nil)
a.LogAuditRec(rctx, auditRec, nil)
return nil
}

View File

@ -57,6 +57,8 @@ func slackImportCmdF(command *cobra.Command, args []string) error {
}
defer a.Srv().Shutdown()
rctx := request.EmptyContext(a.Log())
if len(args) != 2 {
return errors.New("Incorrect number of arguments.")
}
@ -79,7 +81,7 @@ func slackImportCmdF(command *cobra.Command, args []string) error {
CommandPrettyPrintln("Running Slack Import. This may take a long time for large teams or teams with many messages.")
importErr, log := a.SlackImport(request.EmptyContext(a.Log()), fileReader, fileInfo.Size(), team.Id)
importErr, log := a.SlackImport(rctx, fileReader, fileInfo.Size(), team.Id)
if importErr != nil {
return err
@ -92,10 +94,10 @@ func slackImportCmdF(command *cobra.Command, args []string) error {
CommandPrettyPrintln("Finished Slack Import.")
CommandPrettyPrintln("")
auditRec := a.MakeAuditRecord("slackImport", audit.Success)
auditRec := a.MakeAuditRecord(rctx, "slackImport", audit.Success)
auditRec.AddMeta("team", team)
auditRec.AddMeta("file", args[1])
a.LogAuditRec(auditRec, nil)
a.LogAuditRec(rctx, auditRec, nil)
return nil
}
@ -107,6 +109,8 @@ func bulkImportCmdF(command *cobra.Command, args []string) error {
}
defer a.Srv().Shutdown()
rctx := request.EmptyContext(a.Log())
apply, err := command.Flags().GetBool("apply")
if err != nil {
return errors.New("Apply flag error")
@ -152,7 +156,7 @@ func bulkImportCmdF(command *cobra.Command, args []string) error {
CommandPrettyPrintln("")
if err, lineNumber := a.BulkImportWithPath(request.EmptyContext(a.Log()), fileReader, nil, !apply, workers, importPath); err != nil {
if err, lineNumber := a.BulkImportWithPath(rctx, fileReader, nil, !apply, workers, importPath); err != nil {
CommandPrintErrorln(err.Error())
if lineNumber != 0 {
CommandPrintErrorln(fmt.Sprintf("Error occurred on data file line %v", lineNumber))
@ -162,9 +166,9 @@ func bulkImportCmdF(command *cobra.Command, args []string) error {
if apply {
CommandPrettyPrintln("Finished Bulk Import.")
auditRec := a.MakeAuditRecord("bulkImport", audit.Success)
auditRec := a.MakeAuditRecord(rctx, "bulkImport", audit.Success)
auditRec.AddMeta("file", args[0])
a.LogAuditRec(auditRec, nil)
a.LogAuditRec(rctx, auditRec, nil)
} else {
CommandPrettyPrintln("Validation complete. You can now perform the import by rerunning this command with the --apply flag.")
}

View File

@ -11,6 +11,7 @@ import (
"github.com/spf13/cobra"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/app"
"github.com/mattermost/mattermost/server/v8/channels/audit"
"github.com/mattermost/mattermost/server/v8/config"
@ -43,6 +44,8 @@ func jobserverCmdF(command *cobra.Command, args []string) error {
a.Srv().LoadLicense()
rctx := request.EmptyContext(a.Log())
// Run jobs
mlog.Info("Starting Mattermost job server")
defer mlog.Info("Stopped Mattermost job server")
@ -57,8 +60,8 @@ func jobserverCmdF(command *cobra.Command, args []string) error {
}
if !noJobs || !noSchedule {
auditRec := a.MakeAuditRecord("jobServer", audit.Success)
a.LogAuditRec(auditRec, nil)
auditRec := a.MakeAuditRecord(rctx, "jobServer", audit.Success)
a.LogAuditRec(rctx, auditRec, nil)
}
signalChan := make(chan os.Signal, 1)