Files
upstream-mattermost/server/channels/api4/integration_action.go
upstream-mirror 240db4e2a7
Some checks failed
Server CI / Postgres (shard 0) (push) Has been skipped
Server CI / Postgres (shard 3) (push) Has been skipped
BuildEnv Docker Image / build-image (push) Failing after 4s
BuildEnv Docker Image / build-image-fips (push) Failing after 4s
Migration Review & Release Notes / Generate migration review & release notes (push) Failing after 3s
Server CI / Build Environment (push) Failing after 3s
Server CI / Postgres (shard 1) (push) Has been skipped
Tools CI / check-style (mattermost-govet) (push) Failing after 4s
Server CI / Postgres (shard 2) (push) Has been skipped
Tools CI / check-style (mmgotool) (push) Failing after 3s
Server CI / Elasticsearch v8 Compatibility (push) Has been skipped
Server CI / OpenSearch v2 Compatibility (push) Has been skipped
Server CI / Postgres FIPS (shard 0) (push) Has been skipped
Tools CI / Test (mattermost-govet) (push) Failing after 3s
Server CI / Postgres FIPS (shard 1) (push) Has been skipped
Server CI / Postgres FIPS (shard 2) (push) Has been skipped
Tools CI / Test (mmgotool) (push) Failing after 3s
Server CI / Postgres FIPS (shard 3) (push) Has been skipped
Server CI / Run mmctl tests (push) Has been skipped
Server CI / Run mmctl tests (FIPS) (push) Has been skipped
Server CI / Merge Postgres Test Results (push) Has been skipped
Server CI / Merge Postgres FIPS Test Results (push) Has been skipped
Server CI / Check backport migrations (push) Has been skipped
Server CI / Check generated files (push) Has been skipped
Server CI / check-style (push) Has been skipped
Server CI / Vet API (push) Has been skipped
Server CI / Build mattermost server app (push) Has been skipped
Server CI / Server CI Complete (push) Failing after 2s
Server CI / Server CI Artifacts (push) Has been skipped
Server CI / Sentry Upload (push) Has been skipped
Server CI / Server CI Report (push) Failing after 5m1s
Server CI Nightly Race / Race Detector (push) Has been skipped
CodeQL / Analyze (go) (push) Has been cancelled
CodeQL / Analyze (javascript) (push) Has been cancelled
Webapp CI Cache Warm / Warm Webapp node_modules Cache (push) Has been cancelled
E2E CI Cache Warm / Warm E2E npm Registry Cache (push) Has been cancelled
API / build (push) Has been cancelled
Web App CI / check-types (push) Has been cancelled
Web App CI / check-lint (push) Has been cancelled
Web App CI / check-i18n (push) Has been cancelled
Web App CI / check-external-links (push) Has been cancelled
Web App CI / test (platform) (push) Has been cancelled
Web App CI / test (mattermost-redux) (push) Has been cancelled
Web App CI / test (channels shard 1/4) (push) Has been cancelled
Web App CI / test (channels shard 2/4) (push) Has been cancelled
Web App CI / test (channels shard 3/4) (push) Has been cancelled
Web App CI / test (channels shard 4/4) (push) Has been cancelled
Web App CI / upload-coverage (push) Has been cancelled
Web App CI / build (push) Has been cancelled
YAML Lint / yamllint (push) Has been cancelled
Push mirrored docker images / cd/Push mirrored docker images (push) Has been cancelled
docs-cd / Build and deploy docs (push) Has been cancelled
Docs CI / build (push) Has been cancelled
E2E Cache Warm: Cypress deps / Warm Cypress deps cache (push) Has been cancelled
Scorecards supply-chain security / Scorecard analysis (push) Has been cancelled
Server CI Weekly / Postgres FIPS (push) Has been skipped
Server CI Weekly / Run mmctl tests (FIPS) (push) Has been skipped
Server CI Weekly / Postgres with binary parameters (push) Has been skipped
Server CI Weekly / Build Environment (push) Failing after 1s
Server CI Cache Warm / Warm Go Module and Build Cache (push) Failing after 2s
Server CI Nightly Race / Build Environment (push) Failing after 1s
snapshot of https://github.com/mattermost/mattermost.git (master, 2026-09-16; blobs > 131072B omitted)
2026-09-16 00:29:55 +05:00

