-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathcommand_test.go
More file actions
829 lines (719 loc) · 28.4 KB
/
Copy pathcommand_test.go
File metadata and controls
829 lines (719 loc) · 28.4 KB
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
// Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package main
import (
"context"
"encoding/json"
"testing"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/plugin/plugintest"
"github.com/mattermost/mattermost/server/public/pluginapi"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
gitLabAPI "github.com/xanzy/go-gitlab"
"go.uber.org/mock/gomock"
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
mocks "github.com/mattermost/mattermost-plugin-gitlab/server/gitlab/mocks"
)
type subscribeCommandTest struct {
testName string
parameters []string
want string
webhookInfo []*gitlab.WebhookInfo
mattermostURL string
noAccess bool
projectHookErr error
getProjectErr error
mockGitlab bool
}
const (
subscribeSuccessMessage = "Successfully subscribed to group/project.\nA Webhook is needed, run ```/gitlab webhook add group/project``` to create one now."
testGitlabToken = `{"access_token":"6328a1014b19f741489b48cdc4291d93aa2957b0cea67335a34dcdadaf212139","token_type":"Bearer","refresh_token":"e6453b621e8979214c9f8a1b0e1e39723df8af11cef5e0d613a2cb2e39bdfeb7","expiry":"3022-10-23T15:14:43.623638795-05:00"}`
testEncryptionKey = `shD-LC2DElnQzUO50cbvlOvjsNnzfEbk`
)
var subscribeCommandTests = []subscribeCommandTest{
{
testName: "No Subscriptions",
parameters: []string{"list"},
want: "Currently there are no subscriptions in this channel",
},
{
testName: "No Subcommand",
parameters: []string{},
want: invalidSubscribeSubCommand,
},
{
testName: "No Repository permissions",
parameters: []string{"add", "group/project"},
mockGitlab: true,
want: "You don't have the permissions to create subscriptions for this project.",
webhookInfo: []*gitlab.WebhookInfo{{URL: "example.com/somewebhookURL"}},
noAccess: true,
mattermostURL: "example.com",
getProjectErr: errors.New("unable to get project"),
},
{
testName: "Guest permissions only",
parameters: []string{"add", "group/project"},
mockGitlab: true,
want: "You don't have the permissions to create subscriptions for this project.",
webhookInfo: []*gitlab.WebhookInfo{{URL: "example.com/somewebhookURL"}},
noAccess: true,
mattermostURL: "example.com",
},
{
testName: "Hook Found",
parameters: []string{"add", "group/project"},
mockGitlab: true,
want: "Successfully subscribed to group/project.",
webhookInfo: []*gitlab.WebhookInfo{{URL: "example.com/somewebhookURL"}},
mattermostURL: "example.com",
},
{
testName: "No webhooks",
parameters: []string{"add", "group/project"},
mattermostURL: "example.com",
webhookInfo: []*gitlab.WebhookInfo{{}},
mockGitlab: true,
want: subscribeSuccessMessage,
},
{
testName: "Multiple un-matching hooks",
parameters: []string{"add", "group/project"},
mattermostURL: "example.com",
mockGitlab: true,
webhookInfo: []*gitlab.WebhookInfo{{URL: "www.anotherhook.io/wrong"}, {URL: "www.213210948239324.edu/notgood"}},
want: subscribeSuccessMessage,
},
{
testName: "Error getting webhooks",
parameters: []string{"add", "group"},
mattermostURL: "example.com",
mockGitlab: true,
webhookInfo: []*gitlab.WebhookInfo{{}},
want: "Successfully subscribed to group.\nA Webhook is needed, run ```/gitlab webhook add group``` to create one now.\n**Note:** We are unable to determine the webhook status for this project. Please contact your project administrator",
projectHookErr: errors.New("unable to get project hooks"),
},
{
testName: "Missing Organization/Repository",
parameters: []string{"add"},
want: missingOrgOrRepoFromSubscribeCommand,
},
{
testName: "Additional Features Provided",
parameters: []string{"add", "group/project", "merges", "tag"},
mockGitlab: true,
noAccess: true,
want: "You don't have the permissions to create subscriptions for this project.",
},
{
testName: "Delete Missing Repository",
parameters: []string{"delete"},
want: specifyRepositoryMessage,
},
{
testName: "Error Deleting Subscription",
parameters: []string{"delete", ""},
want: "Encountered an error trying to unsubscribe. Please try again.",
},
{
testName: "Invalid Subcommand",
parameters: []string{"unknown"},
want: invalidSubscribeSubCommand,
},
}
func TestSubscribeCommand(t *testing.T) {
for _, test := range subscribeCommandTests {
t.Run(test.testName, func(t *testing.T) {
mockCtrl := gomock.NewController(t)
channelID := "12345"
userInfo := &gitlab.UserInfo{
UserID: "user_id",
}
p := getTestPlugin(t, mockCtrl, test.webhookInfo, test.mattermostURL, test.projectHookErr, test.getProjectErr, test.mockGitlab, test.noAccess)
subscribeMessage, _ := p.subscribeCommand(context.Background(), test.parameters, channelID, &configuration{}, userInfo)
assert.Equal(t, test.want, subscribeMessage, "Subscribe command message should be the same.")
})
}
}
type webhookCommandTest struct {
testName string
parameters []string
scope string
webhookInfo []*gitlab.WebhookInfo
want string
siteURL string
webhook *gitlab.WebhookInfo
}
var listWebhookCommandTests = []webhookCommandTest{
{
testName: "List Project hooks",
parameters: []string{"list", "group/project"},
scope: "project",
webhookInfo: []*gitlab.WebhookInfo{
{
URL: "http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook",
PushEvents: true,
IssuesEvents: true,
ConfidentialIssuesEvents: true,
MergeRequestsEvents: true,
TagPushEvents: true,
NoteEvents: true,
JobEvents: false,
PipelineEvents: false,
WikiPageEvents: false,
},
},
want: "\n\n`http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook`" + `
Triggers:
* Push Events
* Tag Push Events
* Comments
* Issues Events
* Confidential Issues Events
* Merge Request Events
`,
},
{
testName: "List multiple project hooks",
parameters: []string{"list", "group/project"},
scope: "project",
webhookInfo: []*gitlab.WebhookInfo{
{
URL: "http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook",
PushEvents: true,
},
{
URL: "http://anotherURL",
PushEvents: true,
},
},
want: "\n\n`http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook`" + `
Triggers:
* Push Events
` + "\n\n`http://anotherURL`" + `
Triggers:
* Push Events
`,
},
{
testName: "List Group hooks",
parameters: []string{"list", "group"},
scope: "group",
webhookInfo: []*gitlab.WebhookInfo{
{
URL: "http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook",
PushEvents: true,
IssuesEvents: true,
ConfidentialIssuesEvents: true,
MergeRequestsEvents: true,
TagPushEvents: true,
NoteEvents: true,
JobEvents: false,
PipelineEvents: false,
WikiPageEvents: false,
},
},
want: "\n\n`http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook`" + `
Triggers:
* Push Events
* Tag Push Events
* Comments
* Issues Events
* Confidential Issues Events
* Merge Request Events
`,
},
{
testName: "Unrecognized sub command",
parameters: []string{"invalid", "group"},
want: "Unknown webhook command: invalid",
},
{
testName: "List missing namespace",
parameters: []string{"list"},
want: "Unknown action, please use `/gitlab help` to see all actions available.",
},
}
func TestListWebhookCommand(t *testing.T) {
for _, test := range listWebhookCommandTests {
t.Run(test.testName, func(t *testing.T) {
p := new(Plugin)
mockCtrl := gomock.NewController(t)
mockedClient := mocks.NewMockGitlab(mockCtrl)
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
p.configuration = &configuration{
EncryptionKey: testEncryptionKey,
}
api := &plugintest.API{}
api.On("KVGet", "_usertoken").Return([]byte(encryptedToken), nil)
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
switch test.scope {
case "project":
mockedClient.EXPECT().GetProjectHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(test.webhookInfo, nil)
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "project", nil)
p.GitlabClient = mockedClient
case "group":
mockedClient.EXPECT().GetGroupHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(test.webhookInfo, nil)
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "", nil)
p.GitlabClient = mockedClient
}
got := p.webhookCommand(context.Background(), test.parameters, &gitlab.UserInfo{}, true)
assert.Equal(t, test.want, got)
})
}
}
func TestListWebhookCommandNamespaceNotAllowed(t *testing.T) {
p := new(Plugin)
mockCtrl := gomock.NewController(t)
mockedClient := mocks.NewMockGitlab(mockCtrl)
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("other-group", "project", nil)
p.GitlabClient = mockedClient
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
p.configuration = &configuration{
EncryptionKey: testEncryptionKey,
GitlabGroup: "allowed-group",
}
api := &plugintest.API{}
api.On("KVGet", "_usertoken").Return([]byte(encryptedToken), nil)
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
got := p.webhookCommand(context.Background(), []string{"list", "other-group/project"}, &gitlab.UserInfo{}, true)
assert.Contains(t, got, "only repositories in the allowed-group namespace are allowed")
}
func getTestPlugin(t *testing.T, mockCtrl *gomock.Controller, hooks []*gitlab.WebhookInfo, mattermostURL string, projectHookErr error, getProjectErr error, mockGitlab, noAccess bool) *Plugin {
p := new(Plugin)
accessLevel := gitLabAPI.OwnerPermissions
if noAccess {
accessLevel = gitLabAPI.GuestPermissions
}
mockedClient := mocks.NewMockGitlab(mockCtrl)
if mockGitlab {
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("group", "project", nil)
if getProjectErr != nil {
mockedClient.EXPECT().GetProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, getProjectErr)
} else {
mockedClient.EXPECT().GetProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&gitLabAPI.Project{
Permissions: &gitLabAPI.Permissions{
ProjectAccess: &gitLabAPI.ProjectAccess{
AccessLevel: accessLevel,
},
},
}, nil)
}
if !noAccess {
mockedClient.EXPECT().GetProjectHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(hooks, projectHookErr)
if projectHookErr == nil {
mockedClient.EXPECT().GetGroupHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(hooks, projectHookErr)
}
}
}
p.GitlabClient = mockedClient
conf := &model.Config{}
conf.ServiceSettings.SiteURL = &mattermostURL
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
p.configuration = &configuration{
EncryptionKey: testEncryptionKey,
}
info := gitlab.UserInfo{
UserID: "user_id",
GitlabUsername: "gitlab_username",
}
jsonInfo, err := json.Marshal(info)
require.NoError(t, err)
var subVal []byte
api := &plugintest.API{}
api.On("GetConfig", mock.Anything).Return(conf)
api.On("KVGet", "user_id_usertoken").Return([]byte(encryptedToken), nil)
api.On("KVGet", "user_id_userinfo").Return(subVal, nil).Once()
api.On("KVGet", "user_id_gitlabtoken").Return(jsonInfo, nil).Once()
api.On("KVGet", "subscriptions").Return(subVal, nil)
api.On("KVSet", mock.Anything, mock.Anything).Return(nil)
api.On("KVSetWithOptions", mock.AnythingOfType("string"), mock.Anything, mock.AnythingOfType("model.PluginKVSetOptions")).Return(true, nil)
api.On("PublishWebSocketEvent", mock.Anything, mock.Anything, mock.Anything).Return(nil)
api.On("LogWarn",
mock.AnythingOfType("string"),
mock.AnythingOfType("string"),
mock.AnythingOfType("string"),
mock.AnythingOfType("string"),
mock.AnythingOfType("string"))
api.On("LogDebug",
mock.AnythingOfType("string"),
mock.AnythingOfType("string"),
mock.AnythingOfType("string"))
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
return p
}
var exampleWebhookWithAlltriggers = &gitlab.WebhookInfo{
URL: "https://example.com",
PushEvents: true,
TagPushEvents: true,
NoteEvents: true,
ConfidentialNoteEvents: true,
IssuesEvents: true,
ConfidentialIssuesEvents: true,
MergeRequestsEvents: true,
JobEvents: true,
PipelineEvents: true,
WikiPageEvents: true,
EnableSSLVerification: true,
}
const allTriggersFormated = `
SSL Verification Enabled
Triggers:
* Push Events
* Tag Push Events
* Comments
* Confidential Comments
* Issues Events
* Confidential Issues Events
* Merge Request Events
* Job Events
* Pipeline Events
* Wiki Page Events
`
var addWebhookCommandTests = []webhookCommandTest{
{
testName: "Create project hook with defaults",
parameters: []string{"add", "group/project"},
want: "Webhook Created:\n\n\n`https://example.com`" + allTriggersFormated,
siteURL: "https://example.com",
webhook: exampleWebhookWithAlltriggers,
},
{
testName: "Create project hook with all trigers",
parameters: []string{"add", "group/project", "*"},
want: "Webhook Created:\n\n\n`https://example.com`" + allTriggersFormated,
siteURL: "https://example.com",
webhook: exampleWebhookWithAlltriggers,
},
{
testName: "Create project hook with explicit trigers",
parameters: []string{"add", "group/project", "PushEvents,MergeRequestEvents"},
want: "Webhook Created:\n\n\n`https://example.com`" + `
Triggers:
* Push Events
* Merge Request Events
`,
siteURL: "https://example.com",
webhook: &gitlab.WebhookInfo{
URL: "https://example.com",
PushEvents: true,
MergeRequestsEvents: true,
},
},
{
testName: "Create project hook with explicit URL",
parameters: []string{"add", "group/project", "*", "https://anothersite.com"},
want: "Webhook Created:\n\n\n`https://anothersite.com`" + allTriggersFormated,
siteURL: "https://example.com",
webhook: &gitlab.WebhookInfo{
URL: "https://anothersite.com",
EnableSSLVerification: true,
PushEvents: true,
TagPushEvents: true,
NoteEvents: true,
ConfidentialNoteEvents: true,
IssuesEvents: true,
ConfidentialIssuesEvents: true,
MergeRequestsEvents: true,
JobEvents: true,
PipelineEvents: true,
WikiPageEvents: true,
},
},
{
testName: "Create project hook with explicit token",
parameters: []string{"add", "group/project", "*", "https://example.com", "1234abcd"},
want: "Webhook Created:\n\n\n`https://example.com`" + allTriggersFormated,
siteURL: "https://example.com",
webhook: exampleWebhookWithAlltriggers,
},
{
testName: "Create Group hook with defaults",
parameters: []string{"add", "group"},
want: "Webhook Created:\n\n\n`https://example.com`" + allTriggersFormated,
siteURL: "https://example.com",
scope: "group",
webhook: exampleWebhookWithAlltriggers,
},
}
func TestAddWebhookCommand(t *testing.T) {
for _, test := range addWebhookCommandTests {
t.Run(test.testName, func(t *testing.T) {
p := new(Plugin)
mockCtrl := gomock.NewController(t)
mockedClient := mocks.NewMockGitlab(mockCtrl)
if test.scope == "group" {
mockedClient.EXPECT().NewGroupHook(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(test.webhook, nil)
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "", nil)
} else {
project := &gitLabAPI.Project{ID: 4}
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "project", nil)
mockedClient.EXPECT().GetProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(project, nil)
mockedClient.EXPECT().NewProjectHook(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(test.webhook, nil)
}
p.GitlabClient = mockedClient
conf := &model.Config{}
conf.ServiceSettings.SiteURL = new(test.siteURL)
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
p.configuration = &configuration{
EncryptionKey: testEncryptionKey,
}
api := &plugintest.API{}
api.On("GetConfig", mock.Anything).Return(conf)
api.On("KVGet", "_usertoken").Return([]byte(encryptedToken), nil)
api.On("LogAuditRec", mock.Anything).Maybe()
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
got := p.webhookCommand(context.Background(), test.parameters, &gitlab.UserInfo{}, true)
assert.Equal(t, test.want, got)
})
}
}
func TestAddWebhookCommandNamespaceNotAllowed(t *testing.T) {
p := new(Plugin)
mockCtrl := gomock.NewController(t)
mockedClient := mocks.NewMockGitlab(mockCtrl)
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("other-group", "project", nil)
p.GitlabClient = mockedClient
conf := &model.Config{}
conf.ServiceSettings.SiteURL = new("https://example.com")
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
p.configuration = &configuration{
EncryptionKey: testEncryptionKey,
GitlabGroup: "allowed-group",
}
api := &plugintest.API{}
api.On("GetConfig", mock.Anything).Return(conf)
api.On("KVGet", "_usertoken").Return([]byte(encryptedToken), nil)
api.On("LogAuditRec", mock.Anything).Maybe()
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
got := p.webhookCommand(context.Background(), []string{"add", "other-group/project"}, &gitlab.UserInfo{}, true)
assert.Contains(t, got, "only repositories in the allowed-group namespace are allowed")
}
func TestAddWebhookCommandForbidden(t *testing.T) {
p := new(Plugin)
mockCtrl := gomock.NewController(t)
mockedClient := mocks.NewMockGitlab(mockCtrl)
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "project", nil)
mockedClient.EXPECT().GetProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&gitLabAPI.Project{ID: 4}, nil)
mockedClient.EXPECT().NewProjectHook(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, gitlab.ErrForbidden)
p.GitlabClient = mockedClient
conf := &model.Config{}
conf.ServiceSettings.SiteURL = new("https://example.com")
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
p.configuration = &configuration{EncryptionKey: testEncryptionKey}
api := &plugintest.API{}
api.On("GetConfig", mock.Anything).Return(conf)
api.On("KVGet", "_usertoken").Return([]byte(encryptedToken), nil)
api.On("LogAuditRec", mock.Anything).Maybe()
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
got := p.webhookCommand(context.Background(), []string{"add", "group/project"}, &gitlab.UserInfo{}, true)
assert.Contains(t, got, "You don't have permission to manage webhooks for the repository `group/project`")
assert.Contains(t, got, "Maintainer or Owner access")
}
func TestListWebhookCommandForbidden(t *testing.T) {
p := new(Plugin)
mockCtrl := gomock.NewController(t)
mockedClient := mocks.NewMockGitlab(mockCtrl)
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "", nil)
mockedClient.EXPECT().GetGroupHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, gitlab.ErrForbidden)
p.GitlabClient = mockedClient
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
p.configuration = &configuration{EncryptionKey: testEncryptionKey}
api := &plugintest.API{}
api.On("KVGet", "_usertoken").Return([]byte(encryptedToken), nil)
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
got := p.webhookCommand(context.Background(), []string{"list", "group"}, &gitlab.UserInfo{}, true)
assert.Contains(t, got, "You don't have permission to manage webhooks for the group `group`")
assert.Contains(t, got, "Maintainer or Owner access")
}
type instanceNameTestCase struct {
name string
parameters []string
instanceName string
exists bool
}
var instanceNameTestCases = []instanceNameTestCase{
{"single word", []string{"SimpleInstance"}, "SimpleInstance", true},
{"whitespace in name", []string{"Gitlab", "Test", "Instance"}, "Gitlab Test Instance", true},
{"multiple whitespaces", []string{"My", "Corporate", "GitLab", "Server"}, "My Corporate GitLab Server", true},
{"leading and trailing whitespaces", []string{" Test", "Instance", "Name "}, "Test Instance Name", true},
{"non-existent instance", []string{"NonExistent", "Instance"}, "NonExistent Instance", false},
}
func setupInstanceCommandTest(t *testing.T, instanceList []string, instanceConfig map[string]InstanceConfiguration) (*Plugin, *string, *plugintest.API) {
t.Helper()
p := new(Plugin)
p.configuration = &configuration{EncryptionKey: testEncryptionKey}
instanceListJSON, _ := json.Marshal(instanceList)
instanceConfigJSON, _ := json.Marshal(instanceConfig)
var capturedMessage string
api := &plugintest.API{}
api.On("KVGet", instanceConfigNameListKey).Return(instanceListJSON, nil)
api.On("KVGet", instanceConfigMapKey).Return(instanceConfigJSON, nil)
api.On("KVSetWithOptions", mock.AnythingOfType("string"), mock.Anything, mock.AnythingOfType("model.PluginKVSetOptions")).Return(true, nil)
api.On("SavePluginConfig", mock.Anything).Return(nil)
api.On("LogError", mock.Anything, mock.Anything, mock.Anything).Return(nil)
siteURL := "https://mattermost.example.com"
conf := &model.Config{}
conf.ServiceSettings.SiteURL = &siteURL
api.On("GetConfig", mock.Anything).Return(conf)
api.On("SendEphemeralPost", mock.Anything, mock.MatchedBy(func(post *model.Post) bool {
capturedMessage = post.Message
return true
})).Return(&model.Post{})
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
return p, &capturedMessage, api
}
func TestAdminProtectedCommands(t *testing.T) {
t.Run("instance commands require admin", func(t *testing.T) {
testCases := []struct {
name string
parameters []string
}{
{"list", []string{"list"}},
{"install", []string{"install"}},
{"uninstall", []string{"uninstall", "test-instance"}},
{"set-default", []string{"set-default", "test-instance"}},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
p := new(Plugin)
p.configuration = &configuration{EncryptionKey: testEncryptionKey}
// Mock a non-admin user
nonAdminUser := &model.User{
Id: "user_id",
Roles: "system_user",
}
api := &plugintest.API{}
api.On("GetUser", "user_id").Return(nonAdminUser, nil)
var capturedMessage string
api.On("SendEphemeralPost", mock.Anything, mock.MatchedBy(func(post *model.Post) bool {
capturedMessage = post.Message
return true
})).Return(&model.Post{})
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
args := &model.CommandArgs{UserId: "user_id", ChannelId: "channel_id"}
_, _ = p.handleInstance(args, tc.parameters)
assert.Contains(t, capturedMessage, "Only System Admins are allowed to manage instances.")
})
}
})
t.Run("instance commands allowed for admin", func(t *testing.T) {
p := new(Plugin)
p.configuration = &configuration{EncryptionKey: testEncryptionKey}
// Mock admin user
adminUser := &model.User{
Id: "admin_id",
Roles: "system_admin system_user",
}
instanceList := []string{"test-instance"}
instanceConfig := map[string]InstanceConfiguration{"test-instance": {GitlabURL: "https://gitlab.example.com"}}
instanceListJSON, _ := json.Marshal(instanceList)
instanceConfigJSON, _ := json.Marshal(instanceConfig)
api := &plugintest.API{}
api.On("GetUser", "admin_id").Return(adminUser, nil)
api.On("KVGet", instanceConfigNameListKey).Return(instanceListJSON, nil)
api.On("KVGet", instanceConfigMapKey).Return(instanceConfigJSON, nil)
var capturedMessage string
api.On("SendEphemeralPost", mock.Anything, mock.MatchedBy(func(post *model.Post) bool {
capturedMessage = post.Message
return true
})).Return(&model.Post{})
p.SetAPI(api)
p.client = pluginapi.NewClient(api, p.Driver)
args := &model.CommandArgs{UserId: "admin_id", ChannelId: "channel_id"}
_, _ = p.handleInstance(args, []string{"list"})
// Should show instance list, not an error
assert.Contains(t, capturedMessage, "test-instance")
assert.NotContains(t, capturedMessage, "Only System Admins")
})
}
func TestInstanceCommands(t *testing.T) {
args := &model.CommandArgs{UserId: "user_id", ChannelId: "channel_id"}
t.Run("set-default", func(t *testing.T) {
for _, tc := range instanceNameTestCases {
t.Run("set-default "+tc.name, func(t *testing.T) {
instanceList := []string{tc.instanceName}
if !tc.exists {
instanceList = []string{"Other Instance"}
}
p, msg, _ := setupInstanceCommandTest(t, instanceList, nil)
_, _ = p.handleSetDefaultInstance(args, tc.parameters)
if tc.exists {
assert.Contains(t, *msg, "Instance '"+tc.instanceName+"' has been set as the default.")
} else {
assert.Contains(t, *msg, "does not exist")
}
})
}
t.Run("no parameters", func(t *testing.T) {
p, msg, _ := setupInstanceCommandTest(t, nil, nil)
_, _ = p.handleSetDefaultInstance(args, []string{})
assert.Contains(t, *msg, "Please specify the instance name.")
})
})
t.Run("uninstall", func(t *testing.T) {
for _, tc := range instanceNameTestCases {
t.Run("uninstall "+tc.name, func(t *testing.T) {
instanceList := []string{tc.instanceName}
config := map[string]InstanceConfiguration{tc.instanceName: {GitlabURL: "https://gitlab.example.com"}}
if !tc.exists {
instanceList = []string{"Other Instance"}
config = map[string]InstanceConfiguration{"Other Instance": {GitlabURL: "https://gitlab.example.com"}}
}
p, msg, _ := setupInstanceCommandTest(t, instanceList, config)
_, _ = p.handleUnInstallInstance(args, tc.parameters)
if tc.exists {
assert.Contains(t, *msg, "Instance '"+tc.instanceName+"' has been uninstalled.")
} else {
assert.Contains(t, *msg, "not found in the list")
}
})
}
t.Run("no parameters", func(t *testing.T) {
p, msg, _ := setupInstanceCommandTest(t, nil, nil)
_, _ = p.handleUnInstallInstance(args, []string{})
assert.Contains(t, *msg, "Please specify the instance name.")
})
})
t.Run("connect", func(t *testing.T) {
t.Run("with default instance configured", func(t *testing.T) {
instanceList := []string{"production"}
instanceConfig := map[string]InstanceConfiguration{
"production": {
GitlabURL: "https://gitlab.example.com",
GitlabOAuthClientID: "client-id",
GitlabOAuthClientSecret: "client-secret",
},
}
p, msg, _ := setupInstanceCommandTest(t, instanceList, instanceConfig)
p.configuration.DefaultInstanceName = "production"
_, _ = p.handleConnect(args, []string{})
assert.Contains(t, *msg, "Click here to link your GitLab account")
})
t.Run("with legacy plugin settings", func(t *testing.T) {
p, msg, _ := setupInstanceCommandTest(t, nil, nil)
p.configuration.GitlabURL = "https://gitlab.example.com"
p.configuration.GitlabOAuthClientID = "client-id"
p.configuration.GitlabOAuthClientSecret = "client-secret"
_, _ = p.handleConnect(args, []string{})
assert.Contains(t, *msg, "Click here to link your GitLab account")
})
t.Run("not configured", func(t *testing.T) {
p, msg, _ := setupInstanceCommandTest(t, nil, nil)
_, _ = p.handleConnect(args, []string{})
assert.Contains(t, *msg, "No instance is configured")
})
})
}