-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathapi.go
More file actions
1121 lines (939 loc) · 37.7 KB
/
Copy pathapi.go
File metadata and controls
1121 lines (939 loc) · 37.7 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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"regexp"
"runtime/debug"
"strconv"
"strings"
"time"
"unicode"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/plugin"
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/flow"
internGitlab "github.com/xanzy/go-gitlab"
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
)
var oauthStateRegexp = regexp.MustCompile(`^[a-z0-9]{15}_[a-z0-9]{26}$`)
const (
APIErrorIDNotConnected = "not_connected"
queryParamSearch = "search"
queryParamProjectID = "projectID"
requestTimeout = 30 * time.Second
)
func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
p.router.ServeHTTP(w, r)
}
func (p *Plugin) initializeAPI() {
p.router = mux.NewRouter()
p.router.Use(p.withRecovery)
p.router.PathPrefix("/mcp").HandlerFunc(p.serveMCPHTTP)
oauthRouter := p.router.PathPrefix("/oauth").Subrouter()
apiRouter := p.router.PathPrefix("/api/v1").Subrouter()
apiRouter.Use(p.checkConfigured)
p.router.HandleFunc("/webhook", p.handleWebhook).Methods(http.MethodPost)
oauthRouter.HandleFunc("/connect", p.checkAuth(p.attachContext(p.connectUserToGitlab), ResponseTypePlain)).Methods(http.MethodGet)
oauthRouter.HandleFunc("/complete", p.checkAuth(p.attachContext(p.completeConnectUserToGitlab), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/connected", p.attachContext(p.getConnected)).Methods(http.MethodGet)
apiRouter.HandleFunc("/user", p.checkAuth(p.attachContext(p.getGitlabUser), ResponseTypeJSON)).Methods(http.MethodPost)
apiRouter.HandleFunc("/todo", p.checkAuth(p.attachUserContext(p.postToDo), ResponseTypeJSON)).Methods(http.MethodPost)
apiRouter.HandleFunc("/issue", p.checkAuth(p.attachUserContext(p.createIssue), ResponseTypePlain)).Methods(http.MethodPost)
apiRouter.HandleFunc("/attachcommenttoissue", p.checkAuth(p.attachUserContext(p.attachCommentToIssue), ResponseTypePlain)).Methods(http.MethodPost)
apiRouter.HandleFunc("/projects", p.checkAuth(p.attachUserContext(p.getYourProjects), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/labels", p.checkAuth(p.attachUserContext(p.getLabels), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/assignees", p.checkAuth(p.attachUserContext(p.getAssignees), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/milestones", p.checkAuth(p.attachUserContext(p.getMilestones), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/searchissues", p.checkAuth(p.attachUserContext(p.searchIssues), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/lhs-data", p.checkAuth(p.attachUserContext(p.getLHSData), ResponseTypePlain)).Methods(http.MethodGet)
apiRouter.HandleFunc("/prdetails", p.checkAuth(p.attachUserContext(p.getPrDetails), ResponseTypePlain)).Methods(http.MethodPost)
apiRouter.HandleFunc("/issue", p.checkAuth(p.attachUserContext(p.getIssueByNumber), ResponseTypeJSON)).Methods(http.MethodGet)
apiRouter.HandleFunc("/mergerequest", p.checkAuth(p.attachUserContext(p.getMergeRequestByNumber), ResponseTypeJSON)).Methods(http.MethodGet)
apiRouter.HandleFunc("/settings", p.checkAuth(p.attachUserContext(p.updateSettings), ResponseTypePlain)).Methods(http.MethodPost)
apiRouter.HandleFunc("/channel/{channel_id:[A-Za-z0-9]+}/subscriptions", p.checkAuth(p.attachUserContext(p.getChannelSubscriptions), ResponseTypeJSON)).Methods(http.MethodGet)
}
type Context struct {
Ctx context.Context
UserID string
Log logger.Logger
}
func (p *Plugin) createContext(_ http.ResponseWriter, r *http.Request) (*Context, context.CancelFunc) {
userID := r.Header.Get("Mattermost-User-ID")
logger := logger.New(p.API).With(logger.LogContext{
"userid": userID,
})
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
context := &Context{
Ctx: ctx,
UserID: userID,
Log: logger,
}
return context, cancel
}
// HTTPHandlerFuncWithContext is http.HandleFunc but with a Context attached
type HTTPHandlerFuncWithContext func(c *Context, w http.ResponseWriter, r *http.Request)
func (p *Plugin) attachContext(handler HTTPHandlerFuncWithContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
context, cancel := p.createContext(w, r)
defer cancel()
handler(context, w, r)
}
}
type UserContext struct {
Context
GitlabInfo *gitlab.UserInfo
}
// HTTPHandlerFuncWithUserContext is http.HandleFunc but with a UserContext attached
type HTTPHandlerFuncWithUserContext func(c *UserContext, w http.ResponseWriter, r *http.Request)
func (p *Plugin) attachUserContext(handler HTTPHandlerFuncWithUserContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
context, cancel := p.createContext(w, r)
defer cancel()
info, apiErr := p.getGitlabUserInfoByMattermostID(context.UserID)
if apiErr != nil {
p.writeAPIError(w, apiErr)
return
}
context.Log = context.Log.With(logger.LogContext{
"gitlab username": info.GitlabUsername,
"gitlab userid": info.GitlabUserID,
})
userContext := &UserContext{
Context: *context,
GitlabInfo: info,
}
handler(userContext, w, r)
}
}
func (p *Plugin) withRecovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if x := recover(); x != nil {
p.client.Log.Warn("Recovered from a panic",
"url", r.URL.String(),
"error", x,
"stack", string(debug.Stack()))
}
}()
next.ServeHTTP(w, r)
})
}
func (p *Plugin) checkConfigured(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
if err := config.IsValid(); err != nil {
http.Error(w, "This plugin is not configured.", http.StatusNotImplemented)
return
}
next.ServeHTTP(w, r)
})
}
func (p *Plugin) checkAuth(handler http.HandlerFunc, responseType ResponseType) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
switch responseType {
case ResponseTypeJSON:
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized.", StatusCode: http.StatusUnauthorized})
case ResponseTypePlain:
http.Error(w, "Not authorized", http.StatusUnauthorized)
default:
p.client.Log.Debug("Unknown ResponseType detected")
}
return
}
handler(w, r)
}
}
// ResponseType indicates type of response returned by api
type ResponseType string
const (
// ResponseTypeJSON indicates that response type is json
ResponseTypeJSON ResponseType = "JSON_RESPONSE"
// ResponseTypePlain indicates that response type is text plain
ResponseTypePlain ResponseType = "TEXT_RESPONSE"
)
type APIErrorResponse struct {
ID string `json:"id"`
Message string `json:"message"`
StatusCode int `json:"status_code"`
}
func (e *APIErrorResponse) Error() string {
return e.Message
}
func (p *Plugin) writeAPIError(w http.ResponseWriter, err *APIErrorResponse) {
b, _ := json.Marshal(err)
w.WriteHeader(err.StatusCode)
if _, err := w.Write(b); err != nil {
p.client.Log.Warn("can't write api error http response", "err", err.Error())
}
}
// apiErrorForGitlabError returns (message, statusCode) for GitLab client errors. For ErrNamespaceNotAllowed
// it returns the error message and 403; otherwise it returns the defaultMessage and 500.
func apiErrorForGitlabError(err error, defaultMessage string) (message string, statusCode int) {
if err != nil && errors.Is(err, ErrNamespaceNotAllowed) {
return err.Error(), http.StatusForbidden
}
return defaultMessage, http.StatusInternalServerError
}
func (p *Plugin) writeAPIResponse(w http.ResponseWriter, resp any) {
b, jsonErr := json.Marshal(resp)
if jsonErr != nil {
p.client.Log.Warn("Error encoding JSON response", "err", jsonErr.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an unexpected error. Please try again.", StatusCode: http.StatusInternalServerError})
}
if _, err := w.Write(b); err != nil {
p.client.Log.Warn("can't write response user to http", "err", err.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an unexpected error. Please try again.", StatusCode: http.StatusInternalServerError})
}
}
func (p *Plugin) connectUserToGitlab(c *Context, w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
conf, err := p.getOAuthConfig()
if err != nil {
c.Log.WithError(err).Warnf("Failed to get OAuth configuration")
http.Error(w, "OAuth configuration not found", http.StatusInternalServerError)
return
}
state := fmt.Sprintf("%v_%v", model.NewId()[0:15], userID)
if _, err := p.client.KV.Set(state, []byte(state)); err != nil {
c.Log.WithError(err).Warnf("Can't store state oauth2")
http.Error(w, "can't store state oauth2", http.StatusInternalServerError)
return
}
url := conf.AuthCodeURL(state, oauth2.AccessTypeOffline)
ch := p.oauthBroker.SubscribeOAuthComplete(userID)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
var errorMsg string
select {
case err := <-ch:
if err != nil {
errorMsg = err.Error()
}
case <-ctx.Done():
errorMsg = "Timed out waiting for OAuth connection. Please check if the SiteURL is correct."
}
if errorMsg != "" {
_, err := p.poster.DMWithAttachments(userID, &model.MessageAttachment{
Text: fmt.Sprintf("There was an error connecting to your GitLab: `%s` Please double check your configuration.", errorMsg),
Color: string(flow.ColorDanger),
})
if err != nil {
c.Log.WithError(err).Warnf("Failed to DM with cancel information")
}
}
p.oauthBroker.UnsubscribeOAuthComplete(userID, ch)
}()
http.Redirect(w, r, url, http.StatusFound)
}
func (p *Plugin) completeConnectUserToGitlab(c *Context, w http.ResponseWriter, r *http.Request) {
authedUserID := r.Header.Get("Mattermost-User-ID")
if authedUserID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
var rErr error
defer func() {
p.oauthBroker.publishOAuthComplete(authedUserID, rErr, false)
}()
config := p.getConfiguration()
conf, err := p.getOAuthConfig()
if err != nil {
c.Log.WithError(err).Warnf("Failed to get OAuth configuration")
rErr = errors.Wrap(err, "OAuth configuration not found")
http.Error(w, "OAuth configuration not found", http.StatusInternalServerError)
return
}
code := r.URL.Query().Get("code")
if len(code) == 0 {
rErr = errors.New("missing authorization code")
http.Error(w, "Missing authorization code", http.StatusBadRequest)
return
}
state := r.URL.Query().Get("state")
if !oauthStateRegexp.MatchString(state) {
rErr = errors.New("invalid state format")
http.Error(w, "Invalid OAuth state", http.StatusBadRequest)
return
}
userID := strings.Split(state, "_")[1]
if userID != authedUserID {
rErr = errors.New("not authorized, incorrect user")
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
var storedState []byte
err = p.client.KV.Get(state, &storedState)
if err != nil {
c.Log.WithError(err).Warnf("Can't get state from store")
rErr = errors.Wrap(err, "missing stored state")
http.Error(w, "Missing stored OAuth state", http.StatusBadRequest)
return
}
if string(storedState) != state {
rErr = errors.New("invalid state token")
http.Error(w, "Invalid OAuth state", http.StatusBadRequest)
return
}
err = p.client.KV.Delete(state)
if err != nil {
c.Log.WithError(err).Warnf("Failed to delete state token")
rErr = errors.Wrap(err, "error deleting stored state")
http.Error(w, "Error completing OAuth connection", http.StatusInternalServerError)
return
}
tok, err := conf.Exchange(c.Ctx, code)
if err != nil {
c.Log.WithError(err).Warnf("Can't exchange state")
rErr = errors.Wrap(err, "Failed to exchange oauth code into token")
http.Error(w, "Error completing OAuth connection", http.StatusInternalServerError)
return
}
userInfo, err := p.GitlabClient.GetCurrentUser(c.Ctx, userID, *tok)
if err != nil {
c.Log.WithError(err).Warnf("Can't retrieve user info from gitLab API")
rErr = errors.Wrap(err, "unable to connect user to GitLab")
http.Error(w, "Unable to connect user to GitLab", http.StatusInternalServerError)
return
}
if err = p.storeGitlabUserInfo(userInfo); err != nil {
c.Log.WithError(err).Warnf("Can't store user info")
rErr = errors.Wrap(err, "Unable to connect user to GitLab")
http.Error(w, "Unable to connect user to GitLab", http.StatusInternalServerError)
return
}
if err = p.storeGitlabUserToken(userInfo.UserID, tok); err != nil {
c.Log.WithError(err).Warnf("Can't store user token")
rErr = errors.Wrap(err, "Unable to connect user to GitLab")
http.Error(w, "Unable to connect user to GitLab", http.StatusInternalServerError)
return
}
if err = p.storeGitlabToUserIDMapping(userInfo.GitlabUsername, userID); err != nil {
c.Log.WithError(err).Warnf("Can't store GitLab to user id mapping")
}
if err = p.storeGitlabIDToUserIDMapping(userInfo.GitlabUsername, userInfo.GitlabUserID); err != nil {
c.Log.WithError(err).Warnf("Can't store GitLab to GitLab id mapping")
}
flow := p.flowManager.setupFlow.ForUser(authedUserID)
stepName, err := flow.GetCurrentStep()
if err != nil {
c.Log.WithError(err).Warnf("Failed to get current step")
}
if stepName == stepOAuthConnect {
err = flow.Go(stepWebhookQuestion)
if err != nil {
c.Log.WithError(err).Warnf("Failed go to next step")
}
} else {
// Only post introduction message if no setup wizard is running
// Post intro post
message := fmt.Sprintf("#### Welcome to the Mattermost GitLab Plugin!\n"+
"You've connected your Mattermost account to %s on GitLab. Read about the features of this plugin below:\n\n"+
"##### Daily Reminders\n"+
"The first time you log in each day, you will get a post right here letting you know what messages you need to read and what merge requests are awaiting your review.\n"+
"Turn off reminders with `/gitlab settings reminders off`.\n\n"+
"##### Notifications\n"+
"When someone mentions you, requests your review, comments on or modifies one of your merge requests/issues, or assigns you, you'll get a post here about it.\n"+
"Turn off notifications with `/gitlab settings notifications off`.\n\n"+
"##### Sidebar Buttons\n"+
"Check out the buttons in the left-hand sidebar of Mattermost.\n"+
"* The first button tells you how many merge requests you are assigned to.\n"+
"* The second shows the number of merge requests that are awaiting your review.\n"+
"* The third shows the number of issues you are assigned to.\n"+
"* The fourth tracks the number of todos you have.\n"+
"* The fifth will refresh the numbers.\n\n"+
"Click on them!\n\n"+
"##### Slash Commands\n"+
strings.ReplaceAll(commandHelp, "|", "`"), userInfo.GitlabUsername)
if err := p.CreateBotDMPost(userID, message, "custom_git_welcome"); err != nil {
c.Log.WithError(err).Warnf("Can't send help message with bot dm")
}
}
p.client.Frontend.PublishWebSocketEvent(
WsEventConnect,
map[string]any{
"connected": true,
"gitlab_username": userInfo.GitlabUsername,
"gitlab_client_id": config.GitlabOAuthClientID,
"gitlab_url": config.GitlabURL,
"organization": config.GitlabGroup,
},
&model.WebsocketBroadcast{UserId: userID},
)
html := `
<!DOCTYPE html>
<html>
<head>
<script>
window.close();
</script>
</head>
<body>
<p>Completed connecting to GitLab. Please close this window.</p>
</body>
</html>
`
w.Header().Set("Content-Type", "text/html")
if _, err := w.Write([]byte(html)); err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: ">Completed connecting to GitLab. Please close this window.", StatusCode: http.StatusInternalServerError})
}
}
type ConnectedResponse struct {
Connected bool `json:"connected"`
GitlabUsername string `json:"gitlab_username"`
GitlabClientID string `json:"gitlab_client_id"`
GitlabURL string `json:"gitlab_url,omitempty"`
Organization string `json:"organization"`
Settings *gitlab.UserSettings `json:"settings"`
}
type GitlabUserRequest struct {
UserID string `json:"user_id"`
}
type GitlabUserResponse struct {
Username string `json:"username"`
}
func (p *Plugin) getGitlabUser(c *Context, w http.ResponseWriter, r *http.Request) {
req := &GitlabUserRequest{}
dec := json.NewDecoder(r.Body)
if err := dec.Decode(&req); err != nil || req.UserID == "" {
if err != nil {
c.Log.WithError(err).Warnf("Error decoding JSON body")
}
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a JSON object with a non-blank user_id field.", StatusCode: http.StatusBadRequest})
return
}
userInfo, apiErr := p.getGitlabUserInfoByMattermostID(req.UserID)
if apiErr != nil {
if apiErr.ID == APIErrorIDNotConnected {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "User is not connected to a GitLab account.", StatusCode: http.StatusNotFound})
} else {
p.writeAPIError(w, apiErr)
}
return
}
if userInfo == nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "User is not connected to a GitLab account.", StatusCode: http.StatusNotFound})
return
}
p.writeAPIResponse(w, &GitlabUserResponse{Username: userInfo.GitlabUsername})
}
func (p *Plugin) getConnected(c *Context, w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
resp := &ConnectedResponse{
Connected: false,
GitlabURL: config.GitlabURL,
Organization: config.GitlabGroup,
}
info, _ := p.getGitlabUserInfoByMattermostID(c.UserID)
if info != nil {
resp.Connected = true
resp.GitlabUsername = info.GitlabUsername
resp.GitlabClientID = config.GitlabOAuthClientID
resp.Settings = info.Settings
if info.Settings.DailyReminder && r.URL.Query().Get("reminder") == "true" {
lastPostAt := info.LastToDoPostAt
var timezone *time.Location
offset, _ := strconv.Atoi(r.Header.Get("X-Timezone-Offset"))
timezone = time.FixedZone("local", -60*offset)
// Post to do message if it's the next day and been more than an hour since the last post
now := model.GetMillis()
nt := time.Unix(now/1000, 0).In(timezone)
lt := time.Unix(lastPostAt/1000, 0).In(timezone)
if nt.Sub(lt).Hours() >= 1 && (nt.Day() != lt.Day() || nt.Month() != lt.Month() || nt.Year() != lt.Year()) {
p.PostToDo(c.Ctx, info)
info.LastToDoPostAt = now
if err := p.storeGitlabUserInfo(info); err != nil {
c.Log.WithError(err).Warnf("Can't store user info")
}
}
}
}
p.writeAPIResponse(w, resp)
}
func (p *Plugin) getPrDetails(c *UserContext, w http.ResponseWriter, r *http.Request) {
var prList []*gitlab.PRDetails
if err := json.NewDecoder(r.Body).Decode(&prList); err != nil {
c.Log.WithError(err).Warnf("Error decoding PRDetails JSON body")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("Error decoding PRDetails JSON body. Error: %s", err.Error()), StatusCode: http.StatusBadRequest})
return
}
var result []*gitlab.PRDetails
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetYourPrDetails(c.Ctx, c.Log, info, token, prList)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
c.Log.WithError(err).Warnf("Can't list merge-request details in GitLab API")
msg, code := apiErrorForGitlabError(err, "Can't list merge-request details in GitLab API.")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: msg, StatusCode: code})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) getLHSData(c *UserContext, w http.ResponseWriter, r *http.Request) {
var result *gitlab.LHSContent
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetLHSData(c.Ctx, info, token)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
c.Log.WithError(err).Warnf("Unable to list issue where assignee in GitLab API")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to list issue in GitLab API.", StatusCode: http.StatusInternalServerError})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) createIssue(c *UserContext, w http.ResponseWriter, r *http.Request) {
var issue *gitlab.IssueRequest
if err := json.NewDecoder(r.Body).Decode(&issue); err != nil {
c.Log.WithError(err).Warnf("There was an error while creating the issue")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("There was an error while creating the issue. Error: %s", err.Error()), StatusCode: http.StatusBadRequest})
return
}
var post *model.Post
var appErr *model.AppError
permalink := ""
if issue.PostID != "" {
post, appErr = p.API.GetPost(issue.PostID)
if appErr != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("failed to load post %s", issue.PostID), StatusCode: http.StatusInternalServerError})
return
}
if post == nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("failed to load post %s : not found", issue.PostID), StatusCode: http.StatusNotFound})
return
}
if !p.client.User.HasPermissionToChannel(c.UserID, post.ChannelId, model.PermissionCreatePost) {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized to post in this channel.", StatusCode: http.StatusForbidden})
return
}
permalink = p.getPermalink(issue.PostID)
}
auditRec := plugin.MakeAuditRecord("createIssue", model.AuditStatusFail)
defer p.API.LogAuditRec(auditRec)
auditParams := CreateIssueAuditParams{
MattermostUserID: c.UserID,
ProjectID: issue.ProjectID,
}
model.AddEventParameterAuditableToAuditRec(auditRec, "create_issue", auditParams)
auditRec.Actor.UserId = c.UserID
var result *internGitlab.Issue
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.CreateIssue(c.Ctx, c.GitlabInfo, issue, token)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
auditRec.AddErrorDesc(err.Error())
c.Log.WithError(err).Warnf("can't create issue in GitLab")
msg, code := apiErrorForGitlabError(err, "unable to create issue in GitLab.")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: msg, StatusCode: code})
return
}
auditRec.Success()
auditRec.AddEventResultState(CreateIssueAuditResult{IssueIID: result.IID})
rootID := issue.PostID
channelID := issue.ChannelID
message := fmt.Sprintf("Created GitLab issue [#%v](%v)", result.IID, result.WebURL)
if post != nil {
if post.RootId != "" {
rootID = post.RootId
}
channelID = post.ChannelId
message += fmt.Sprintf(" from a [message](%s)", permalink)
}
reply := &model.Post{
Message: message,
ChannelId: channelID,
RootId: rootID,
UserId: p.BotUserID,
}
if post != nil {
_, appErr = p.API.CreatePost(reply)
} else {
p.API.SendEphemeralPost(c.UserID, reply)
}
if appErr != nil {
c.Log.WithError(appErr).Warnf("failed to create notification post")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("failed to create notification post, postID: %s, channelID: %s", issue.PostID, channelID), StatusCode: http.StatusInternalServerError})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) attachCommentToIssue(c *UserContext, w http.ResponseWriter, r *http.Request) {
var issue *gitlab.IssueRequest
if err := json.NewDecoder(r.Body).Decode(&issue); err != nil {
c.Log.WithError(err).Warnf("There was an error while attaching a comment to the issue")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("There was an error while attaching a comment to the issue. Error: %s", err.Error()), StatusCode: http.StatusBadRequest})
return
}
if err := p.validateCommentBody(issue); err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: err.Error(), StatusCode: http.StatusBadRequest})
return
}
if err := p.validateWebURL(issue.WebURL); err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: err.Error(), StatusCode: http.StatusBadRequest})
return
}
post, appErr := p.API.GetPost(issue.PostID)
if appErr != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("failed to load post %s", issue.PostID), StatusCode: appErr.StatusCode})
return
}
if post == nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("failed to load post %s : not found", issue.PostID), StatusCode: http.StatusNotFound})
return
}
if !p.client.User.HasPermissionToChannel(c.UserID, post.ChannelId, model.PermissionCreatePost) {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized to post in this channel.", StatusCode: http.StatusForbidden})
return
}
commentUsername, apiErr := p.getUsername(post.UserId)
if apiErr != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("failed to get username. Error: %s", apiErr.Message), StatusCode: apiErr.StatusCode})
return
}
permalink := p.getPermalink(issue.PostID)
auditParams := AttachCommentToIssueAuditParams{
MattermostUserID: c.UserID,
ProjectID: issue.ProjectID,
}
auditRec := plugin.MakeAuditRecord("attachCommentToIssue", model.AuditStatusFail)
defer p.API.LogAuditRec(auditRec)
auditRec.Actor.UserId = c.UserID
model.AddEventParameterAuditableToAuditRec(auditRec, "attach_comment_to_issue", auditParams)
var result *internGitlab.Note
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.AttachCommentToIssue(c.Ctx, c.GitlabInfo, issue, permalink, commentUsername, token)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
auditRec.AddErrorDesc(err.Error())
c.Log.WithError(err).Warnf("can't add comment to issue in GitLab")
msg, code := apiErrorForGitlabError(err, "unable to add comment to issue in GitLab.")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: msg, StatusCode: code})
return
}
auditRec.Success()
auditRec.AddEventResultState(AttachCommentToIssueAuditResult{NoteID: result.ID})
rootID := issue.PostID
if post.RootId != "" {
// The original post was a reply
rootID = post.RootId
}
permalinkReplyMessage := fmt.Sprintf("[Message](%s) attached to GitLab issue [#%d](%s)", permalink, issue.IID, issue.WebURL)
reply := &model.Post{
Message: permalinkReplyMessage,
ChannelId: post.ChannelId,
RootId: rootID,
UserId: p.BotUserID,
}
_, appErr = p.API.CreatePost(reply)
if appErr != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("failed to create notification post %s", issue.PostID), StatusCode: appErr.StatusCode})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) validateCommentBody(issue *gitlab.IssueRequest) error {
if issue.PostID == "" {
return errors.Errorf("please provide a valid post id")
}
if issue.IID == 0 {
return errors.Errorf("please provide a valid post iid")
}
if issue.Comment == "" {
return errors.Errorf("please provide a valid non empty comment")
}
return nil
}
func (p *Plugin) validateWebURL(webURL string) error {
config := p.getConfiguration()
configURL, err := url.Parse(config.GitlabURL)
if err != nil {
return errors.Errorf("invalid GitLab URL configuration")
}
parsedURL, err := url.Parse(webURL)
if err != nil || parsedURL.Host == "" {
return errors.Errorf("invalid web_url")
}
if hasInvalidURLChars(webURL) {
return errors.Errorf("invalid web_url")
}
if !strings.EqualFold(parsedURL.Scheme, configURL.Scheme) || !strings.EqualFold(parsedURL.Host, configURL.Host) {
return errors.Errorf("web_url must be a URL under the configured GitLab instance (%s)", config.GitlabURL)
}
configPath := strings.TrimRight(configURL.Path, "/") + "/"
if !strings.HasPrefix(parsedURL.Path, configPath) {
return errors.Errorf("web_url must be a URL under the configured GitLab instance (%s)", config.GitlabURL)
}
return nil
}
func hasInvalidURLChars(rawURL string) bool {
for _, r := range rawURL {
if unicode.IsSpace(r) || unicode.IsControl(r) {
return true
}
switch r {
case '(', ')', '[', ']', '<', '>', '`', '"', '\\':
return true
}
}
return false
}
func (p *Plugin) getPermalink(postID string) string {
return getSiteURL(p.client) + "/" + path.Join("_redirect", "pl", postID)
}
func (p *Plugin) searchIssues(c *UserContext, w http.ResponseWriter, r *http.Request) {
search := r.FormValue(queryParamSearch)
var result []*internGitlab.Issue
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.SearchIssues(c.Ctx, c.GitlabInfo, search, token)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
c.Log.WithError(err).Warnf("unable to search issues in GitLab")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("unable to search issues in GitLab. Error: %s", err.Error()), StatusCode: http.StatusInternalServerError})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) getYourProjects(c *UserContext, w http.ResponseWriter, r *http.Request) {
var result []*internGitlab.Project
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetYourProjects(c.Ctx, c.GitlabInfo, token)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
c.Log.WithError(err).Warnf("can't list projects in GitLab")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to list projects in GitLab.", StatusCode: http.StatusInternalServerError})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) getLabels(c *UserContext, w http.ResponseWriter, r *http.Request) {
projectID := r.URL.Query().Get(queryParamProjectID)
var result []*internGitlab.Label
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetLabels(c.Ctx, c.GitlabInfo, projectID, token)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
c.Log.WithError(err).Warnf("can't list labels of project in GitLab")
msg, code := apiErrorForGitlabError(err, "unable to list labels in GitLab.")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: msg, StatusCode: code})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) getMilestones(c *UserContext, w http.ResponseWriter, r *http.Request) {
projectID := r.URL.Query().Get(queryParamProjectID)
var result []*internGitlab.Milestone
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetMilestones(c.Ctx, c.GitlabInfo, projectID, token)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
c.Log.WithError(err).Warnf("can't list milestones of project in GitLab")
msg, code := apiErrorForGitlabError(err, "unable to list milestones in GitLab.")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: msg, StatusCode: code})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) getAssignees(c *UserContext, w http.ResponseWriter, r *http.Request) {
projectID := r.URL.Query().Get(queryParamProjectID)
var result []*internGitlab.ProjectMember
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
resp, err := p.GitlabClient.GetProjectMembers(c.Ctx, c.GitlabInfo, projectID, token)
if err != nil {
return err
}
result = resp
return nil
})
if err != nil {
c.Log.WithError(err).Warnf("can't list assignees of the project in GitLab")
msg, code := apiErrorForGitlabError(err, "unable to list assignees in GitLab.")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: msg, StatusCode: code})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) postToDo(c *UserContext, w http.ResponseWriter, r *http.Request) {
_, text, err := p.GetToDo(c.Ctx, c.GitlabInfo)
if err != nil {
c.Log.WithError(err).Warnf("Can't get todo")
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an error getting the to do items.", StatusCode: http.StatusUnauthorized})
return
}
if err := p.CreateBotDMPost(c.UserID, text, "custom_git_todo"); err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an error posting the to do items.", StatusCode: http.StatusUnauthorized})
}
p.writeAPIResponse(w, struct{ status string }{status: "OK"})
}
func (p *Plugin) updateSettings(c *UserContext, w http.ResponseWriter, r *http.Request) {
var settings *gitlab.UserSettings
err := json.NewDecoder(r.Body).Decode(&settings)
if settings == nil || err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
info, apiErr := p.getGitlabUserInfoByMattermostID(c.UserID)
if apiErr != nil {
p.writeAPIError(w, apiErr)
return
}
info.Settings = settings
if err := p.storeGitlabUserInfo(info); err != nil {
c.Log.WithError(err).Errorf("can't store GitLab user info when update settings")