Refactor context out of API packages (#8755)

* Refactor context out of API packages

* Update function names per feedback

* Move webhook handlers to web and fix web tests

* Move more webhook tests out of api package

* Fix static handler
Этот коммит содержится в:
Joram Wilander
2018-05-14 10:24:58 -04:00
коммит произвёл GitHub
родитель 7e7c551987
Коммит 47250c6629
16 изменённых файлов: 708 добавлений и 611 удалений

Просмотреть файл

@@ -4,8 +4,6 @@
package api
import (
"fmt"
"net/http"
"testing"
"github.com/mattermost/mattermost-server/model"
@@ -968,155 +966,3 @@ func TestRegenOutgoingHookToken(t *testing.T) {
t.Fatal("should have errored - webhooks turned off")
}
}
func TestIncomingWebhooks(t *testing.T) {
th := Setup().InitBasic().InitSystemAdmin()
defer th.TearDown()
Client := th.SystemAdminClient
team := th.SystemAdminTeam
channel1 := th.CreateChannel(Client, team)
user2 := th.CreateUser(Client)
th.LinkUserToTeam(user2, team)
th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true })
hook := &model.IncomingWebhook{ChannelId: channel1.Id}
hook = Client.Must(Client.CreateIncomingWebhook(hook)).Data.(*model.IncomingWebhook)
url := "/hooks/" + hook.Id
text := `this is a \"test\"
that contains a newline and a tab`
if _, err := Client.DoPost(url, "{\"text\":\"this is a test\"}", "application/json"); err != nil {
t.Fatal(err)
}
if _, err := Client.DoPost(url, "{\"text\":\""+text+"\"}", "application/json"); err != nil {
t.Fatal(err)
}
if _, err := Client.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", channel1.Name), "application/json"); err != nil {
t.Fatal(err)
}
if _, err := Client.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"#%s\"}", channel1.Name), "application/json"); err != nil {
t.Fatal(err)
}
if _, err := Client.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"@%s\"}", user2.Username), "application/json"); err != nil {
t.Fatal(err)
}
if _, err := Client.DoPost(url, "payload={\"text\":\"this is a test\"}", "application/x-www-form-urlencoded"); err != nil {
t.Fatal(err)
}
if _, err := Client.DoPost(url, "payload={\"text\":\""+text+"\"}", "application/x-www-form-urlencoded"); err != nil {
t.Fatal(err)
}
if _, err := th.BasicClient.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DEFAULT_CHANNEL), "application/json"); err != nil {
t.Fatal("should not have failed -- ExperimentalTownSquareIsReadOnly is false and it's not a read only channel")
}
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true })
th.App.SetLicense(model.NewTestLicense())
if _, err := th.BasicClient.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DEFAULT_CHANNEL), "application/json"); err == nil {
t.Fatal("should have failed -- ExperimentalTownSquareIsReadOnly is true and it's a read only channel")
}
attachmentPayload := `{
"text": "this is a test",
"attachments": [
{
"fallback": "Required plain-text summary of the attachment.",
"color": "#36a64f",
"pretext": "Optional text that appears above the attachment block",
"author_name": "Bobby Tables",
"author_link": "http://flickr.com/bobby/",
"author_icon": "http://flickr.com/icons/bobby.jpg",
"title": "Slack API Documentation",
"title_link": "https://api.slack.com/",
"text": "Optional text that appears within the attachment",
"fields": [
{
"title": "Priority",
"value": "High",
"short": false
}
],
"image_url": "http://my-website.com/path/to/image.jpg",
"thumb_url": "http://example.com/path/to/thumb.png"
}
]
}`
if _, err := Client.DoPost(url, attachmentPayload, "application/json"); err != nil {
t.Fatal(err)
}
if _, err := Client.DoPost(url, "{\"text\":\"\"}", "application/json"); err == nil || err.StatusCode != http.StatusBadRequest {
t.Fatal("should have failed - no text")
}
tooLongText := ""
for i := 0; i < 8200; i++ {
tooLongText += "a"
}
if _, err := Client.DoPost(url, "{\"text\":\""+tooLongText+"\"}", "application/json"); err != nil {
t.Fatal(err)
}
attachmentPayload = `{
"text": "this is a test",
"attachments": [
{
"fallback": "Required plain-text summary of the attachment.",
"color": "#36a64f",
"pretext": "Optional text that appears above the attachment block",
"author_name": "Bobby Tables",
"author_link": "http://flickr.com/bobby/",
"author_icon": "http://flickr.com/icons/bobby.jpg",
"title": "Slack API Documentation",
"title_link": "https://api.slack.com/",
"text": "` + tooLongText + `",
"fields": [
{
"title": "Priority",
"value": "High",
"short": false
}
],
"image_url": "http://my-website.com/path/to/image.jpg",
"thumb_url": "http://example.com/path/to/thumb.png"
}
]
}`
if _, err := Client.DoPost(url, attachmentPayload, "application/json"); err != nil {
t.Fatal(err)
}
th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false })
if _, err := Client.DoPost(url, "{\"text\":\"this is a test\"}", "application/json"); err == nil {
t.Fatal("should have failed - webhooks turned off")
}
}

Просмотреть файл

