Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions api/v4/source/content_flagging.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -441,3 +441,44 @@
description: Internal server error.
'501':
description: Feature is disabled either via config or an Enterprise Advanced license is not available.

/api/v4/content_flagging/post/{post_id}/exposure_report:
post:
summary: Generate and download a post exposure report
description: |
Generates a CSV report listing the users who may have been exposed to a flagged post, derived from the channel membership history between the post's creation and it being flagged, and from each member's channel read state. All other content reviewers of the post's team are notified that an exposure report has been generated.
The user must be a content reviewer of the team to which the post belongs to, and the post must be flagged. The report remains available after the review is closed, in any status.
Exposure reports are not available for direct or group message channels.
An enterprise advanced license is required.
tags:
- Content Flagging
parameters:
- in: path
name: post_id
required: true
schema:
type: string
description: The ID of the flagged post to generate the exposure report for
operationId: GenerateCFPostExposureReport
responses:
'200':
description: Report generated successfully. The response body is a CSV file. Metadata and the reporting window are emitted as `#`-prefixed comment lines above the header row.
headers:
Content-Disposition:
schema:
type: string
description: Specifies the suggested filename for the downloaded file (e.g. `attachment; filename="post-exposure-{post_id}-{timestamp}.csv"`).
content:
text/csv:
schema:
type: string
'400':
description: Bad request - Invalid post ID, or the post is in a direct or group message channel.
'403':
description: Forbidden - User does not have permission to access this post, or is not a reviewer of the post's team.
'404':
description: Post not found or post is not flagged.
'500':
description: Internal server error.
'501':
description: Feature is disabled either via config or an Enterprise Advanced license is not available.
1 change: 1 addition & 0 deletions server/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ Never run `go mod tidy` directly. Always run `make modules-tidy` instead — it

After editing `i18n/en.json`, always run `make i18n-extract` — it regenerates the file with strings in the required order.

