-
Notifications
You must be signed in to change notification settings - Fork 323
/
resolver.go
3944 lines (3372 loc) · 125 KB
/
resolver.go
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
package graph
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/marketplacemetering"
"github.com/go-redis/cache/v9"
"go.opentelemetry.io/otel/trace"
"github.com/bwmarrin/discordgo"
github2 "github.com/google/go-github/v50/github"
"github.com/sashabaranov/go-openai"
parse "github.com/highlight-run/highlight/backend/event-parse"
"github.com/highlight-run/highlight/backend/integrations/github"
"github.com/highlight-run/highlight/backend/integrations/gitlab"
"github.com/highlight-run/highlight/backend/integrations/jira"
"gorm.io/gorm/clause"
"github.com/go-chi/chi"
"github.com/samber/lo"
"github.com/highlight-run/go-resthooks"
"github.com/highlight-run/highlight/backend/alerts/integrations/discord"
microsoft_teams "github.com/highlight-run/highlight/backend/alerts/integrations/microsoft-teams"
"github.com/highlight-run/highlight/backend/clickhouse"
"github.com/highlight-run/highlight/backend/clickup"
"github.com/highlight-run/highlight/backend/front"
"github.com/highlight-run/highlight/backend/integrations"
"github.com/highlight-run/highlight/backend/integrations/height"
kafka_queue "github.com/highlight-run/highlight/backend/kafka-queue"
"github.com/highlight-run/highlight/backend/lambda"
"github.com/highlight-run/highlight/backend/oauth"
"github.com/highlight-run/highlight/backend/redis"
"github.com/highlight-run/highlight/backend/stepfunctions"
"github.com/highlight-run/highlight/backend/store"
"github.com/highlight-run/highlight/backend/vercel"
"github.com/pkg/errors"
"gorm.io/gorm"
"github.com/clearbit/clearbit-go/clearbit"
"github.com/golang-jwt/jwt/v4"
"github.com/openlyinc/pointy"
e "github.com/pkg/errors"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
log "github.com/sirupsen/logrus"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/stripe/stripe-go/v78"
"github.com/stripe/stripe-go/v78/client"
"github.com/stripe/stripe-go/v78/webhook"
"github.com/highlight-run/workerpool"
Email "github.com/highlight-run/highlight/backend/email"
"github.com/highlight-run/highlight/backend/embeddings"
"github.com/highlight-run/highlight/backend/model"
"github.com/highlight-run/highlight/backend/pricing"
modelInputs "github.com/highlight-run/highlight/backend/private-graph/graph/model"
"github.com/highlight-run/highlight/backend/storage"
"github.com/highlight-run/highlight/backend/util"
"github.com/highlight/highlight/sdk/highlight-go"
)
// This file will not be regenerated automatically.
//
// It serves as dependency injection for your app, add any dependencies you require here.
const ErrorGroupLookbackDays = 7
const SessionActiveMetricName = "sessionActiveLength"
const SessionProcessedMetricName = "sessionProcessed"
var AuthenticationError = errors.New("401 - AuthenticationError")
var AuthorizationError = errors.New("403 - AuthorizationError")
var (
WhitelistedUID = os.Getenv("WHITELISTED_FIREBASE_ACCOUNT")
JwtAccessSecret = os.Getenv("JWT_ACCESS_SECRET")
FrontendURI = os.Getenv("REACT_APP_FRONTEND_URI")
)
var BytesConversion = map[string]int64{
"b": 1,
"kb": 1024,
"mb": 1024 * 1024,
"gb": 1024 * 1024 * 1024,
"tb": 1024 * 1024 * 1024 * 1024,
"pb": 1024 * 1024 * 1024 * 1024 * 1024,
}
type PromoCode struct {
TrialDays int
ValidUntil time.Time
}
var PromoCodes = map[string]PromoCode{
"WEBDEVSIMPLIFIED": {
TrialDays: 60,
ValidUntil: time.Date(2023, time.May, 15, 0, 0, 0, 0, time.UTC),
},
"CATCHMYERRORS": {
TrialDays: 7,
ValidUntil: time.Date(2023, time.January, 17, 0, 0, 0, 0, time.UTC),
},
"SIMPLIFIEDHIGHLIGHT": {
TrialDays: 60,
ValidUntil: time.Date(2023, time.August, 7, 0, 0, 0, 0, time.UTC),
},
"USEGOLANG": {
TrialDays: 14,
ValidUntil: time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC),
},
}
func isAuthError(err error) bool {
return e.Is(err, AuthenticationError) || e.Is(err, AuthorizationError)
}
type Resolver struct {
DB *gorm.DB
Tracer trace.Tracer
MailClient *sendgrid.Client
StripeClient *client.API
AWSMPClient *marketplacemetering.Client
StorageClient storage.Client
LambdaClient *lambda.Client
ClearbitClient *clearbit.Client
PrivateWorkerPool *workerpool.WorkerPool
SubscriptionWorkerPool *workerpool.WorkerPool
RH *resthooks.Resthook
Redis *redis.Client
StepFunctions *stepfunctions.Client
OAuthServer *oauth.Server
IntegrationsClient *integrations.Client
ClickhouseClient *clickhouse.Client
Store *store.Store
DataSyncQueue kafka_queue.MessageQueue
TracesQueue kafka_queue.MessageQueue
EmbeddingsClient embeddings.Client
}
func (r *mutationResolver) Transaction(body func(txnR *mutationResolver) error) error {
return r.DB.Transaction(func(tx *gorm.DB) error {
transactionR := *r
embedded := *transactionR.Resolver
transactionR.Resolver = &embedded
transactionR.Resolver.DB = tx
return body(&transactionR)
})
}
func (r *Resolver) createAdmin(ctx context.Context) (*model.Admin, error) {
adminUID := pointy.String(fmt.Sprintf("%v", ctx.Value(model.ContextKeys.UID)))
firebaseSpan, spanCtx := util.StartSpanFromContext(ctx, "db.createAdminFromFirebase", util.ResourceName("resolver.createAdmin"),
util.Tag("admin_uid", adminUID))
firebaseUser, err := AuthClient.GetUser(spanCtx, *adminUID)
if err != nil {
spanError := e.Wrap(err, "error retrieving user from firebase api")
firebaseSpan.Finish(spanError)
return nil, spanError
}
firebaseSpan.Finish()
adminSpan, _ := util.StartSpanFromContext(ctx, "db.admin", util.ResourceName("resolver.createAdmin"))
admin := &model.Admin{
UID: adminUID,
Name: &firebaseUser.DisplayName,
Email: &firebaseUser.Email,
PhotoURL: &firebaseUser.PhotoURL,
EmailVerified: &firebaseUser.EmailVerified,
Phone: &firebaseUser.PhoneNumber,
AboutYouDetailsFilled: &model.F,
}
tx := r.DB.WithContext(ctx).Where(&model.Admin{UID: admin.UID}).
Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "uid"}}, DoNothing: true}).
Create(&admin).
Attrs(&admin)
if tx.Error != nil {
spanError := e.Wrap(tx.Error, "error retrieving user from db")
adminSpan.Finish(spanError)
return nil, spanError
}
adminSpan.Finish()
return admin, nil
}
func (r *Resolver) getCurrentAdmin(ctx context.Context) (*model.Admin, error) {
admin, err := r.Query().Admin(ctx)
if err != nil {
return nil, AuthenticationError
}
return admin, nil
}
func (r *Resolver) getCustomVerifiedAdminEmailDomain(admin *model.Admin) (string, error) {
domain, err := r.getVerifiedAdminEmailDomain(admin)
if err != nil {
return "", e.Wrap(err, "error getting verified admin email domain")
}
// this is just the top 10 email domains as of June 6, 2016, and protonmail.com
if map[string]bool{"gmail.com": true, "yahoo.com": true, "hotmail.com": true, "aol.com": true, "hotmail.co.uk": true, "protonmail.com": true, "hotmail.fr": true, "msn.com": true, "yahoo.fr": true, "wanadoo.fr": true, "orange.fr": true}[strings.ToLower(domain)] {
return "", nil
}
return domain, nil
}
func (r *Resolver) getVerifiedAdminEmailDomain(admin *model.Admin) (string, error) {
if admin.EmailVerified == nil || !*admin.EmailVerified {
return "", e.New("admin email is not verified")
}
if admin.Email == nil {
return "", e.New("admin email is nil")
}
components := strings.Split(*admin.Email, "@")
if len(components) < 2 {
return "", e.New("invalid admin email")
}
domain := components[1]
return domain, nil
}
func (r *Resolver) getTaggedAdmins(taggedAdmins []*modelInputs.SanitizedAdminInput, isGuestCreatingSession bool) (admins []model.Admin) {
if !isGuestCreatingSession {
for _, a := range taggedAdmins {
admins = append(admins,
model.Admin{
Model: model.Model{ID: a.ID},
},
)
}
}
return
}
func (r *Resolver) formatSanitizedAuthor(admin *model.Admin) *modelInputs.SanitizedAdmin {
name := ""
email := ""
photo_url := ""
if admin.Name != nil {
name = *admin.Name
}
if admin.Email != nil {
email = *admin.Email
}
if admin.PhotoURL != nil {
photo_url = *admin.PhotoURL
}
sanitizedAdmin := &modelInputs.SanitizedAdmin{
ID: admin.ID,
Name: &name,
Email: email,
PhotoURL: &photo_url,
}
return sanitizedAdmin
}
func (r *Resolver) isWhitelistedAccount(ctx context.Context) bool {
uid := fmt.Sprintf("%v", ctx.Value(model.ContextKeys.UID))
email := fmt.Sprintf("%v", ctx.Value(model.ContextKeys.Email))
// Allow access to engineering@highlight.run or any verified @highlight.run / @runhighlight.com email.
_, isHighlightAdmin := lo.Find(HighlightAdminEmailDomains, func(domain string) bool { return strings.Contains(email, domain) })
return !util.IsInDocker() && isHighlightAdmin || uid == WhitelistedUID
}
func (r *Resolver) isDemoProject(ctx context.Context, project_id int) bool {
return project_id == r.demoProjectID(ctx)
}
func (r *Resolver) isDemoWorkspace(workspace_id int) bool {
return workspace_id == 0
}
func (r *Resolver) demoProjectID(ctx context.Context) int {
demoProjectString := os.Getenv("DEMO_PROJECT_ID")
// Demo project is disabled if the env var is not set.
if demoProjectString == "" {
return 0
}
if demoProjectID, err := strconv.Atoi(demoProjectString); err != nil {
log.WithContext(ctx).Error(err, "error converting DemoProjectID to int")
return 0
} else {
return demoProjectID
}
}
// These are authentication methods used to make sure that data is secured.
// This'll probably get expensive at some point; they can probably be cached.
// isAdminInProjectOrDemoProject should be used for actions that you want admins in all projects
// and laymen in the demo project to have access to.
func (r *Resolver) isAdminInProjectOrDemoProject(ctx context.Context, project_id int) (*model.Project, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "isAdminInProjectOrDemoProject", util.ResourceName("resolver.internal.auth"))
log.WithContext(ctx).WithField("project_id", project_id).Info("checking if admin is in project or demo workspace")
defer authSpan.Finish()
start := time.Now()
defer func() {
highlight.RecordMetric(
ctx, "resolver.internal.auth.isAdminInProjectOrDemoProject", time.Since(start).Seconds(),
)
}()
var project *model.Project
var err error
if r.isDemoProject(ctx, project_id) {
if err = r.DB.WithContext(ctx).Model(&model.Project{}).Where("id = ?", r.demoProjectID(ctx)).Take(&project).Error; err != nil {
return nil, e.Wrap(err, "error querying demo project")
}
} else {
project, err = r.isAdminInProject(ctx, project_id)
if err != nil {
return nil, err
}
}
return project, nil
}
func (r *Resolver) isAdminInWorkspaceOrDemoWorkspace(ctx context.Context, workspace_id int) (*model.Workspace, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "isAdminInWorkspaceOrDemoWorkspace", util.ResourceName("resolver.internal.auth"))
log.WithContext(ctx).WithField("workspace_id", workspace_id).Info("checking if admin is in workspace or demo workspace")
defer authSpan.Finish()
start := time.Now()
defer func() {
highlight.RecordMetric(
ctx, "resolver.internal.auth.isAdminInWorkspaceOrDemoWorkspace", time.Since(start).Seconds(),
)
}()
var workspace *model.Workspace
var err error
if r.isDemoWorkspace(workspace_id) {
if err = r.DB.WithContext(ctx).Model(&model.Workspace{}).Where("id = ?", 0).Take(&workspace).Error; err != nil {
return nil, e.Wrap(err, "error querying demo workspace")
}
} else {
workspace, err = r.isAdminInWorkspace(ctx, workspace_id)
if err != nil {
return nil, err
}
}
return workspace, nil
}
func (r *Resolver) GetWorkspace(workspaceID int) (*model.Workspace, error) {
var workspace model.Workspace
if err := r.DB.WithContext(context.TODO()).Where(&model.Workspace{Model: model.Model{ID: workspaceID}}).Take(&workspace).Error; err != nil {
return nil, e.Wrap(err, "error querying workspace")
}
return &workspace, nil
}
func (r *Resolver) GetAWSMarketPlaceWorkspace(ctx context.Context, workspaceID int) (*model.Workspace, error) {
var workspace model.Workspace
if err := r.DB.WithContext(ctx).
Model(&workspace).
Joins("AWSMarketplaceCustomer").
Where(&model.Workspace{Model: model.Model{ID: workspaceID}}).
Take(&workspace).
Error; err != nil {
return nil, err
}
return &workspace, nil
}
func (r *Resolver) GetAdminRole(ctx context.Context, adminID int, workspaceID int) (string, error) {
var workspaceAdmin model.WorkspaceAdmin
if err := r.DB.WithContext(ctx).Where(&model.WorkspaceAdmin{AdminID: adminID, WorkspaceID: workspaceID}).Take(&workspaceAdmin).Error; err != nil {
return "", e.Wrap(err, "error querying workspace_admin")
}
if workspaceAdmin.Role == nil || *workspaceAdmin.Role == "" {
log.WithContext(ctx).Errorf("workspace_admin admin_id:%d,workspace_id:%d has invalid role", adminID, workspaceID)
return "", e.New("workspace_admin has invalid role")
}
return *workspaceAdmin.Role, nil
}
func (r *Resolver) addAdminMembership(ctx context.Context, workspaceId int, inviteID string) (*int, error) {
workspace := &model.Workspace{}
if err := r.DB.WithContext(ctx).Model(workspace).Where("id = ?", workspaceId).Take(workspace).Error; err != nil {
return nil, e.Wrap(err, "500: error querying workspace")
}
admin, err := r.getCurrentAdmin(ctx)
if err != nil {
return nil, err
}
inviteLink := &model.WorkspaceInviteLink{}
if err := r.DB.WithContext(ctx).Where(&model.WorkspaceInviteLink{WorkspaceID: &workspaceId, Secret: &inviteID}).Take(&inviteLink).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, e.New("404: Invite not found")
}
return nil, e.Wrap(err, "500: error querying for invite Link")
}
// Non-admin specific invites don't have a specific invitee. Only block if the invite is for a specific admin and the emails don't match.
if inviteLink.InviteeEmail != nil {
// check case-insensitively because email addresses are case-insensitive.
if !strings.EqualFold(*inviteLink.InviteeEmail, *admin.Email) {
return nil, AuthorizationError
}
}
if r.IsInviteLinkExpired(inviteLink) {
if err := r.DB.Delete(inviteLink).Error; err != nil {
return nil, e.Wrap(err, "500: error while trying to delete expired invite link")
}
return nil, e.New("405: This invite link has expired.")
}
if err := r.DB.Clauses(clause.OnConflict{
OnConstraint: "workspace_admins_pkey",
DoNothing: true,
}).Create(&model.WorkspaceAdmin{
AdminID: admin.ID,
WorkspaceID: workspace.ID,
Role: inviteLink.InviteeRole,
}).Error; err != nil {
return nil, e.Wrap(err, "500: error adding admin to association")
}
// Only delete the invite for specific-admin invites. Specific-admin invites are 1-time use only.
// Non-admin specific invites are multi-use and only have an expiration date.
if inviteLink.InviteeEmail != nil {
if err := r.DB.Delete(inviteLink).Error; err != nil {
return nil, e.Wrap(err, "500: error while trying to delete used invite link")
}
}
return &admin.ID, nil
}
func (r *Resolver) DeleteAdminAssociation(ctx context.Context, obj interface{}, adminID int) (*int, error) {
admin, err := r.getCurrentAdmin(ctx)
if err != nil {
return nil, err
}
if admin.ID == adminID {
return nil, e.New("Admin tried deleting their own association")
}
if err := r.DB.WithContext(ctx).Model(obj).Association("Admins").Delete(model.Admin{Model: model.Model{ID: adminID}}); err != nil {
return nil, e.Wrap(err, "error deleting admin association")
}
return &adminID, nil
}
func (r *Resolver) isAdminInWorkspace(ctx context.Context, workspaceID int) (*model.Workspace, error) {
span, ctx := util.StartSpanFromContext(ctx, "isAdminInWorkspace", util.ResourceName("resolver.internal.auth"))
defer span.Finish()
span.SetAttribute("WorkspaceID", workspaceID)
if r.isWhitelistedAccount(ctx) {
return r.GetWorkspace(workspaceID)
}
admin, err := r.getCurrentAdmin(ctx)
if err != nil {
return nil, err
}
span.SetAttribute("AdminID", admin.ID)
workspace := model.Workspace{}
if err := r.DB.Order("name asc").
Where(&model.Workspace{Model: model.Model{ID: workspaceID}}).
Model(&admin).Association("Workspaces").Find(&workspace); err != nil {
return nil, e.Wrap(err, "error getting associated workspaces")
}
if workspaceID != workspace.ID {
return nil, AuthorizationError
}
return &workspace, nil
}
// isAdminInProject should be used for actions that you only want admins in all projects to have access to.
// Use this on actions that you don't want laymen in the demo project to have access to.
func (r *Resolver) isAdminInProject(ctx context.Context, project_id int) (*model.Project, error) {
span, ctx := util.StartSpanFromContext(ctx, "isAdminInProject", util.ResourceName("resolver.internal.auth"))
defer span.Finish()
span.SetAttribute("ProjectID", project_id)
if r.isWhitelistedAccount(ctx) {
project := &model.Project{}
if err := r.DB.WithContext(ctx).Where(&model.Project{Model: model.Model{ID: project_id}}).Take(&project).Error; err != nil {
return nil, e.Wrap(err, "error querying project")
}
return project, nil
}
projects, err := r.Query().Projects(ctx)
if err != nil {
return nil, e.Wrap(err, "error querying projects")
}
if len(projects) == 0 {
return nil, AuthenticationError
}
for _, p := range projects {
if p.ID == project_id {
span.SetAttribute("WorkspaceID", p.WorkspaceID)
return p, nil
}
}
return nil, AuthorizationError
}
func (r *Resolver) SetErrorFrequenciesClickhouse(ctx context.Context, projectID int, errorGroups []*model.ErrorGroup, lookbackPeriod int) error {
params := modelInputs.ErrorGroupFrequenciesParamsInput{
DateRange: &modelInputs.DateRangeRequiredInput{
StartDate: time.Now().Add(time.Duration(-24*lookbackPeriod) * time.Hour),
EndDate: time.Now(),
},
ResolutionMinutes: 24 * 60,
}
errorGroupsById := map[int]*model.ErrorGroup{}
for _, errorGroup := range errorGroups {
errorGroup.ErrorMetrics = []*modelInputs.ErrorDistributionItem{}
errorGroup.ErrorFrequency = []int64{}
errorGroupsById[errorGroup.ID] = errorGroup
}
frequencies, err := r.ClickhouseClient.QueryErrorGroupFrequencies(ctx, projectID, lo.Keys(errorGroupsById), params)
if err != nil {
return err
}
aggregates, err := r.ClickhouseClient.QueryErrorGroupAggregateFrequency(ctx, projectID, lo.Keys(errorGroupsById))
if err != nil {
return err
}
allMetrics := append(frequencies, aggregates...)
for _, r := range allMetrics {
eg := errorGroupsById[r.ErrorGroupID]
if eg == nil {
continue
}
if r.Name == "count" {
eg.ErrorFrequency = append(eg.ErrorFrequency, r.Value)
}
eg.ErrorMetrics = append(eg.ErrorMetrics, &modelInputs.ErrorDistributionItem{ErrorGroupID: eg.ID, Date: r.Date, Name: r.Name, Value: r.Value})
}
return nil
}
type SavedSegmentParams struct {
Query string
}
func SavedSegmentQueryToParams(query string) *SavedSegmentParams {
modelParams := &SavedSegmentParams{
Query: query,
}
return modelParams
}
func (r *Resolver) doesAdminOwnErrorGroup(ctx context.Context, errorGroupSecureID string) (*model.ErrorGroup, bool, error) {
eg := &model.ErrorGroup{}
if err := r.DB.Joins("ErrorTag").Where(&model.ErrorGroup{SecureID: errorGroupSecureID}).Take(&eg).Error; err != nil {
return nil, false, e.Wrap(err, "error querying error group by secureID: "+errorGroupSecureID)
}
_, err := r.isAdminInProjectOrDemoProject(ctx, eg.ProjectID)
if err != nil {
return eg, false, err
}
return eg, true, nil
}
func (r *Resolver) loadErrorGroupFrequenciesClickhouse(ctx context.Context, eg *model.ErrorGroup) error {
var err error
if eg.FirstOccurrence, eg.LastOccurrence, err = r.ClickhouseClient.QueryErrorGroupOccurrences(ctx, eg.ProjectID, eg.ID); err != nil {
return e.Wrap(err, "error querying error group occurrences")
}
if err := r.SetErrorFrequenciesClickhouse(ctx, eg.ProjectID, []*model.ErrorGroup{eg}, 30); err != nil {
return e.Wrap(err, "error querying error group frequencies")
}
return nil
}
func (r *Resolver) canAdminViewErrorObject(ctx context.Context, errorObjectID int) (*model.ErrorObject, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "canAdminViewErrorObject", util.ResourceName("resolver.internal.auth"))
defer authSpan.Finish()
errorObject := model.ErrorObject{}
if err := r.DB.WithContext(ctx).Where(&model.ErrorObject{ID: errorObjectID}).
Preload("ErrorGroup").
Take(&errorObject).Error; err != nil {
return nil, err
}
if _, err := r.canAdminViewErrorGroup(ctx, errorObject.ErrorGroup.SecureID); err != nil {
return nil, err
}
return &errorObject, nil
}
func (r *Resolver) canAdminViewErrorGroup(ctx context.Context, errorGroupSecureID string) (*model.ErrorGroup, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "canAdminViewErrorGroup", util.ResourceName("resolver.internal.auth"))
defer authSpan.Finish()
errorGroup, isOwner, err := r.doesAdminOwnErrorGroup(ctx, errorGroupSecureID)
if err == nil && isOwner {
return errorGroup, nil
}
if errorGroup != nil && errorGroup.IsPublic {
return errorGroup, nil
}
return nil, err
}
func (r *Resolver) canAdminModifyErrorGroup(ctx context.Context, errorGroupSecureID string) (*model.ErrorGroup, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "canAdminModifyErrorGroup", util.ResourceName("resolver.internal.auth"))
defer authSpan.Finish()
errorGroup, isOwner, err := r.doesAdminOwnErrorGroup(ctx, errorGroupSecureID)
if err == nil && isOwner {
return errorGroup, nil
}
return nil, err
}
func (r *Resolver) _doesAdminOwnSession(ctx context.Context, sessionSecureId string) (session *model.Session, ownsSession bool, err error) {
if session, err = r.Store.GetSessionFromSecureID(ctx, sessionSecureId); err != nil {
return nil, false, AuthorizationError
}
_, err = r.isAdminInProjectOrDemoProject(ctx, session.ProjectID)
if err != nil {
return session, false, err
}
return session, true, nil
}
func (r *Resolver) canAdminViewSession(ctx context.Context, session_secure_id string) (*model.Session, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "canAdminViewSession", util.ResourceName("resolver.internal.auth"))
defer authSpan.Finish()
session, isOwner, err := r._doesAdminOwnSession(ctx, session_secure_id)
if err != nil {
if !isAuthError(err) {
return nil, err
} else {
if session == nil {
return nil, AuthorizationError
}
// auth error, but we should check if this is demo / public session
}
}
if isOwner {
return session, nil
} else if session.IsPublic {
return session, nil
} else if session.ProjectID == r.demoProjectID(ctx) {
return session, nil
}
return nil, AuthorizationError
}
func (r *Resolver) canAdminModifySession(ctx context.Context, session_secure_id string) (*model.Session, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "canAdminModifySession", util.ResourceName("resolver.internal.auth"))
defer authSpan.Finish()
session, isOwner, err := r._doesAdminOwnSession(ctx, session_secure_id)
if err == nil && isOwner {
return session, nil
}
return nil, err
}
func (r *Resolver) isAdminSegmentOwner(ctx context.Context, segment_id int) (*model.Segment, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "isAdminSegmentOwner", util.ResourceName("resolver.internal.auth"))
defer authSpan.Finish()
segment := &model.Segment{}
if err := r.DB.WithContext(ctx).Where("id = ?", segment_id).Take(&segment).Error; err != nil {
return nil, e.Wrap(err, "error querying segment")
}
_, err := r.isAdminInProjectOrDemoProject(ctx, segment.ProjectID)
if err != nil {
return nil, err
}
return segment, nil
}
func (r *Resolver) isAdminSavedSegmentOwner(ctx context.Context, segment_id int) (*model.SavedSegment, error) {
authSpan, ctx := util.StartSpanFromContext(ctx, "isAdminSavedSegmentOwner", util.ResourceName("resolver.internal.auth"))
defer authSpan.Finish()
segment := &model.SavedSegment{}
if err := r.DB.WithContext(ctx).Where("id = ?", segment_id).Take(&segment).Error; err != nil {
return nil, err
}
_, err := r.isAdminInProjectOrDemoProject(ctx, segment.ProjectID)
if err != nil {
return nil, err
}
return segment, nil
}
func (r *Resolver) SendEmailAlert(
tos []*mail.Email,
ccs []*mail.Email,
authorName string,
viewLink string,
muteLink string,
subjectScope string,
textForEmail string,
templateID string,
sessionImage *string,
asmGroupId *int,
) error {
m := mail.NewV3Mail()
from := mail.NewEmail("Highlight", Email.SendGridOutboundEmail)
m.SetFrom(from)
m.SetTemplateID(templateID)
p := mail.NewPersonalization()
p.AddTos(tos...)
p.AddCCs(ccs...)
p.SetDynamicTemplateData("Author_Name", authorName)
p.SetDynamicTemplateData("Comment_Link", viewLink)
p.SetDynamicTemplateData("Comment_Body", textForEmail)
p.SetDynamicTemplateData("Mute_Thread", muteLink)
p.SetDynamicTemplateData("Subject_Scope", subjectScope)
if sessionImage != nil && *sessionImage != "" {
p.SetDynamicTemplateData("Session_Image", sessionImage)
a := mail.NewAttachment()
a.SetContent(*sessionImage)
a.SetFilename("session-image.png")
a.SetContentID("sessionImage")
a.SetType("image/png")
m.AddAttachment(a)
}
m.AddPersonalizations(p)
if asmGroupId != nil {
asm := mail.NewASM()
asm.SetGroupID(*asmGroupId)
m.SetASM(asm)
}
response, err := r.MailClient.Send(m)
if err != nil {
return e.Wrap(err, "error sending sendgrid email for comments mentions")
}
if response.StatusCode == 400 {
return e.Wrap(errors.New(response.Body), "bad request")
}
return nil
}
func (r *Resolver) CreateSlackBlocks(admin *model.Admin, viewLink, commentText, action string, subjectScope string, additionalContext *string) ([]slack.Block, *slack.Attachment) {
determiner := "a"
if subjectScope == "error" {
determiner = "an"
}
// Header
var headerBlockSet []slack.Block
message := fmt.Sprintf("*You were %s in %s %s comment.*", action, determiner, subjectScope)
if admin.Email != nil && *admin.Email != "" {
message = fmt.Sprintf("*%s %s you in %s %s comment.*", *admin.Email, action, determiner, subjectScope)
}
if admin.Name != nil && *admin.Name != "" {
message = fmt.Sprintf("*%s %s you in %s %s comment.*", *admin.Name, action, determiner, subjectScope)
}
headerBlock := slack.NewTextBlockObject(slack.MarkdownType, message, false, false)
headerBlockSet = append(headerBlockSet, slack.NewSectionBlock(headerBlock, nil, nil))
// comment message
var bodyBlockSet []slack.Block
commentBlock := slack.NewTextBlockObject(slack.MarkdownType, fmt.Sprintf("> %s", commentText), false, false)
detailsString := ""
// info on the session/error
if subjectScope == "error" {
detailsString = fmt.Sprintf("*Error* %s", viewLink)
} else if subjectScope == "session" {
detailsString = fmt.Sprintf("*Session* %s", viewLink)
}
if additionalContext != nil {
detailsString = fmt.Sprintf("%s\n%s", detailsString, *additionalContext)
}
detailsBlock := slack.NewTextBlockObject(slack.MarkdownType, detailsString, false, false)
// button
var actionBlocks []slack.BlockElement
button := slack.NewButtonBlockElement(
"",
"click",
slack.NewTextBlockObject(
slack.PlainTextType,
"View comment",
false,
false,
),
)
button.URL = viewLink
actionBlocks = append(actionBlocks, button)
bodyBlockSet = append(bodyBlockSet, slack.NewSectionBlock(commentBlock, nil, nil))
bodyBlockSet = append(bodyBlockSet, slack.NewSectionBlock(detailsBlock, nil, nil))
bodyBlockSet = append(bodyBlockSet, slack.NewActionBlock("", actionBlocks...))
attachment := &slack.Attachment{
Color: "#6c37f4",
Blocks: slack.Blocks{BlockSet: bodyBlockSet},
}
return headerBlockSet, attachment
}
func (r *Resolver) SendSlackThreadReply(ctx context.Context, workspace *model.Workspace, admin *model.Admin, viewLink, commentText, action string, subjectScope string, threadIDs []int) error {
if workspace.SlackAccessToken == nil {
return nil
}
slackClient := slack.New(*workspace.SlackAccessToken)
headerBlock, bodyAttachment := r.CreateSlackBlocks(admin, viewLink, commentText, action, subjectScope, nil)
for _, threadID := range threadIDs {
thread := &model.CommentSlackThread{}
if err := r.DB.WithContext(ctx).Where(&model.CommentSlackThread{Model: model.Model{ID: threadID}}).Take(&thread).Error; err != nil {
return e.Wrap(err, "error querying slack thread")
}
opts := []slack.MsgOption{
slack.MsgOptionBlocks(headerBlock...),
slack.MsgOptionAttachments(*bodyAttachment),
slack.MsgOptionDisableLinkUnfurl(), /** Disables showing a preview of any links that are in the Slack message.*/
slack.MsgOptionDisableMediaUnfurl(), /** Disables showing a preview of any media that are in the Slack message.*/
slack.MsgOptionTS(thread.ThreadTS),
}
_, _, err := slackClient.PostMessage(thread.SlackChannelID, opts...)
if err != nil {
log.WithContext(ctx).Error(err)
}
}
return nil
}
func (r *Resolver) SendSlackAlertToUser(ctx context.Context, workspace *model.Workspace, admin *model.Admin, taggedSlackUsers []*modelInputs.SanitizedSlackChannelInput, viewLink, commentText, action string, subjectScope string, base64Image *string, sessionCommentID *int, errorCommentID *int, additionalContext *string) error {
// this is needed for posting DMs
// if nil, user simply hasn't signed up for notifications, so return nil
if workspace.SlackAccessToken == nil {
return nil
}
slackClient := slack.New(*workspace.SlackAccessToken)
headerBlock, bodyAttachment := r.CreateSlackBlocks(admin, viewLink, commentText, action, subjectScope, additionalContext)
// Prepare to upload the screenshot to the user's Slack workspace.
// We do this instead of upload it to S3 or somewhere else to defer authorization checks to Slack.
// If we upload the image somewhere public, anyone with the link to the image will have access. The image could contain sensitive information.
// By uploading to the user's Slack workspace, we limit the authorization of the image to only Slack members of the user's workspace.
var uploadedFileKey string
if base64Image != nil {
// This key will be used as the file name for the file written to disk.
// This needs to be unique. The uniqueness is guaranteed by the project ID, the admin who created the comment's ID, and the current time
uploadedFileKey = fmt.Sprintf("slack-image-%d-%d-%d.png", workspace.ID, admin.ID, time.Now().UnixNano())
// We are writing the base64 string to disk as a png. We need to do this because the Slack Go client
// doesn't support uploading files as base64.
// This is something we'll need to revisit when we start getting larger traffic for comments.
// The reason for this is each task has disk space of 20GB, each image is around 200 KB. Ideally we do everything in memory without relying on disk.
dec, err := base64.StdEncoding.DecodeString(*base64Image)
if err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "Failed to decode base64 image"))
}
f, err := os.Create(uploadedFileKey)
if err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "Failed to create file on disk"))
}
defer f.Close()
if _, err := f.Write(dec); err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "Failed to write file on disk"))
}
if err := f.Sync(); err != nil {
log.WithContext(ctx).Error("Failed to sync file on disk")
}
}
for _, slackUser := range taggedSlackUsers {
if slackUser.WebhookChannelID != nil {
_, _, _, err := slackClient.JoinConversation(*slackUser.WebhookChannelID)
if err != nil {
log.WithContext(ctx).Warn(e.Wrap(err, "failed to join slack channel"))
}
opts := []slack.MsgOption{
slack.MsgOptionBlocks(headerBlock...),
slack.MsgOptionAttachments(*bodyAttachment),
slack.MsgOptionDisableLinkUnfurl(), /** Disables showing a preview of any links that are in the Slack message.*/
slack.MsgOptionDisableMediaUnfurl(), /** Disables showing a preview of any media that are in the Slack message.*/
}
_, respTs, err := slackClient.PostMessage(*slackUser.WebhookChannelID, opts...)
if err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "error posting slack message via slack bot"))
} else {
thread := &model.CommentSlackThread{
SlackChannelID: *slackUser.WebhookChannelID,
ThreadTS: respTs,
}
if sessionCommentID != nil {
thread.SessionCommentID = *sessionCommentID
} else if errorCommentID != nil {
thread.ErrorCommentID = *errorCommentID
}
r.DB.WithContext(ctx).Create(thread)
}
if uploadedFileKey != "" {
// We need to write the base64 image to disk, read the file, then upload it to Slack.
// We can't send Slack a base64 string.
fileUploadParams := slack.FileUploadParameters{
Filetype: "image/png",
Filename: fmt.Sprintf("Highlight %s Image.png", subjectScope),
// These are the channels that will have access to the uploaded file.
Channels: []string{*slackUser.WebhookChannelID},
File: uploadedFileKey,
Title: fmt.Sprintf("File from Highlight uploaded on behalf of %s", *admin.Name),
// include the image in the initial comment's thread
ThreadTimestamp: respTs,
}
_, err = slackClient.UploadFile(fileUploadParams)
if err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "failed to upload file to Slack"))
}
}
}
}
if uploadedFileKey != "" {
if err := os.Remove(uploadedFileKey); err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "Failed to remove temporary session screenshot"))
}
}
return nil
}
// GetSessionChunk Given a session and session-relative timestamp, finds the chunk and chunk-relative timestamp.
func (r *Resolver) GetSessionChunk(ctx context.Context, sessionID int, ts int) (chunkIdx int, chunkTs int) {
chunkTs = ts
var chunks []*model.EventChunk
if err := r.DB.Order("chunk_index ASC").Model(&model.EventChunk{}).Where(&model.EventChunk{SessionID: sessionID}).
Scan(&chunks).Error; err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "error retrieving event chunks from DB"))
return
}
if len(chunks) > 1 {
t := chunks[0].Timestamp
absTime := t + int64(ts)
for i, chunk := range chunks[1:] {
if chunk.Timestamp > absTime {
break
}
chunkIdx = i + 1
t = chunk.Timestamp
}
chunkTs = int(absTime - t)
}
return