323 lines
10 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package api4
import (
"encoding/json"
"errors"
"io"
"net/http"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
)
func (api *API) InitAction() {
api.BaseRoutes.Post.Handle("/actions/{action_id:[A-Za-z0-9_-]+}", api.APISessionRequired(doPostAction)).Methods(http.MethodPost)
api.BaseRoutes.APIRoot.Handle("/actions/dialogs/open", api.APIHandler(openDialog)).Methods(http.MethodPost)
api.BaseRoutes.APIRoot.Handle("/actions/dialogs/submit", api.APISessionRequired(submitDialog)).Methods(http.MethodPost)
api.BaseRoutes.APIRoot.Handle("/actions/dialogs/lookup", api.APISessionRequired(lookupDialog)).Methods(http.MethodPost)
api.BaseRoutes.APIRoot.Handle("/actions/dialogs/execute", api.APISessionRequired(executeDialogAction)).Methods(http.MethodPost)
}
func doPostAction(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequirePostId()
if c.Err != nil {
return
}
var actionRequest model.DoPostActionRequest
dec := json.NewDecoder(r.Body)
err := dec.Decode(&actionRequest)
if err != nil && !errors.Is(err, io.EOF) {
// Empty body is allowed for backward-compatibility with older clients.
// Any other decode failure means the request cannot be trusted — in
// particular, a wrong-type query would otherwise fall through as nil
// and silently execute the action without the caller's params.
c.SetInvalidParamWithErr("action_request", err)
return
}
if err == nil {
// Reject trailing JSON values after the first object (e.g.
// `{"query":{"k":"v"}}{"cookie":"x"}`). json.Decoder.Decode
// stops at the first complete value and would otherwise silently
// ignore the rest, leaving the caller's intent ambiguous.
var trailing any
if extraErr := dec.Decode(&trailing); !errors.Is(extraErr, io.EOF) {
c.SetInvalidParamWithErr("action_request", extraErr)
return
}
}
var legacyCookie *model.PostActionCookie
var mmBlocksCookie *model.MmBlocksActionCookie
if actionRequest.Cookie != "" {
cookieStr, decErr := model.DecryptPostActionCookie(actionRequest.Cookie, c.App.PostActionCookieSecret())
if decErr != nil {
c.Err = model.NewAppError("DoPostAction", "api.post.do_action.action_integration.app_error", nil, "", http.StatusBadRequest).Wrap(decErr)
return
}
var parseErr error
legacyCookie, mmBlocksCookie, parseErr = model.ParseDecryptedActionCookiePayload(cookieStr)
if parseErr != nil {
c.Err = model.NewAppError("DoPostAction", "api.post.do_action.action_integration.app_error", nil, "", http.StatusBadRequest).Wrap(parseErr)
return
}
if !c.App.Config().FeatureFlags.MmBlocksEnabled && mmBlocksCookie != nil {
c.Err = model.NewAppError("DoPostAction", "api.post.do_action.action_integration.app_error", nil, "", http.StatusBadRequest).Wrap(errors.New("mm_blocks are not enabled"))
return
}
var cookiePostId string
var channelID string
if legacyCookie != nil {
cookiePostId = legacyCookie.PostId
channelID = legacyCookie.ChannelId
} else if mmBlocksCookie != nil {
cookiePostId = mmBlocksCookie.PostId
channelID = mmBlocksCookie.ChannelId
}
if cookiePostId != c.Params.PostId {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
channel, appErr := c.App.GetChannel(c.AppContext, channelID)
if appErr != nil {
c.Err = appErr
return
}
if ok, _ := c.App.SessionHasPermissionToReadChannel(c.AppContext, *c.AppContext.Session(), channel); !ok {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
} else {
if ok, _ := c.App.SessionHasPermissionToReadPost(c.AppContext, *c.AppContext.Session(), c.Params.PostId); !ok {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
}
var appErr *model.AppError
resp := &model.PostActionAPIResponse{Status: "OK"}
resp.TriggerId, resp.GotoLocation, appErr = c.App.DoPostActionWithCookie(c.AppContext, c.Params.PostId, c.Params.ActionId, c.AppContext.Session().UserId,
actionRequest.SelectedOption, legacyCookie, mmBlocksCookie, actionRequest.Query, actionRequest.IntegrationFormat)
if appErr != nil {
c.Err = appErr
return
}
err = json.NewEncoder(w).Encode(resp)
if err != nil {
c.Logger.Warn("Error writing response", mlog.Err(err))
}
}
func openDialog(c *Context, w http.ResponseWriter, r *http.Request) {
var dialog model.OpenDialogRequest
err := json.NewDecoder(r.Body).Decode(&dialog)
if err != nil {
c.SetInvalidParamWithErr("dialog", err)
return
}
if dialog.URL == "" {
c.SetInvalidParam("url")
return
}
if appErr := c.App.OpenInteractiveDialog(c.AppContext, dialog); appErr != nil {
c.Err = appErr
return
}
ReturnStatusOK(w)
}
func submitDialog(c *Context, w http.ResponseWriter, r *http.Request) {
var submit model.SubmitDialogRequest
jsonErr := json.NewDecoder(r.Body).Decode(&submit)
if jsonErr != nil {
c.SetInvalidParamWithErr("dialog", jsonErr)
return
}
if submit.URL == "" {
c.SetInvalidParam("url")
return
}
submit.UserId = c.AppContext.Session().UserId
channel, err := c.App.GetChannel(c.AppContext, submit.ChannelId)
if err != nil {
c.Err = err
return
}
if ok, _ := c.App.SessionHasPermissionToReadChannel(c.AppContext, *c.AppContext.Session(), channel); !ok {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
// Derive the team from the server-loaded channel, not the client-supplied
// TeamId — otherwise a client could omit TeamId on a team channel and skip
// the PermissionViewTeam check. channel.TeamId is empty for DM/GM channels.
if channel.TeamId != "" {
if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionViewTeam) {
c.SetPermissionError(model.PermissionViewTeam)
return
}
}
// The client-supplied TeamId is not trusted for the permission check above, so
// don't forward it to the integration either — use the channel's authoritative
// team (empty for DM/GM).
submit.TeamId = channel.TeamId
resp, err := c.App.SubmitInteractiveDialog(c.AppContext, submit)
if err != nil {
c.Err = err
return
}
b, _ := json.Marshal(resp)
if _, err := w.Write(b); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func executeDialogAction(c *Context, w http.ResponseWriter, r *http.Request) {
var request model.ExecuteDialogActionRequest
jsonErr := json.NewDecoder(r.Body).Decode(&request)
if jsonErr != nil {
c.SetInvalidParamWithErr("dialog_action", jsonErr)
return
}
if request.URL == "" {
c.SetInvalidParam("url")
return
}
if !model.IsValidLookupURL(request.URL) {
c.SetInvalidParam("url")
return
}
channel, err := c.App.GetChannel(c.AppContext, request.ChannelId)
if err != nil {
c.Err = err
return
}
if ok, _ := c.App.SessionHasPermissionToReadChannel(c.AppContext, *c.AppContext.Session(), channel); !ok {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
// Derive the team from the server-loaded channel, not the client-supplied
// TeamId — otherwise a client could omit TeamId on a team channel and skip
// the PermissionViewTeam check. channel.TeamId is empty for DM/GM channels.
if channel.TeamId != "" {
if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionViewTeam) {
c.SetPermissionError(model.PermissionViewTeam)
return
}
}
// The client-supplied TeamId is not trusted for the permission check above,
// so don't trust it for the downstream team lookup / integration payload either.
// Use the channel's authoritative team (empty for DM/GM, which skips the lookup).
request.TeamId = channel.TeamId
triggerId, err := c.App.ExecuteDialogAction(c.AppContext, c.AppContext.Session().UserId, request)
if err != nil {
c.Err = err
return
}
resp := &model.ExecuteDialogActionResponse{TriggerId: triggerId}
if encErr := json.NewEncoder(w).Encode(resp); encErr != nil {
c.Logger.Warn("Error writing response", mlog.Err(encErr))
}
}
// lookupDialog handles API requests for dynamic dialog element lookups.
// It validates the request URL for security, checks user permissions, and
// delegates to the app layer for the actual lookup operation.
func lookupDialog(c *Context, w http.ResponseWriter, r *http.Request) {
var lookup model.SubmitDialogRequest
jsonErr := json.NewDecoder(r.Body).Decode(&lookup)
if jsonErr != nil {
c.SetInvalidParamWithErr("dialog", jsonErr)
return
}
if lookup.URL == "" {
c.SetInvalidParam("url")
return
}
// Validate URL for security
if !model.IsValidLookupURL(lookup.URL) {
c.SetInvalidParam("url")
return
}
lookup.UserId = c.AppContext.Session().UserId
channel, err := c.App.GetChannel(c.AppContext, lookup.ChannelId)
if err != nil {
c.Err = err
return
}
if ok, _ := c.App.SessionHasPermissionToReadChannel(c.AppContext, *c.AppContext.Session(), channel); !ok {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
// Derive the team from the server-loaded channel, not the client-supplied
// TeamId — otherwise a client could omit TeamId on a team channel and skip
// the PermissionViewTeam check. channel.TeamId is empty for DM/GM channels.
if channel.TeamId != "" {
if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionViewTeam) {
c.SetPermissionError(model.PermissionViewTeam)
return
}
}
// The client-supplied TeamId is not trusted for the permission check above, so
// don't forward it to the integration either — use the channel's authoritative
// team (empty for DM/GM). Set before logging so the trace reflects the real team.
lookup.TeamId = channel.TeamId
c.Logger.Debug("Performing lookup dialog request",
mlog.String("url", lookup.URL),
mlog.String("user_id", lookup.UserId),
mlog.String("channel_id", lookup.ChannelId),
mlog.String("team_id", lookup.TeamId),
mlog.Any("selected_field", lookup.Submission["selected_field"]),
mlog.Any("query", lookup.Submission["query"]),
)
resp, err := c.App.LookupInteractiveDialog(c.AppContext, lookup)
if err != nil {
c.Logger.Error("Error performing lookup dialog", mlog.Err(err))
c.Err = err
return
}
b, _ := json.Marshal(resp)
if _, err := w.Write(b); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}