Prefer request-scoped loggers when logging from request paths. If a method needs to log and does not have access to the request logger, it is reasonable to add `request.CTX` to the method signature when the caller can provide it.
In the store layer, do not use `context.Context` in store method signatures. Use `request.CTX` and only call `rctx.Context()` inside internals that require a standard `context.Context`.
1 change: 1 addition & 0 deletions server/channels/api4/content_flagging.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func (api *API) InitContentFlagging() {
api.BaseRoutes.ContentFlagging.Handle("/post/{post_id:[A-Za-z0-9]+}/remove", api.APISessionRequired(contentFlaggingRequired(removeFlaggedPost))).Methods(http.MethodPut)
api.BaseRoutes.ContentFlagging.Handle("/post/{post_id:[A-Za-z0-9]+}/keep", api.APISessionRequired(contentFlaggingRequired(keepFlaggedPost))).Methods(http.MethodPut)
api.BaseRoutes.ContentFlagging.Handle("/post/{post_id:[A-Za-z0-9]+}/report", api.APISessionRequired(contentFlaggingRequired(generateFlaggedPostReport))).Methods(http.MethodPost)
api.BaseRoutes.ContentFlagging.Handle("/post/{post_id:[A-Za-z0-9]+}/exposure_report", api.APISessionRequired(contentFlaggingRequired(generatePostExposureReport))).Methods(http.MethodPost)
api.BaseRoutes.ContentFlagging.Handle("/team/{team_id:[A-Za-z0-9]+}/reviewers/search", api.APISessionRequired(contentFlaggingRequired(searchReviewers))).Methods(http.MethodGet)
api.BaseRoutes.ContentFlagging.Handle("/post/{post_id:[A-Za-z0-9]+}/assign/{content_reviewer_id:[A-Za-z0-9]+}", api.APISessionRequired(contentFlaggingRequired(assignFlaggedPostReviewer))).Methods(http.MethodPost)

Expand Down
66 changes: 66 additions & 0 deletions server/channels/api4/content_flagging_report.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package api4

import (
"bytes"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -106,3 +107,68 @@ func generateFlaggedPostReport(c *Context, w http.ResponseWriter, r *http.Reques

auditRec.Success()
}

func generatePostExposureReport(c *Context, w http.ResponseWriter, r *http.Request) {
if c.Err != nil {
return
}

c.RequirePostId()
if c.Err != nil {
return
}

postId := c.Params.PostId
userId := c.AppContext.Session().UserId

auditRec := c.MakeAuditRecord(model.AuditEventGeneratePostExposureReport, model.AuditStatusFail)
defer c.LogAuditRecWithLevel(auditRec, app.LevelContent)
model.AddEventParameterToAuditRec(auditRec, "flaggedPostId", postId)
model.AddEventParameterToAuditRec(auditRec, "userId", userId)

post, appErr := c.App.GetSinglePost(c.AppContext, postId, true)
if appErr != nil {
c.Err = appErr
return
}

channel, appErr := c.App.GetChannel(c.AppContext, post.ChannelId)
if appErr != nil {
c.Err = appErr
return
}

requireTeamContentReviewer(c, userId, channel.TeamId)
if c.Err != nil {
return
}

requireFlaggedPost(c, postId)
if c.Err != nil {
return
}

report, appErr := c.App.ComputePostExposure(c.AppContext, postId)
if appErr != nil {
c.Err = appErr
return
}

var buf bytes.Buffer
if err := app.WritePostExposureCSV(&buf, report, c.AppContext.GetT()); err != nil {
c.Err = model.NewAppError("generatePostExposureReport", "api.data_spillage.exposure.write.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
return
}

c.App.NotifyReviewersOfPostExposureReportGeneration(c.AppContext, postId, userId)

filename := fmt.Sprintf("post-exposure-%s-%d.csv", postId, model.GetMillis())
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
if _, err := w.Write(buf.Bytes()); err != nil {
c.Logger.Warn("Failed to write post exposure report response", mlog.String("post_id", postId), mlog.Err(err))
return
}

auditRec.Success()
}
208 changes: 208 additions & 0 deletions server/channels/api4/content_flagging_report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import (
"archive/zip"
"bytes"
"context"
"encoding/csv"
"io"
"net/http"
"testing"

"github.com/goccy/go-yaml"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -230,3 +232,209 @@ func TestGenerateFlaggedPostReport(t *testing.T) {
require.Empty(t, report)
})
}

// parseExposureCSV skips the "#"-prefixed metadata preamble and returns the remaining records.
func parseExposureCSV(t *testing.T, b []byte) [][]string {
t.Helper()

r := csv.NewReader(bytes.NewReader(b))
r.Comment = '#'
records, err := r.ReadAll()
require.NoError(t, err)
return records
}

func TestGeneratePostExposureReport(t *testing.T) {
th := Setup(t).InitBasic(t)

client := th.Client
th.App.Srv().SetLicense(model.NewTestLicenseSKU(model.LicenseShortSkuEnterpriseAdvanced))
defer th.RemoveLicense(t)

t.Run("Should return 501 when feature is disabled", func(t *testing.T) {
th.App.UpdateConfig(func(config *model.Config) {
config.ContentFlaggingSettings.EnableContentFlagging = model.NewPointer(false)
config.ContentFlaggingSettings.SetDefaults()
})

post := th.CreatePost(t)
report, resp, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.Error(t, err)
require.Equal(t, http.StatusNotImplemented, resp.StatusCode)
require.Empty(t, report)
})

t.Run("Should return 400 when post ID is invalid", func(t *testing.T) {
appErr := setBasicCommonReviewerConfig(th)
require.Nil(t, appErr)

report, resp, err := client.GeneratePostExposureReport(context.Background(), "invalid")
require.Error(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
require.Empty(t, report)
})

t.Run("Should return 403 when user is not a reviewer", func(t *testing.T) {
appErr := setNonReviewerConfig(th)
require.Nil(t, appErr)

post := th.CreatePost(t)
report, resp, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.Error(t, err)
require.Equal(t, http.StatusForbidden, resp.StatusCode)
require.Empty(t, report)
})

t.Run("Should return 404 when post is not flagged", func(t *testing.T) {
appErr := setBasicCommonReviewerConfig(th)
require.Nil(t, appErr)

post := th.CreatePost(t)
report, resp, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.Error(t, err)
require.Equal(t, http.StatusNotFound, resp.StatusCode)
require.Empty(t, report)
})

t.Run("Should successfully generate report when the post has already been retained", func(t *testing.T) {
appErr := setBasicCommonReviewerConfig(th)
require.Nil(t, appErr)

post := th.CreatePost(t)
flagPostViaAPI(t, client, post.Id)

resp, err := client.KeepFlaggedPost(context.Background(), post.Id, &model.FlagContentActionRequest{Comment: "looks fine"})
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)

report, resp, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.NotEmpty(t, report)

require.Contains(t, resp.Header.Get("Content-Type"), "text/csv")
require.Contains(t, resp.Header.Get("Content-Disposition"), "attachment; filename=\"post-exposure-"+post.Id)
})

t.Run("Should successfully generate report when the post has already been removed", func(t *testing.T) {
appErr := setBasicCommonReviewerConfig(th)
require.Nil(t, appErr)

post := th.CreatePost(t)
flagPostViaAPI(t, client, post.Id)

resp, err := client.RemoveFlaggedPost(context.Background(), post.Id, &model.FlagContentActionRequest{Comment: "confirmed spillage"})
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)

// Removal scrubs the post's content but retains a stub row, and it never deletes
// the reporting_time property, so the exposure window is still computable.
report, resp, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.NotEmpty(t, report)

require.Contains(t, resp.Header.Get("Content-Type"), "text/csv")
require.Contains(t, resp.Header.Get("Content-Disposition"), "attachment; filename=\"post-exposure-"+post.Id)
})

t.Run("Should successfully generate report for a common reviewer", func(t *testing.T) {
appErr := setBasicCommonReviewerConfig(th)
require.Nil(t, appErr)

post := th.CreatePost(t)
flagPostViaAPI(t, client, post.Id)

report, resp, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.NotEmpty(t, report)

require.Contains(t, resp.Header.Get("Content-Type"), "text/csv")
require.Contains(t, resp.Header.Get("Content-Disposition"), "attachment; filename=\"post-exposure-"+post.Id)
})

t.Run("Should successfully generate report when user is a team reviewer", func(t *testing.T) {
appErr := setBasicTeamReviewerConfig(th)
require.Nil(t, appErr)

post := th.CreatePost(t)
flagPostViaAPI(t, client, post.Id)

report, resp, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.NotEmpty(t, report)
})

t.Run("Should generate report for both the assignee and a non-assignee reviewer", func(t *testing.T) {
appErr := setBasicCommonReviewerConfig(th, th.BasicUser2.Id)
require.Nil(t, appErr)

post := th.CreatePost(t)
flagPostViaAPI(t, client, post.Id)

resp, err := client.AssignContentFlaggingReviewer(context.Background(), post.Id, th.BasicUser2.Id)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)

// BasicUser is a reviewer but not the assignee.
report, resp, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.NotEmpty(t, report)

// BasicUser2 is the assignee, and is therefore also a reviewer.
assigneeClient := th.CreateClient()
th.LoginBasic2WithClient(t, assigneeClient)

report, resp, err = assigneeClient.GeneratePostExposureReport(context.Background(), post.Id)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.NotEmpty(t, report)
})

t.Run("Should return a parseable CSV listing the channel members", func(t *testing.T) {
appErr := setBasicCommonReviewerConfig(th)
require.Nil(t, appErr)

post := th.CreatePost(t)
flagPostViaAPI(t, client, post.Id)

report, _, err := client.GeneratePostExposureReport(context.Background(), post.Id)
require.NoError(t, err)

body := string(report)
require.Contains(t, body, "# Post ID: "+post.Id)
require.Contains(t, body, "# Report version: "+model.PostExposureReportVersion)

records := parseExposureCSV(t, report)
require.NotEmpty(t, records)
require.Equal(t, model.PostExposureReportCSVHeader(i18n.GetUserTranslations("en")), records[0])

var found bool
for _, record := range records[1:] {
if record[0] == th.BasicUser.Id {
found = true
require.Equal(t, th.BasicUser.Username, record[1])
}
}
require.True(t, found, "the post author is a channel member and must appear in the report")
})

t.Run("Should return 403 in team reviewer mode for a user not on the team's reviewer list", func(t *testing.T) {
appErr := setBasicTeamReviewerConfig(th)
require.Nil(t, appErr)

post := th.CreatePost(t)
flagPostViaAPI(t, client, post.Id)

otherClient := th.CreateClient()
th.LoginBasic2WithClient(t, otherClient)

report, resp, err := otherClient.GeneratePostExposureReport(context.Background(), post.Id)
require.Error(t, err)
require.Equal(t, http.StatusForbidden, resp.StatusCode)
require.Empty(t, report)
})
}
6 changes: 4 additions & 2 deletions server/channels/api4/content_flagging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ import (
"github.com/stretchr/testify/require"
)

