Files
07e56271fd Feature mm 64509 team admin abac channels (#36061)
* MM-67592 - be changes for team admin abac channels (#35353)

* MM-67592 - be changes for team admin abac channels

* Revert team-scoped API routes, keep app layer business logic

* move from config to permission; Add cluster-aware LRU cache for policy team scope lookup

* remove unnecessary references to config value

* local/remote cache invalidation consistency for policy scope

* Replace policy scope cache with store-level team scope query

* rename functions and add comments to query

---------

Co-authored-by: Mattermost Build <[email protected]>

* MM 67594 - policies CUD operations to team settings modal channels ABAC (#35590)

* MM-67592 - be changes for team admin abac channels

* Revert team-scoped API routes, keep app layer business logic

* move from config to permission; Add cluster-aware LRU cache for policy team scope lookup

* remove unnecessary references to config value

* local/remote cache invalidation consistency for policy scope

* Replace policy scope cache with store-level team scope query

* format files correctly

* fix mock expectations for store-query approach in tests

* rename functions and add comments to query

* revert error ids to original to prevent break tests

* adjust translations

* MM-67669 - add tab to team settings modal and basic listing

* adjust tests and fix linter

* use existing search api logic

* fix style and adjust flaky test to clean up and restore orinals

* address ai corabbit feedback and fix linter

* fix unit tests

* MM-67592 - be changes for team admin abac channels (#35353)

* MM-67592 - be changes for team admin abac channels

* fix linter

* fix ts linter for playwright

* Revert team-scoped API routes, keep app layer business logic

* move from config to permission; Add cluster-aware LRU cache for policy team scope lookup

* remove unnecessary references to config value

* local/remote cache invalidation consistency for policy scope

* Replace policy scope cache with store-level team scope query

* format files correctly

* fix mock expectations for store-query approach in tests

* rename functions and add comments to query

* revert error ids to original to prevent break tests

* adjust translations

---------

Co-authored-by: Mattermost Build <[email protected]>

* MM-67594 - support cud operations for team abac BE changes

* create the team settings policy edit section, reuse most components, add basic e2e

* move optional refresh policy list button to list component

* temp get team admins cud policies and sync job

* enhance validation and adjust e2e

* Fix testExpression permission; fix pagination of team policies; add isValidId validation

* adjust styles, handling renaming and add permission migrations

* update the permissions names, use the simple confirmation modal, define the delete modal

* fix policy deletion flow

* fix some linter issues and adjust helper tests

* remove delete from list and fix e2e

* code comments clean up

* remove CEL editor for now, clean styles, enhance e2e

* fix linter, adjust unit test

* fix linter and add missing translation

* fix policy deletion ownership and sanitize test expression

* fixed e2e tests

* rollback orphaned policy on failed channel assignment

* enforce channelless check before last_team_id fallback

* enforce channelless guard on assign fallback too

* add translations missing

* add teamId to audit payload when present

* fix refresh button pagination reset

* fix null safety in channel selector loadChannels

* use responsive width cap for team settings modal and adjust header size

* remove redundant raw term from channel search URL, add showRefreshButton prop to PolicyList component

* handle error when stamping last team ID on channelless policy

* replace Props-based ownership with in-memory LRU cache, disable save on zero channels

* make e2e tests more reliable in CI

* test skip if no license valid found

* add childCount guard to cache-hit paths and reduce TTL to 5s

* fix e2e, adjust translation

* address review feedback: flatten permission checks and separate error types

- Flatten nested permission branching in deleteAccessControlPolicy using
  early returns to reduce indentation (review: isacikgoz)
- Validate teamID as input (400) before using it for permission checks (403)
  in testExpression and validateExpressionAgainstRequester handlers
- Remove redundant hasSystemPermission check in searchAccessControlPolicies
  since system_admin role already includes manage_team_access_rules
- Refactor ValidateTeamAdminPolicyOwnership to return (bool, *model.AppError)
  separating "not owned" from "internal error" across all 8 call sites
- Update tests to assert on both return values

* add persistent team scope to access control policies, replace in-memory cache

* fix translation

* fix case-insensitive policy search and sanitize search term input

* make policies tests have a unique name

* decouple scope/scopeID filter from TeamID in policy store

* Fix authZ bypass searchChannelsForAccessControlPolicy by forcing TeamIds to authorized team

* show unsaved changes on navigator back, and list all private channels on load

* filter already applied channels to a policy

* adjust the styles to dark mode; do not show added channels to the policy in the add channels modal

* fix linter

* MM-67967 add sync status footer to team settings (#35729)

* MM-67967 add sync status footer to team settings

* remove magic numbers and strings and polish the code

* fix linter

* fix linter: replace interface{} with any per gofmt rewrite rule

* refine getJobsByType team-scoped filtering and permissions

* fix sync footer stuck in syncing state on job creation error

* fix team-scoped job pagination in getJobsByType

* Fix authZ bypass searchChannelsForAccessControlPolicy by forcing TeamIds to authorized team

* implement ux feedback, change titles font, fix marging and scroll view jump

* MM-68135 - migrate add channels to policy modal to generic modal (#35907)

* MM-67920 unify e2e team settings tests (#35867)

* MM-67920 - extract duplicated policy editor helpers

* remove duplicate team icon test file

* rename Access Control to Membership Policies in e2e

* replace networkidle with explicit element waits

* fix attribute loading issue

---------

---------

Co-authored-by: Mattermost Build <[email protected]>

* fix playwright feedback issues and persist filters to the store layer in the no systemconsole path

* Improve policy scope validation and team admin security checks

* Renamed public channels to "AAA Public Channel %03d" and private ones to "ZZZ Private..." so the 55 public channels now fill the 50-result cap

* fix e2e tests and add new unit tests to improve coverage

* Improve e2e test stability: race condition handling and timeout adjustments

* Improve team-scoped ABAC policies: scope preservation, input validation, shared exclusion

* Add comprehensive ABAC test coverage: team admin ops and security validation to reduce flakyness

* Fix team policy editor back button: preserve navigation intent through Undo

* style: format import statements for better readability

* Enhance access control policy creation for team admins: enforce scope stamping from query parameters to prevent unauthorized team assignments

---------

Co-authored-by: Mattermost Build <[email protected]>

Co-authored-by: Hanzo Dev <[email protected]>
2026-04-16 00:48:43 +02:00

438 lines
13 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package api4
import (
"encoding/json"
"net/http"
"path"
"path/filepath"
"sort"
"strconv"
"time"
"github.com/mattermost/mattermost/server/v8/platform/shared/filestore"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/v8/platform/shared/web"
)
func (api *API) InitJob() {
api.BaseRoutes.Jobs.Handle("", api.APISessionRequired(getJobs)).Methods(http.MethodGet)
api.BaseRoutes.Jobs.Handle("", api.APISessionRequired(createJob)).Methods(http.MethodPost)
api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}", api.APISessionRequired(getJob)).Methods(http.MethodGet)
api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/download", api.APISessionRequiredTrustRequester(downloadJob)).Methods(http.MethodGet)
api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/cancel", api.APISessionRequired(cancelJob)).Methods(http.MethodPost)
api.BaseRoutes.Jobs.Handle("/type/{job_type:[A-Za-z0-9_-]+}", api.APISessionRequired(getJobsByType)).Methods(http.MethodGet)
api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/status", api.APISessionRequired(updateJobStatus)).Methods(http.MethodPatch)
}
func getJob(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireJobId()
if c.Err != nil {
return
}
job, err := c.App.GetJob(c.AppContext, c.Params.JobId)
if err != nil {
c.Err = err
return
}
hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), job.Type)
if permissionRequired == nil {
c.Err = model.NewAppError("getJob", "api.job.retrieve.nopermissions", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
if err := json.NewEncoder(w).Encode(job); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) {
config := c.App.Config()
const oldFilePath = "export"
const FileMime = "application/zip"
c.RequireJobId()
if c.Err != nil {
return
}
if !*config.MessageExportSettings.DownloadExportResults {
c.Err = model.NewAppError("downloadExportResultsNotEnabled", "app.job.download_export_results_not_enabled", nil, "", http.StatusNotImplemented)
return
}
job, err := c.App.GetJob(c.AppContext, c.Params.JobId)
if err != nil {
c.Err = err
return
}
// Currently, this endpoint only supports downloading the compliance report.
// If you need to download another job type, you will need to alter this section of the code to accommodate it.
if job.Type == model.JobTypeMessageExport && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionDownloadComplianceExportResult) {
c.SetPermissionError(model.PermissionDownloadComplianceExportResult)
return
} else if job.Type != model.JobTypeMessageExport {
c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job.incorrect_job_type", nil, "", http.StatusBadRequest)
return
}
isDownloadable, _ := strconv.ParseBool(job.Data["is_downloadable"])
if !isDownloadable {
c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job", nil, "", http.StatusBadRequest)
return
}
exportDir, ok := job.Data["export_dir"]
fileName := path.Base(exportDir)
if !ok || exportDir == "" || fileName == "/" || fileName == "." {
// Could be a pre-overhaul job. Try the old method:
fileName = job.Id + ".zip"
filePath := filepath.Join(oldFilePath, fileName)
var fileReader filestore.ReadCloseSeeker
fileReader, err = c.App.ExportFileReader(filePath)
if err != nil {
c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job", nil,
"job.Data did not include export_dir, export_dir was malformed, or jobId.zip wasn't found",
http.StatusNotFound).Wrap(err)
return
}
defer fileReader.Close()
// We are able to pass 0 for content size due to the fact that Golang's serveContent (https://golang.org/src/net/http/fs.go)
// already sets that for us
web.WriteFileResponse(fileName, FileMime, 0, time.UnixMilli(job.LastActivityAt), *c.App.Config().ServiceSettings.WebserverMode, fileReader, true, w, r)
return
}
// We have a base directory, we're using that as the exported filename:
fileName += ".zip"
cleanedExportDir := filepath.Clean(exportDir)
if !filepath.IsLocal(cleanedExportDir) {
c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job", nil,
"job.Data did not include export_dir, export_dir was malformed, or jobId.zip wasn't found",
http.StatusNotFound)
return
}
zipReader, err := c.App.ExportZipReader(cleanedExportDir, false)
if err != nil {
c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job", nil,
"error creating zip reader", http.StatusNotFound).Wrap(err)
return
}
defer zipReader.Close()
if err := web.WriteStreamResponse(w, zipReader, fileName, FileMime, true); err != nil {
c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job", nil,
"failure to WriteStreamResponse", http.StatusInternalServerError).
Wrap(err)
return
}
}
func createJob(c *Context, w http.ResponseWriter, r *http.Request) {
var job model.Job
if jsonErr := json.NewDecoder(r.Body).Decode(&job); jsonErr != nil {
c.SetInvalidParamWithErr("job", jsonErr)
return
}
auditRec := c.MakeAuditRecord(model.AuditEventCreateJob, model.AuditStatusFail)
defer c.LogAuditRec(auditRec)
model.AddEventParameterAuditableToAuditRec(auditRec, "job", &job)
hasPermission, permissionRequired := c.App.SessionHasPermissionToCreateJob(*c.AppContext.Session(), &job)
if permissionRequired == nil {
c.Err = model.NewAppError("unableToCreateJob", "api.job.unable_to_create_job.incorrect_job_type", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
// Inject requester context for self-inclusion resolution.
if job.Type == model.JobTypeAccessControlSync {
if job.Data == nil {
job.Data = make(model.StringMap)
}
job.Data["requester_id"] = c.AppContext.Session().UserId
if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) {
job.Data["requester_is_admin"] = "true"
} else {
delete(job.Data, "requester_is_admin")
}
}
rjob, err := c.App.CreateJob(c.AppContext, &job)
if err != nil {
c.Err = err
return
}
auditRec.Success()
auditRec.AddEventResultState(rjob)
auditRec.AddEventObjectType("job")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(rjob); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func getJobs(c *Context, w http.ResponseWriter, r *http.Request) {
if c.Err != nil {
return
}
jobType := r.URL.Query().Get("job_type")
var validJobTypes []string
if jobType != "" {
isValidJobType := model.IsValidJobType(jobType)
if !isValidJobType {
c.SetInvalidURLParam("job_type")
return
}
hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), jobType)
if permissionRequired == nil {
c.Err = model.NewAppError("getJobsByType", "api.job.retrieve.nopermissions", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
validJobTypes = append(validJobTypes, jobType)
} else {
for _, jType := range model.AllJobTypes {
hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), jType)
if permissionRequired == nil {
c.Logger.Warn("The job types of a job you are trying to retrieve does not contain permissions", mlog.String("jobType", jType))
continue
}
if hasPermission {
validJobTypes = append(validJobTypes, jType)
}
}
}
if len(validJobTypes) == 0 {
c.SetPermissionError()
return
}
status := r.URL.Query().Get("status")
isValidStatus := model.IsValidJobStatus(status)
if status != "" && !isValidStatus {
c.Err = model.NewAppError("getJobs", "api.job.status.invalid", nil, "", http.StatusBadRequest)
}
var jobs []*model.Job
var appErr *model.AppError
if status == "" {
jobs, appErr = c.App.GetJobsByTypesPage(c.AppContext, validJobTypes, c.Params.Page, c.Params.PerPage)
} else {
jobs, appErr = c.App.GetJobsByTypesAndStatuses(c.AppContext, validJobTypes, []string{status}, c.Params.Page, c.Params.PerPage)
}
if appErr != nil {
c.Err = appErr
return
}
js, err := json.Marshal(jobs)
if err != nil {
c.Err = model.NewAppError("getJobs", "api.marshal_error", nil, "", http.StatusInternalServerError).Wrap(err)
return
}
if _, err := w.Write(js); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func getJobsByType(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireJobType()
if c.Err != nil {
return
}
hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), c.Params.JobType)
if permissionRequired == nil {
c.Err = model.NewAppError("getJobsByType", "api.job.retrieve.nopermissions", nil, "", http.StatusBadRequest)
return
}
// Team admin path: allow reading access_control_sync jobs scoped to their team.
teamID := r.URL.Query().Get("team_id")
hasTeamFilter := false
if teamID != "" {
if !model.IsValidId(teamID) {
c.SetInvalidURLParam("team_id")
return
}
hasTeamFilter = true
}
isTeamScopedSyncRequest := !hasPermission &&
c.Params.JobType == model.JobTypeAccessControlSync &&
hasTeamFilter &&
c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamID, model.PermissionManageTeamAccessRules)
if !hasPermission && !isTeamScopedSyncRequest {
c.SetPermissionError(permissionRequired)
return
}
var jobs []*model.Job
if hasTeamFilter {
// When team_id is provided, return only jobs scoped to that team.
// Sorted by CreateAt DESC; limited to the requested page size.
teamJobs, appErr := c.App.GetJobsByTypeAndData(c.AppContext, c.Params.JobType, map[string]string{"team_id": teamID})
if appErr != nil {
c.Err = appErr
return
}
sort.Slice(teamJobs, func(i, j int) bool {
return teamJobs[i].CreateAt > teamJobs[j].CreateAt
})
start := c.Params.Page * c.Params.PerPage
if start >= len(teamJobs) {
jobs = []*model.Job{}
} else {
end := min(start+c.Params.PerPage, len(teamJobs))
jobs = teamJobs[start:end]
}
} else {
// Store returns jobs ordered by CreateAt DESC; pagination applied at the store level.
var appErr *model.AppError
jobs, appErr = c.App.GetJobsByTypePage(c.AppContext, c.Params.JobType, c.Params.Page, c.Params.PerPage)
if appErr != nil {
c.Err = appErr
return
}
}
js, err := json.Marshal(jobs)
if err != nil {
c.Err = model.NewAppError("getJobsByType", "api.marshal_error", nil, "", http.StatusInternalServerError).Wrap(err)
return
}
if _, err := w.Write(js); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func cancelJob(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireJobId()
if c.Err != nil {
return
}
auditRec := c.MakeAuditRecord(model.AuditEventCancelJob, model.AuditStatusFail)
defer c.LogAuditRec(auditRec)
model.AddEventParameterToAuditRec(auditRec, "job_id", c.Params.JobId)
job, err := c.App.GetJob(c.AppContext, c.Params.JobId)
if err != nil {
c.Err = err
return
}
auditRec.AddEventPriorState(job)
auditRec.AddEventObjectType("job")
// if permission to create, permission to cancel, same permission
hasPermission, permissionRequired := c.App.SessionHasPermissionToCreateJob(*c.AppContext.Session(), job)
if permissionRequired == nil {
c.Err = model.NewAppError("unableToCancelJob", "api.job.unable_to_create_job.incorrect_job_type", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
if err := c.App.CancelJob(c.AppContext, c.Params.JobId); err != nil {
c.Err = err
return
}
auditRec.Success()
ReturnStatusOK(w)
}
func updateJobStatus(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireJobId()
if c.Err != nil {
return
}
auditRec := c.MakeAuditRecord(model.AuditEventUpdateJobStatus, model.AuditStatusFail)
defer c.LogAuditRec(auditRec)
model.AddEventParameterToAuditRec(auditRec, "job_id", c.Params.JobId)
props := model.StringInterfaceFromJSON(r.Body)
status, ok := props["status"].(string)
if !ok {
c.SetInvalidParam("status")
return
}
force, ok := props["force"].(bool)
if !ok {
force = false
}
job, err := c.App.GetJob(c.AppContext, c.Params.JobId)
if err != nil {
c.Err = err
return
}
auditRec.AddEventPriorState(job)
auditRec.AddEventObjectType("job")
hasPermission, permissionRequired := c.App.SessionHasPermissionToManageJob(*c.AppContext.Session(), job)
if permissionRequired == nil {
c.Err = model.NewAppError("updateJobStatus", "api.job.unable_to_manage_job.incorrect_job_type", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
if !force && !job.IsValidStatusChange(status) {
c.Err = model.NewAppError("updateJobStatus", "api.job.status.invalid", nil, "", http.StatusBadRequest)
return
}
if err := c.App.UpdateJobStatus(c.AppContext, job, status); err != nil {
c.Err = err
return
}
auditRec.Success()
ReturnStatusOK(w)
}