summaryrefslogtreecommitdiffstats
path: root/app/plugin_test.go
blob: db5954d4dff2f8a23f01f7983963757089731e5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package app

import (
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/gorilla/mux"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/mattermost/mattermost-server/model"
	"github.com/mattermost/mattermost-server/plugin"
	"github.com/mattermost/mattermost-server/plugin/plugintest"
)

func TestPluginKeyValueStore(t *testing.T) {
	th := Setup().InitBasic()
	defer th.TearDown()

	pluginId := "testpluginid"

	assert.Nil(t, th.App.SetPluginKey(pluginId, "key", []byte("test")))
	ret, err := th.App.GetPluginKey(pluginId, "key")
	assert.Nil(t, err)
	assert.Equal(t, []byte("test"), ret)

	// Test inserting over existing entries
	assert.Nil(t, th.App.SetPluginKey(pluginId, "key", []byte("test2")))

	// Test getting non-existent key
	ret, err = th.App.GetPluginKey(pluginId, "notakey")
	assert.Nil(t, err)
	assert.Nil(t, ret)

	assert.Nil(t, th.App.DeletePluginKey(pluginId, "stringkey"))
	assert.Nil(t, th.App.DeletePluginKey(pluginId, "intkey"))
	assert.Nil(t, th.App.DeletePluginKey(pluginId, "postkey"))
	assert.Nil(t, th.App.DeletePluginKey(pluginId, "notrealkey"))
}

func TestServePluginRequest(t *testing.T) {
	th := Setup().InitBasic()
	defer th.TearDown()

	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = false })

	w := httptest.NewRecorder()
	r := httptest.NewRequest("GET", "/plugins/foo/bar", nil)
	th.App.ServePluginRequest(w, r)
	assert.Equal(t, http.StatusNotImplemented, w.Result().StatusCode)
}

func TestHandlePluginRequest(t *testing.T) {
	th := Setup().InitBasic()
	defer th.TearDown()

	th.App.UpdateConfig(func(cfg *model.Config) {
		*cfg.PluginSettings.Enable = false
		*cfg.ServiceSettings.EnableUserAccessTokens = true
	})

	token, err := th.App.CreateUserAccessToken(&model.UserAccessToken{
		UserId: th.BasicUser.Id,
	})
	require.Nil(t, err)

	var assertions func(*http.Request)
	router := mux.NewRouter()
	router.HandleFunc("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}/{anything:.*}", func(_ http.ResponseWriter, r *http.Request) {
		th.App.servePluginRequest(nil, r, func(_ http.ResponseWriter, r *http.Request) {
			assertions(r)
		})
	})

	r := httptest.NewRequest("GET", "/plugins/foo/bar", nil)
	r.Header.Add("Authorization", "Bearer "+token.Token)
	assertions = func(r *http.Request) {
		assert.Equal(t, "/bar", r.URL.Path)
		assert.Equal(t, th.BasicUser.Id, r.Header.Get("Mattermost-User-Id"))
	}
	router.ServeHTTP(nil, r)

	r = httptest.NewRequest("GET", "/plugins/foo/bar?a=b&access_token="+token.Token+"&c=d", nil)
	assertions = func(r *http.Request) {
		assert.Equal(t, "/bar", r.URL.Path)
		assert.Equal(t, "a=b&c=d", r.URL.RawQuery)
		assert.Equal(t, th.BasicUser.Id, r.Header.Get("Mattermost-User-Id"))
	}
	router.ServeHTTP(nil, r)

	r = httptest.NewRequest("GET", "/plugins/foo/bar?a=b&access_token=asdf&c=d", nil)
	assertions = func(r *http.Request) {
		assert.Equal(t, "/bar", r.URL.Path)
		assert.Equal(t, "a=b&c=d", r.URL.RawQuery)
		assert.Empty(t, r.Header.Get("Mattermost-User-Id"))
	}
	router.ServeHTTP(nil, r)
}

type testPlugin struct {
	plugintest.Hooks
}

func (p *testPlugin) OnConfigurationChange() error {
	return nil
}

func (p *testPlugin) OnDeactivate() error {
	return nil
}

type pluginCommandTestPlugin struct {
	testPlugin

	TeamId string
}

func (p *pluginCommandTestPlugin) OnActivate(api plugin.API) error {
	if err := api.RegisterCommand(&model.Command{
		Trigger: "foo",
		TeamId:  p.TeamId,
	}); err != nil {
		return err
	}
	if err := api.RegisterCommand(&model.Command{
		Trigger: "foo2",
		TeamId:  p.TeamId,
	}); err != nil {
		return err
	}
	return api.UnregisterCommand(p.TeamId, "foo2")
}