@@ -4,14 +4,12 @@
package api4
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
"github.com/mattermost/mattermost-server/web"
_ "github.com/nicksnyder/go-i18n/i18n"
)
@@ -231,7 +229,7 @@ func Init(a *app.App, root *mux.Router, full bool) *API {
api.InitRole()
api.InitImage()
root.Handle("/api/v4/{anything:.*}", http.HandlerFunc(Handle404))
root.Handle("/api/v4/{anything:.*}", http.HandlerFunc(api.Handle404))
// REMOVE CONDITION WHEN APIv3 REMOVED
if full {
@@ -241,14 +239,8 @@ func Init(a *app.App, root *mux.Router, full bool) *API {
return api
}
func Handle404(w http.ResponseWriter, r *http.Request) {
err := model.NewAppError("Handle404", "api.context.404.app_error", nil, "", http.StatusNotFound)
mlog.Debug(fmt.Sprintf("%v: code=404 ip=%v", r.URL.Path, utils.GetIpAddress(r)))
w.WriteHeader(err.StatusCode)
err.DetailedError = "There doesn't appear to be an api call for the url='" + r.URL.Path + "'."
w.Write([]byte(err.ToJson()))
func (api *API) Handle404(w http.ResponseWriter, r *http.Request) {
web.Handle404(api.App, w, r)
}
func ReturnStatusOK(w http.ResponseWriter) {

Просмотреть файл

@@ -9,6 +9,7 @@ import (
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/web"
)
const (
@@ -197,7 +198,7 @@ func searchEmojis(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
emojis, err := c.App.SearchEmoji(emojiSearch.Term, emojiSearch.PrefixOnly, PER_PAGE_MAXIMUM)
emojis, err := c.App.SearchEmoji(emojiSearch.Term, emojiSearch.PrefixOnly, web.PER_PAGE_MAXIMUM)
if err != nil {
c.Err = err
return

67
api4/handlers.go Обычный файл
Просмотреть файл

@@ -0,0 +1,67 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package api4
import (
"net/http"
"github.com/mattermost/mattermost-server/web"
)
type Context = web.Context
func (api *API) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &web.Handler{
App: api.App,
HandleFunc: h,
RequireSession: false,
TrustRequester: false,
RequireMfa: false,
IsStatic: false,
}
}
func (api *API) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &web.Handler{
App: api.App,
HandleFunc: h,
RequireSession: true,
TrustRequester: false,
RequireMfa: true,
IsStatic: false,
}
}
func (api *API) ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &web.Handler{
App: api.App,
HandleFunc: h,
RequireSession: true,
TrustRequester: false,
RequireMfa: false,
IsStatic: false,
}
}
func (api *API) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &web.Handler{
App: api.App,
HandleFunc: h,
RequireSession: false,
TrustRequester: true,
RequireMfa: false,
IsStatic: false,
}
}
func (api *API) ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &web.Handler{
App: api.App,
HandleFunc: h,
RequireSession: true,
TrustRequester: true,
RequireMfa: true,
IsStatic: false,
}
}

Просмотреть файл

@@ -4,14 +4,8 @@
package api4
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
)
@@ -28,12 +22,6 @@ func (api *API) InitWebhook() {
api.BaseRoutes.OutgoingHook.Handle("", api.ApiSessionRequired(updateOutgoingHook)).Methods("PUT")
api.BaseRoutes.OutgoingHook.Handle("", api.ApiSessionRequired(deleteOutgoingHook)).Methods("DELETE")
api.BaseRoutes.OutgoingHook.Handle("/regen_token", api.ApiSessionRequired(regenOutgoingHookToken)).Methods("POST")
api.BaseRoutes.Root.Handle("/hooks/commands/{id:[A-Za-z0-9]+}", api.ApiHandler(commandWebhook)).Methods("POST")
api.BaseRoutes.Root.Handle("/hooks/{id:[A-Za-z0-9]+}", api.ApiHandler(incomingWebhook)).Methods("POST")
// Old endpoint for backwards compatibility
api.BaseRoutes.Root.Handle("/api/v3/teams/{team_id:[A-Za-z0-9]+}/hooks/{id:[A-Za-z0-9]+}", api.ApiHandler(incomingWebhook)).Methods("POST")
}
func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -454,82 +442,3 @@ func deleteOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) {
c.LogAudit("success")
ReturnStatusOK(w)
}
func incomingWebhook(c *Context, w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
r.ParseForm()
var err *model.AppError
incomingWebhookPayload := &model.IncomingWebhookRequest{}
contentType := r.Header.Get("Content-Type")
if strings.Split(contentType, "; ")[0] == "application/x-www-form-urlencoded" {
payload := strings.NewReader(r.FormValue("payload"))
incomingWebhookPayload, err = decodePayload(payload)
if err != nil {
c.Err = err
return
}
} else if strings.HasPrefix(contentType, "multipart/form-data") {
r.ParseMultipartForm(0)
decoder := schema.NewDecoder()
err := decoder.Decode(incomingWebhookPayload, r.PostForm)
if err != nil {
c.Err = model.NewAppError("incomingWebhook", "api.webhook.incoming.error", nil, err.Error(), http.StatusBadRequest)
return
}
} else {
incomingWebhookPayload, err = decodePayload(r.Body)
if err != nil {
c.Err = err
return
}
}
if c.App.Config().LogSettings.EnableWebhookDebugging {
mlog.Debug(fmt.Sprint("Incoming webhook received. Content=", incomingWebhookPayload.ToJson()))
}
err = c.App.HandleIncomingWebhook(id, incomingWebhookPayload)
if err != nil {
c.Err = err
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("ok"))
}
func commandWebhook(c *Context, w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
response, err := model.CommandResponseFromHTTPBody(r.Header.Get("Content-Type"), r.Body)
if err != nil {
c.Err = model.NewAppError("commandWebhook", "web.command_webhook.parse.app_error", nil, err.Error(), http.StatusBadRequest)
return
}
appErr := c.App.HandleCommandWebhook(id, response)
if appErr != nil {
c.Err = appErr
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("ok"))
}
func decodePayload(payload io.Reader) (*model.IncomingWebhookRequest, *model.AppError) {
incomingWebhookPayload, decodeError := model.IncomingWebhookRequestFromJson(payload)
if decodeError != nil {
return nil, decodeError
}
return incomingWebhookPayload, nil
}