func setBasicCommonReviewerConfig(th *TestHelper) *model.AppError {
func setBasicCommonReviewerConfig(th *TestHelper, extraReviewerIds ...string) *model.AppError {
ids := []string{th.BasicUser.Id}
ids = append(ids, extraReviewerIds...)
config := model.ContentFlaggingSettingsRequest{
ContentFlaggingSettingsBase: model.ContentFlaggingSettingsBase{
EnableContentFlagging: new(true),
Expand All @@ -25,7 +27,7 @@ func setBasicCommonReviewerConfig(th *TestHelper) *model.AppError {
CommonReviewers: new(true),
},
ReviewerIDsSettings: model.ReviewerIDsSettings{
CommonReviewerIds: []string{th.BasicUser.Id},
CommonReviewerIds: ids,
},
},
}
Expand Down
4 changes: 2 additions & 2 deletions server/channels/api4/scheduled_post.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ func updateScheduledPost(c *Context, w http.ResponseWriter, r *http.Request) {
model.AddEventParameterAuditableToAuditRec(auditRec, "scheduledPost", &scheduledPost)

userId := c.AppContext.Session().UserId
existingScheduledPost, err := c.App.Srv().Store().ScheduledPost().Get(scheduledPost.Id)
existingScheduledPost, err := c.App.Srv().Store().ScheduledPost().Get(c.AppContext, scheduledPost.Id)
if err != nil {
c.Err = model.NewAppError("updateScheduledPost", "app.update_scheduled_post.get_scheduled_post.error", nil, "", http.StatusInternalServerError).Wrap(err)
return
Expand Down Expand Up @@ -283,7 +283,7 @@ func deleteScheduledPost(c *Context, w http.ResponseWriter, r *http.Request) {

userId := c.AppContext.Session().UserId

existingScheduledPost, err := c.App.Srv().Store().ScheduledPost().Get(scheduledPostId)
existingScheduledPost, err := c.App.Srv().Store().ScheduledPost().Get(c.AppContext, scheduledPostId)
if err != nil {
c.Err = model.NewAppError("deleteScheduledPost", "app.delete_scheduled_post.get_scheduled_post.error", nil, "", http.StatusInternalServerError).Wrap(err)
return
Expand Down
Loading
Loading