func (p *pluginCommandTestPlugin) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
	if args.Command == "/foo" {
		return &model.CommandResponse{
			Text: "bar",
		}, nil
	}
	return nil, model.NewAppError("ExecuteCommand", "this is an error", nil, "", http.StatusBadRequest)
}

func TestPluginCommands(t *testing.T) {
	th := Setup().InitBasic()
	defer th.TearDown()

	th.InstallPlugin(&model.Manifest{
		Id: "foo",
	}, &pluginCommandTestPlugin{
		TeamId: th.BasicTeam.Id,
	})

	require.Nil(t, th.App.EnablePlugin("foo"))

	// Ideally, we would wait for the websocket activation event instead of just sleeping.
	time.Sleep(500 * time.Millisecond)

	pluginStatuses, err := th.App.GetPluginStatuses()
	require.Nil(t, err)
	found := false
	for _, pluginStatus := range pluginStatuses {
		if pluginStatus.PluginId == "foo" {
			require.Equal(t, model.PluginStateRunning, pluginStatus.State)
			found = true
		}
	}
	require.True(t, found, "failed to find plugin foo in plugin statuses")

	resp, err := th.App.ExecuteCommand(&model.CommandArgs{
		Command:   "/foo2",
		TeamId:    th.BasicTeam.Id,
		UserId:    th.BasicUser.Id,
		ChannelId: th.BasicChannel.Id,
	})
	require.NotNil(t, err)
	assert.Equal(t, http.StatusNotFound, err.StatusCode)

	resp, err = th.App.ExecuteCommand(&model.CommandArgs{
		Command:   "/foo",
		TeamId:    th.BasicTeam.Id,
		UserId:    th.BasicUser.Id,
		ChannelId: th.BasicChannel.Id,
	})
	require.Nil(t, err)
	assert.Equal(t, "bar", resp.Text)

	resp, err = th.App.ExecuteCommand(&model.CommandArgs{
		Command:   "/foo baz",
		TeamId:    th.BasicTeam.Id,
		UserId:    th.BasicUser.Id,
		ChannelId: th.BasicChannel.Id,
	})
	require.NotNil(t, err)
	require.Equal(t, "this is an error", err.Message)
	assert.Nil(t, resp)

	require.Nil(t, th.App.RemovePlugin("foo"))

	resp, err = th.App.ExecuteCommand(&model.CommandArgs{
		Command:   "/foo",
		TeamId:    th.BasicTeam.Id,
		UserId:    th.BasicUser.Id,
		ChannelId: th.BasicChannel.Id,
	})
	require.NotNil(t, err)
	assert.Equal(t, http.StatusNotFound, err.StatusCode)
}

type pluginBadActivation struct {
	testPlugin
}

func (p *pluginBadActivation) OnActivate(api plugin.API) error {
	return errors.New("won't activate for some reason")
}

func TestPluginBadActivation(t *testing.T) {
	th := Setup().InitBasic()
	defer th.TearDown()

	th.InstallPlugin(&model.Manifest{
		Id: "foo",
	}, &pluginBadActivation{})

	t.Run("EnablePlugin bad activation", func(t *testing.T) {
		err := th.App.EnablePlugin("foo")
		assert.Nil(t, err)

		// Ideally, we would wait for the websocket activation event instead of just
		// sleeping.
		time.Sleep(500 * time.Millisecond)

		pluginStatuses, err := th.App.GetPluginStatuses()
		require.Nil(t, err)
		found := false
		for _, pluginStatus := range pluginStatuses {
			if pluginStatus.PluginId == "foo" {
				require.Equal(t, model.PluginStateFailedToStart, pluginStatus.State)
				found = true
			}
		}
		require.True(t, found, "failed to find plugin foo in plugin statuses")
	})
}

func TestGetPluginStatusesDisabled(t *testing.T) {
	th := Setup().InitBasic()
	defer th.TearDown()

	th.App.UpdateConfig(func(cfg *model.Config) {
		*cfg.PluginSettings.Enable = false
	})

	_, err := th.App.GetPluginStatuses()
	require.EqualError(t, err, "GetPluginStatuses: Plugins have been disabled. Please check your logs for details., ")
}

func TestGetPluginStatuses(t *testing.T) {
	th := Setup().InitBasic()
	defer th.TearDown()

	th.App.UpdateConfig(func(cfg *model.Config) {
		*cfg.PluginSettings.Enable = true
	})

	pluginStatuses, err := th.App.GetPluginStatuses()
	require.Nil(t, err)
	require.NotNil(t, pluginStatuses)
}