Просмотреть файл

@@ -4,8 +4,6 @@
package api4
import (
"bytes"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
@@ -892,46 +890,3 @@ func TestDeleteOutgoingHook(t *testing.T) {
CheckForbiddenStatus(t, resp)
})
}
func TestCommandWebhooks(t *testing.T) {
th := Setup().InitBasic().InitSystemAdmin()
defer th.TearDown()
Client := th.SystemAdminClient
cmd := &model.Command{
CreatorId: th.BasicUser.Id,
TeamId: th.BasicTeam.Id,
URL: "http://nowhere.com",
Method: model.COMMAND_METHOD_POST,
Trigger: "delayed"}
cmd, _ = Client.CreateCommand(cmd)
args := &model.CommandArgs{
TeamId: th.BasicTeam.Id,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
}
hook, err := th.App.CreateCommandWebhook(cmd.Id, args)
if err != nil {
t.Fatal(err)
}
if resp, _ := http.Post(Client.Url+"/hooks/commands/123123123123", "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)); resp.StatusCode != http.StatusNotFound {
t.Fatal("expected not-found for non-existent hook")
}
if resp, err := http.Post(Client.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"invalid`)); err != nil || resp.StatusCode != http.StatusBadRequest {
t.Fatal(err)
}
for i := 0; i < 5; i++ {
if resp, err := http.Post(Client.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)); err != nil || resp.StatusCode != http.StatusOK {
t.Fatal(err)
}
}
if resp, _ := http.Post(Client.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)); resp.StatusCode != http.StatusBadRequest {
t.Fatal("expected error for sixth usage")
}
}

Просмотреть файл

@@ -107,7 +107,7 @@ func runServer(configFileLocation string, disableConfigWatch bool, interruptChan
api4.Init(a, a.Srv.Router, false)
api3 := api.Init(a, a.Srv.Router)
wsapi.Init(a, a.Srv.WebSocketRouter)
web.Init(api3)
web.NewWeb(a, a.Srv.Router)
license := a.License()

Просмотреть файл

@@ -1,14 +1,13 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package api4
package web
import (
"fmt"
"net/http"
"regexp"
"strings"
"time"
goi18n "github.com/nicksnyder/go-i18n/i18n"
@@ -21,7 +20,7 @@ import (
type Context struct {
App *app.App
Session model.Session
Params *ApiParams
Params *Params
Err *model.AppError
T goi18n.TranslateFunc
RequestId string
@@ -30,169 +29,6 @@ type Context struct {
siteURLHeader string
}
func (api *API) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &handler{
app: api.App,
handleFunc: h,
requireSession: false,
trustRequester: false,
requireMfa: false,
}
}
func (api *API) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &handler{
app: api.App,
handleFunc: h,
requireSession: true,
trustRequester: false,
requireMfa: true,
}
}
func (api *API) ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &handler{
app: api.App,
handleFunc: h,
requireSession: true,
trustRequester: false,
requireMfa: false,
}
}
func (api *API) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &handler{
app: api.App,
handleFunc: h,
requireSession: false,
trustRequester: true,
requireMfa: false,
}
}
func (api *API) ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &handler{
app: api.App,
handleFunc: h,
requireSession: true,
trustRequester: true,
requireMfa: true,
}
}
type handler struct {
app *app.App
handleFunc func(*Context, http.ResponseWriter, *http.Request)
requireSession bool
trustRequester bool
requireMfa bool
}
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
now := time.Now()
mlog.Debug(fmt.Sprintf("%v - %v", r.Method, r.URL.Path))
c := &Context{}
c.App = h.app
c.T, _ = utils.GetTranslationsAndLocale(w, r)
c.RequestId = model.NewId()
c.IpAddress = utils.GetIpAddress(r)
c.Params = ApiParamsFromRequest(r)
token, tokenLocation := app.ParseAuthTokenFromRequest(r)
// CSRF Check
if tokenLocation == app.TokenLocationCookie && h.requireSession && !h.trustRequester {
if r.Header.Get(model.HEADER_REQUESTED_WITH) != model.HEADER_REQUESTED_WITH_XML {
c.Err = model.NewAppError("ServeHTTP", "api.context.session_expired.app_error", nil, "token="+token+" Appears to be a CSRF attempt", http.StatusUnauthorized)
token = ""
}
}
c.SetSiteURLHeader(app.GetProtocol(r) + "://" + r.Host)
w.Header().Set(model.HEADER_REQUEST_ID, c.RequestId)
w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.License() != nil))
w.Header().Set("Content-Type", "application/json")
if r.Method == "GET" {
w.Header().Set("Expires", "0")
}
if len(token) != 0 {
session, err := c.App.GetSession(token)
if err != nil {
mlog.Info(fmt.Sprintf("Invalid session err=%v", err.Error()))
if err.StatusCode == http.StatusInternalServerError {
c.Err = err
} else if h.requireSession {
c.RemoveSessionCookie(w, r)
c.Err = model.NewAppError("ServeHTTP", "api.context.session_expired.app_error", nil, "token="+token, http.StatusUnauthorized)
}
} else if !session.IsOAuth && tokenLocation == app.TokenLocationQueryString {
c.Err = model.NewAppError("ServeHTTP", "api.context.token_provided.app_error", nil, "token="+token, http.StatusUnauthorized)
} else {
c.Session = *session
}
// Rate limit by UserID
if c.App.Srv.RateLimiter != nil && c.App.Srv.RateLimiter.UserIdRateLimit(c.Session.UserId, w) {
return
}
}
c.Path = r.URL.Path
if c.Err == nil && h.requireSession {
c.SessionRequired()
}
if c.Err == nil && h.requireMfa {
c.MfaRequired()
}
if c.Err == nil {
h.handleFunc(c, w, r)
}
// Handle errors that have occurred
if c.Err != nil {
c.Err.Translate(c.T)
c.Err.RequestId = c.RequestId
if c.Err.Id == "api.context.session_expired.app_error" {
c.LogInfo(c.Err)
} else {
c.LogError(c.Err)
}
c.Err.Where = r.URL.Path
// Block out detailed error when not in developer mode
if !*c.App.Config().ServiceSettings.EnableDeveloper {
c.Err.DetailedError = ""
}
w.WriteHeader(c.Err.StatusCode)
w.Write([]byte(c.Err.ToJson()))
if c.App.Metrics != nil {
c.App.Metrics.IncrementHttpError()
}
}
if c.App.Metrics != nil {
c.App.Metrics.IncrementHttpRequest()
if r.URL.Path != model.API_URL_SUFFIX+"/websocket" {
elapsed := float64(time.Since(now)) / float64(time.Second)
c.App.Metrics.ObserveHttpRequestDuration(elapsed)
}
}
}
func (c *Context) LogAudit(extraInfo string) {
audit := &model.Audit{UserId: c.Session.UserId, IpAddress: c.IpAddress, Action: c.Path, ExtraInfo: extraInfo, SessionId: c.Session.Id}
if r := <-c.App.Srv.Store.Audit().Save(audit); r.Err != nil {

Просмотреть файл

@@ -1,4 +1,4 @@
package api4
package web
import (
"net/http"
@@ -8,7 +8,7 @@ import (
func TestRequireHookId(t *testing.T) {
c := &Context{}
t.Run("WhenHookIdIsValid", func(t *testing.T) {
c.Params = &ApiParams{HookId: "abcdefghijklmnopqrstuvwxyz"}
c.Params = &Params{HookId: "abcdefghijklmnopqrstuvwxyz"}
c.RequireHookId()
if c.Err != nil {
@@ -17,7 +17,7 @@ func TestRequireHookId(t *testing.T) {
})
t.Run("WhenHookIdIsInvalid", func(t *testing.T) {
c.Params = &ApiParams{HookId: "abc"}
c.Params = &Params{HookId: "abc"}
c.RequireHookId()
if c.Err == nil {

158
web/handlers.go Обычный файл
Просмотреть файл

@@ -0,0 +1,158 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package web
import (
"fmt"
"net/http"
"time"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
)
func (w *Web) NewHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &Handler{
App: w.App,
HandleFunc: h,
RequireSession: false,
TrustRequester: false,
RequireMfa: false,
IsStatic: false,
}
}
func (w *Web) NewStaticHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
return &Handler{
App: w.App,
HandleFunc: h,
RequireSession: false,
TrustRequester: false,
RequireMfa: false,
IsStatic: true,
}
}
type Handler struct {
App *app.App
HandleFunc func(*Context, http.ResponseWriter, *http.Request)
RequireSession bool
TrustRequester bool
RequireMfa bool
IsStatic bool
}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
now := time.Now()
mlog.Debug(fmt.Sprintf("%v - %v", r.Method, r.URL.Path))
c := &Context{}
c.App = h.App
c.T, _ = utils.GetTranslationsAndLocale(w, r)
c.RequestId = model.NewId()
c.IpAddress = utils.GetIpAddress(r)
c.Params = ParamsFromRequest(r)
token, tokenLocation := app.ParseAuthTokenFromRequest(r)
// CSRF Check
if tokenLocation == app.TokenLocationCookie && h.RequireSession && !h.TrustRequester {
if r.Header.Get(model.HEADER_REQUESTED_WITH) != model.HEADER_REQUESTED_WITH_XML {
c.Err = model.NewAppError("ServeHTTP", "api.context.session_expired.app_error", nil, "token="+token+" Appears to be a CSRF attempt", http.StatusUnauthorized)
token = ""
}
}
c.SetSiteURLHeader(app.GetProtocol(r) + "://" + r.Host)
w.Header().Set(model.HEADER_REQUEST_ID, c.RequestId)
w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.License() != nil))
if h.IsStatic {
// Instruct the browser not to display us in an iframe unless is the same origin for anti-clickjacking
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'")
} else {
// All api response bodies will be JSON formatted by default
w.Header().Set("Content-Type", "application/json")
if r.Method == "GET" {
w.Header().Set("Expires", "0")
}
}
if len(token) != 0 {
session, err := c.App.GetSession(token)
if err != nil {
mlog.Info(fmt.Sprintf("Invalid session err=%v", err.Error()))
if err.StatusCode == http.StatusInternalServerError {
c.Err = err
} else if h.RequireSession {
c.RemoveSessionCookie(w, r)
c.Err = model.NewAppError("ServeHTTP", "api.context.session_expired.app_error", nil, "token="+token, http.StatusUnauthorized)
}
} else if !session.IsOAuth && tokenLocation == app.TokenLocationQueryString {
c.Err = model.NewAppError("ServeHTTP", "api.context.token_provided.app_error", nil, "token="+token, http.StatusUnauthorized)
} else {
c.Session = *session
}
// Rate limit by UserID
if c.App.Srv.RateLimiter != nil && c.App.Srv.RateLimiter.UserIdRateLimit(c.Session.UserId, w) {
return
}
}
c.Path = r.URL.Path
if c.Err == nil && h.RequireSession {
c.SessionRequired()
}
if c.Err == nil && h.RequireMfa {
c.MfaRequired()
}
if c.Err == nil {
h.HandleFunc(c, w, r)
}
// Handle errors that have occurred
if c.Err != nil {
c.Err.Translate(c.T)
c.Err.RequestId = c.RequestId
if c.Err.Id == "api.context.session_expired.app_error" {
c.LogInfo(c.Err)
} else {
c.LogError(c.Err)
}
c.Err.Where = r.URL.Path
// Block out detailed error when not in developer mode
if !*c.App.Config().ServiceSettings.EnableDeveloper {
c.Err.DetailedError = ""
}
w.WriteHeader(c.Err.StatusCode)
w.Write([]byte(c.Err.ToJson()))
if c.App.Metrics != nil {
c.App.Metrics.IncrementHttpError()
}
}
if c.App.Metrics != nil {
c.App.Metrics.IncrementHttpRequest()
if r.URL.Path != model.API_URL_SUFFIX+"/websocket" {
elapsed := float64(time.Since(now)) / float64(time.Second)
c.App.Metrics.ObserveHttpRequestDuration(elapsed)
}
}
}

Просмотреть файл

@@ -1,7 +1,7 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package api4
package web
import (
"net/http"
@@ -19,7 +19,7 @@ const (
LOGS_PER_PAGE_MAXIMUM = 10000
)
type ApiParams struct {
type Params struct {
UserId string
TeamId string
InviteId string
@@ -53,8 +53,8 @@ type ApiParams struct {
Permanent bool
}
func ApiParamsFromRequest(r *http.Request) *ApiParams {
params := &ApiParams{}
func ParamsFromRequest(r *http.Request) *Params {
params := &Params{}
props := mux.Vars(r)
query := r.URL.Query()

84
web/static.go Обычный файл
Просмотреть файл

@@ -0,0 +1,84 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package web
import (
"fmt"
"net/http"
"path/filepath"
"strings"
"github.com/NYTimes/gziphandler"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
)
func (w *Web) InitStatic() {
if *w.App.Config().ServiceSettings.WebserverMode != "disabled" {
staticDir, _ := utils.FindDir(model.CLIENT_DIR)
mlog.Debug(fmt.Sprintf("Using client directory at %v", staticDir))
staticHandler := staticHandler(http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir))))
pluginHandler := pluginHandler(w.App.Config, http.StripPrefix("/static/plugins/", http.FileServer(http.Dir(*w.App.Config().PluginSettings.ClientDirectory))))
if *w.App.Config().ServiceSettings.WebserverMode == "gzip" {
staticHandler = gziphandler.GzipHandler(staticHandler)
pluginHandler = gziphandler.GzipHandler(pluginHandler)
}
w.MainRouter.PathPrefix("/static/plugins/").Handler(pluginHandler)
w.MainRouter.PathPrefix("/static/").Handler(staticHandler)
w.MainRouter.Handle("/{anything:.*}", w.NewStaticHandler(root)).Methods("GET")
}
}
func root(c *Context, w http.ResponseWriter, r *http.Request) {
if !CheckClientCompatability(r.UserAgent()) {
w.Header().Set("Cache-Control", "no-store")
page := utils.NewHTMLTemplate(c.App.HTMLTemplates(), "unsupported_browser")
page.Props["Title"] = c.T("web.error.unsupported_browser.title")
page.Props["Message"] = c.T("web.error.unsupported_browser.message")
page.RenderToWriter(w)
return
}
if IsApiCall(r) {
Handle404(c.App, w, r)
return
}
w.Header().Set("Cache-Control", "no-cache, max-age=31556926, public")
staticDir, _ := utils.FindDir(model.CLIENT_DIR)
http.ServeFile(w, r, filepath.Join(staticDir, "root.html"))
}
func staticHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age=31556926, public")
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
handler.ServeHTTP(w, r)
})
}
func pluginHandler(config model.ConfigFunc, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if *config().ServiceSettings.EnableDeveloper {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
} else {
w.Header().Set("Cache-Control", "max-age=31556926, public")
}
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
handler.ServeHTTP(w, r)
})
}

Просмотреть файл

@@ -6,69 +6,38 @@ package web
import (
"fmt"
"net/http"
"path/filepath"
"strings"
"github.com/NYTimes/gziphandler"
"github.com/avct/uasurfer"
"github.com/gorilla/mux"
"github.com/mattermost/mattermost-server/api"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
)
func Init(api3 *api.API) {
type Web struct {
App *app.App
MainRouter *mux.Router
}
func NewWeb(a *app.App, root *mux.Router) *Web {
mlog.Debug("Initializing web routes")
mainrouter := api3.BaseRoutes.Root
if *api3.App.Config().ServiceSettings.WebserverMode != "disabled" {
staticDir, _ := utils.FindDir(model.CLIENT_DIR)
mlog.Debug(fmt.Sprintf("Using client directory at %v", staticDir))
staticHandler := staticHandler(http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir))))
pluginHandler := pluginHandler(api3.App.Config, http.StripPrefix("/static/plugins/", http.FileServer(http.Dir(*api3.App.Config().PluginSettings.ClientDirectory))))
if *api3.App.Config().ServiceSettings.WebserverMode == "gzip" {
staticHandler = gziphandler.GzipHandler(staticHandler)
pluginHandler = gziphandler.GzipHandler(pluginHandler)
}
mainrouter.PathPrefix("/static/plugins/").Handler(pluginHandler)
mainrouter.PathPrefix("/static/").Handler(staticHandler)
mainrouter.Handle("/{anything:.*}", api3.AppHandlerIndependent(root)).Methods("GET")
web := &Web{
App: a,
MainRouter: root,
}
web.InitStatic()
web.InitWebhooks()
return web
}
func staticHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age=31556926, public")
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
handler.ServeHTTP(w, r)
})
}
func pluginHandler(config model.ConfigFunc, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if *config().ServiceSettings.EnableDeveloper {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
} else {
w.Header().Set("Cache-Control", "max-age=31556926, public")
}
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
handler.ServeHTTP(w, r)
})
}
// Due to the complexities of UA detection and the ramifications of a misdetection only older Safari and IE browsers throw incompatibility errors.
// Due to the complexities of UA detection and the ramifications of a misdetection
// only older Safari and IE browsers throw incompatibility errors.
// Map should be of minimum required browser version.
var browserMinimumSupported = map[string]int{
"BrowserIE": 11,
@@ -85,24 +54,20 @@ func CheckClientCompatability(agentString string) bool {
return true
}
func root(c *api.Context, w http.ResponseWriter, r *http.Request) {
func Handle404(a *app.App, w http.ResponseWriter, r *http.Request) {
err := model.NewAppError("Handle404", "api.context.404.app_error", nil, "", http.StatusNotFound)
if !CheckClientCompatability(r.UserAgent()) {
w.Header().Set("Cache-Control", "no-store")
page := utils.NewHTMLTemplate(c.App.HTMLTemplates(), "unsupported_browser")
page.Props["Title"] = c.T("web.error.unsupported_browser.title")
page.Props["Message"] = c.T("web.error.unsupported_browser.message")
page.RenderToWriter(w)
return
mlog.Debug(fmt.Sprintf("%v: code=404 ip=%v", r.URL.Path, utils.GetIpAddress(r)))
if IsApiCall(r) {
w.WriteHeader(err.StatusCode)
err.DetailedError = "There doesn't appear to be an api call for the url='" + r.URL.Path + "'. Typo? are you missing a team_id or user_id as part of the url?"
w.Write([]byte(err.ToJson()))
} else {
utils.RenderWebAppError(w, r, err, a.AsymmetricSigningKey())
}
if api.IsApiCall(r) {
api.Handle404(c.App, w, r)
return
}
w.Header().Set("Cache-Control", "no-cache, max-age=31556926, public")
staticDir, _ := utils.FindDir(model.CLIENT_DIR)
http.ServeFile(w, r, filepath.Join(staticDir, "root.html"))
}
func IsApiCall(r *http.Request) bool {
return strings.Index(r.URL.Path, "/api/") == 0
}

Просмотреть файл

@@ -8,8 +8,6 @@ import (
"os"
"testing"
"github.com/mattermost/mattermost-server/api"
"github.com/mattermost/mattermost-server/api4"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
@@ -38,7 +36,14 @@ func StopTestStore() {
}
}
func Setup() *app.App {
type TestHelper struct {
App *app.App
BasicUser *model.User
BasicChannel *model.Channel
BasicTeam *model.Team
}
func Setup() *TestHelper {
a, err := app.New(app.StoreOverride(testStore), app.DisableConfigWatch)
if err != nil {
panic(err)
@@ -50,9 +55,8 @@ func Setup() *app.App {
panic(serverErr)
}
a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress })
api4.Init(a, a.Srv.Router, false)
api3 := api.Init(a, a.Srv.Router)
Init(api3)
NewWeb(a, a.Srv.Router)
URL = fmt.Sprintf("http://localhost:%v", a.Srv.ListenAddr.Port)
ApiClient = model.NewClient(URL)
@@ -65,11 +69,31 @@ func Setup() *app.App {
*cfg.ServiceSettings.EnableAPIv3 = true
})
return a
th := &TestHelper{
App: a,
}
return th
}
func TearDown(a *app.App) {
a.Shutdown()
func (th *TestHelper) InitBasic() *TestHelper {
user, _ := th.App.CreateUser(&model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_ADMIN_ROLE_ID})
team, _ := th.App.CreateTeam(&model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: user.Email, Type: model.TEAM_OPEN})
th.App.JoinUserToTeam(team, user, "")
channel, _ := th.App.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id, CreatorId: user.Id}, true)
th.BasicUser = user
th.BasicChannel = channel
th.BasicTeam = team
return th
}
func (th *TestHelper) TearDown() {
th.App.Shutdown()
if err := recover(); err != nil {
StopTestStore()
panic(err)
@@ -93,63 +117,6 @@ func TestStatic(t *testing.T) {
}
*/
func TestIncomingWebhook(t *testing.T) {
a := Setup()
defer TearDown(a)
user := &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1"}
user = ApiClient.Must(ApiClient.CreateUser(user, "")).Data.(*model.User)
store.Must(a.Srv.Store.User().VerifyEmail(user.Id))
ApiClient.Login(user.Email, "passwd1")
team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
team = ApiClient.Must(ApiClient.CreateTeam(team)).Data.(*model.Team)
a.JoinUserToTeam(team, user, "")
a.UpdateUserRoles(user.Id, model.SYSTEM_ADMIN_ROLE_ID, false)
ApiClient.SetTeamId(team.Id)
channel1 := &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = ApiClient.Must(ApiClient.CreateChannel(channel1)).Data.(*model.Channel)
if a.Config().ServiceSettings.EnableIncomingWebhooks {
hook1 := &model.IncomingWebhook{ChannelId: channel1.Id}
hook1 = ApiClient.Must(ApiClient.CreateIncomingWebhook(hook1)).Data.(*model.IncomingWebhook)
payload := "payload={\"text\": \"test text\"}"
if _, err := ApiClient.PostToWebhook(hook1.Id, payload); err != nil {
t.Fatal(err)
}
payload = "payload={\"text\": \"\"}"
if _, err := ApiClient.PostToWebhook(hook1.Id, payload); err == nil {
t.Fatal("should have errored - no text to post")
}
payload = "payload={\"text\": \"test text\", \"channel\": \"junk\"}"
if _, err := ApiClient.PostToWebhook(hook1.Id, payload); err == nil {
t.Fatal("should have errored - bad channel")
}
payload = "payload={\"text\": \"test text\"}"
if _, err := ApiClient.PostToWebhook("abc123", payload); err == nil {
t.Fatal("should have errored - bad hook")
}
payloadMultiPart := "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\nwebhook-bot\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\nthis is a test :tada:\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
if _, err := ApiClient.DoPost("/hooks/"+hook1.Id, payloadMultiPart, "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); err != nil {
t.Fatal("should have errored - bad hook")
}
} else {
if _, err := ApiClient.PostToWebhook("123", "123"); err == nil {
t.Fatal("should have failed - webhooks turned off")
}
}
}
func TestMain(m *testing.M) {
// Setup a global logger to catch tests logging outside of app context
// The global logger will be stomped by apps initalizing but that's fine for testing. Ideally this won't happen.

101
web/webhook.go Обычный файл
Просмотреть файл

@@ -0,0 +1,101 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package web
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
)
func (w *Web) InitWebhooks() {
w.MainRouter.Handle("/hooks/commands/{id:[A-Za-z0-9]+}", w.NewHandler(commandWebhook)).Methods("POST")
w.MainRouter.Handle("/hooks/{id:[A-Za-z0-9]+}", w.NewHandler(incomingWebhook)).Methods("POST")
}
func incomingWebhook(c *Context, w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
r.ParseForm()
var err *model.AppError
incomingWebhookPayload := &model.IncomingWebhookRequest{}
contentType := r.Header.Get("Content-Type")
if strings.Split(contentType, "; ")[0] == "application/x-www-form-urlencoded" {
payload := strings.NewReader(r.FormValue("payload"))
incomingWebhookPayload, err = decodePayload(payload)
if err != nil {
c.Err = err
return
}
} else if strings.HasPrefix(contentType, "multipart/form-data") {
r.ParseMultipartForm(0)
decoder := schema.NewDecoder()
err := decoder.Decode(incomingWebhookPayload, r.PostForm)
if err != nil {
c.Err = model.NewAppError("incomingWebhook", "api.webhook.incoming.error", nil, err.Error(), http.StatusBadRequest)
return
}
} else {
incomingWebhookPayload, err = decodePayload(r.Body)
if err != nil {
c.Err = err
return
}
}
if c.App.Config().LogSettings.EnableWebhookDebugging {
mlog.Debug(fmt.Sprint("Incoming webhook received. Content=", incomingWebhookPayload.ToJson()))
}
err = c.App.HandleIncomingWebhook(id, incomingWebhookPayload)
if err != nil {
c.Err = err
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("ok"))
}
func commandWebhook(c *Context, w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
response, err := model.CommandResponseFromHTTPBody(r.Header.Get("Content-Type"), r.Body)
if err != nil {
c.Err = model.NewAppError("commandWebhook", "web.command_webhook.parse.app_error", nil, err.Error(), http.StatusBadRequest)
return
}
appErr := c.App.HandleCommandWebhook(id, response)
if appErr != nil {
c.Err = appErr
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("ok"))
}
func decodePayload(payload io.Reader) (*model.IncomingWebhookRequest, *model.AppError) {
incomingWebhookPayload, decodeError := model.IncomingWebhookRequestFromJson(payload)
if decodeError != nil {
return nil, decodeError
}
return incomingWebhookPayload, nil
}

216
web/webhook_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,216 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package web
import (
"bytes"
"fmt"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/model"
)
func TestIncomingWebhook(t *testing.T) {
th := Setup().InitBasic()
defer th.TearDown()
if !th.App.Config().ServiceSettings.EnableIncomingWebhooks {
_, err := ApiClient.PostToWebhook("123", "123")
assert.NotNil(t, err, "should have errored - webhooks turned off")
return
}
hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id})
require.Nil(t, err)
url := "/hooks/" + hook.Id
tooLongText := ""
for i := 0; i < 8200; i++ {
tooLongText += "a"
}
t.Run("WebhookBasics", func(t *testing.T) {
payload := "payload={\"text\": \"test text\"}"
_, err := ApiClient.DoPost(url, payload, "application/x-www-form-urlencoded")
assert.Nil(t, err)
payload = "payload={\"text\": \"\"}"
_, err = ApiClient.DoPost(url, payload, "application/x-www-form-urlencoded")
assert.NotNil(t, err, "should have errored - no text to post")
payload = "payload={\"text\": \"test text\", \"channel\": \"junk\"}"
_, err = ApiClient.DoPost(url, payload, "application/x-www-form-urlencoded")
assert.NotNil(t, err, "should have errored - bad channel")
payload = "payload={\"text\": \"test text\"}"
_, err = ApiClient.DoPost("/hooks/abc123", payload, "application/x-www-form-urlencoded")
assert.NotNil(t, err, "should have errored - bad hook")
_, err = ApiClient.DoPost(url, "{\"text\":\"this is a test\"}", "application/json")
assert.Nil(t, err)
text := `this is a \"test\"
that contains a newline and a tab`
_, err = ApiClient.DoPost(url, "{\"text\":\""+text+"\"}", "application/json")
assert.Nil(t, err)
_, err = ApiClient.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", th.BasicChannel.Name), "application/json")
assert.Nil(t, err)
_, err = ApiClient.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"#%s\"}", th.BasicChannel.Name), "application/json")
assert.Nil(t, err)
_, err = ApiClient.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"@%s\"}", th.BasicUser.Username), "application/json")
assert.Nil(t, err)
_, err = ApiClient.DoPost(url, "payload={\"text\":\"this is a test\"}", "application/x-www-form-urlencoded")
assert.Nil(t, err)
_, err = ApiClient.DoPost(url, "payload={\"text\":\""+text+"\"}", "application/x-www-form-urlencoded")
assert.Nil(t, err)
_, err = ApiClient.DoPost(url, "{\"text\":\""+tooLongText+"\"}", "application/json")
assert.Nil(t, err)
payloadMultiPart := "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\nwebhook-bot\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\nthis is a test :tada:\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
_, err = ApiClient.DoPost("/hooks/"+hook.Id, payloadMultiPart, "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
assert.Nil(t, err)
})
t.Run("WebhookExperimentReadOnly", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = false })
_, err := ApiClient.DoPost(url, fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DEFAULT_CHANNEL), "application/json")
assert.Nil(t, err, "Not read only")
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true })
th.App.SetLicense(model.NewTestLicense())
})
t.Run("WebhookAttachments", func(t *testing.T) {
attachmentPayload := `{
"text": "this is a test",
"attachments": [
{
"fallback": "Required plain-text summary of the attachment.",
"color": "#36a64f",
"pretext": "Optional text that appears above the attachment block",
"author_name": "Bobby Tables",
"author_link": "http://flickr.com/bobby/",
"author_icon": "http://flickr.com/icons/bobby.jpg",
"title": "Slack API Documentation",
"title_link": "https://api.slack.com/",
"text": "Optional text that appears within the attachment",
"fields": [
{
"title": "Priority",
"value": "High",
"short": false
}
],
"image_url": "http://my-website.com/path/to/image.jpg",
"thumb_url": "http://example.com/path/to/thumb.png"
}
]
}`
_, err := ApiClient.DoPost(url, attachmentPayload, "application/json")
assert.Nil(t, err)
attachmentPayload = `{
"text": "this is a test",
"attachments": [
{
"fallback": "Required plain-text summary of the attachment.",
"color": "#36a64f",
"pretext": "Optional text that appears above the attachment block",
"author_name": "Bobby Tables",
"author_link": "http://flickr.com/bobby/",
"author_icon": "http://flickr.com/icons/bobby.jpg",
"title": "Slack API Documentation",
"title_link": "https://api.slack.com/",
"text": "` + tooLongText + `",
"fields": [
{
"title": "Priority",
"value": "High",
"short": false
}
],
"image_url": "http://my-website.com/path/to/image.jpg",
"thumb_url": "http://example.com/path/to/thumb.png"
}
]
}`
_, err = ApiClient.DoPost(url, attachmentPayload, "application/json")
assert.Nil(t, err)
})
t.Run("DisableWebhooks", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false })
_, err := ApiClient.DoPost(url, "{\"text\":\"this is a test\"}", "application/json")
assert.NotNil(t, err)
})
}
func TestCommandWebhooks(t *testing.T) {
th := Setup().InitBasic()
defer th.TearDown()
cmd, err := th.App.CreateCommand(&model.Command{
CreatorId: th.BasicUser.Id,
TeamId: th.BasicTeam.Id,
URL: "http://nowhere.com",
Method: model.COMMAND_METHOD_POST,
Trigger: "delayed"})
require.Nil(t, err)
args := &model.CommandArgs{
TeamId: th.BasicTeam.Id,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
}
hook, err := th.App.CreateCommandWebhook(cmd.Id, args)
if err != nil {
t.Fatal(err)
}
if resp, _ := http.Post(ApiClient.Url+"/hooks/commands/123123123123", "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)); resp.StatusCode != http.StatusNotFound {
t.Fatal("expected not-found for non-existent hook")
}
if resp, err := http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"invalid`)); err != nil || resp.StatusCode != http.StatusBadRequest {
t.Fatal(err)
}
for i := 0; i < 5; i++ {
if resp, err := http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)); err != nil || resp.StatusCode != http.StatusOK {
t.Fatal(err)
}
}
if resp, _ := http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)); resp.StatusCode != http.StatusBadRequest {
t.Fatal("expected error for sixth usage")
}
}