forked from Shuffle/shuffle-shared
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifications.go
executable file
·1152 lines (972 loc) · 35.4 KB
/
notifications.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 shuffle
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/satori/go.uuid"
"crypto/sha256"
"encoding/hex"
"io/ioutil"
"strconv"
"log"
"net/http"
"os"
"sort"
"strings"
"time"
)
// Standalone to make it work many places
func markNotificationRead(ctx context.Context, notification *Notification) error {
notification.Read = true
err := SetNotification(ctx, *notification)
if err != nil {
return err
}
return nil
}
func HandleMarkAsRead(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
var fileId string
location := strings.Split(request.URL.String(), "/")
if location[1] == "api" {
if len(location) <= 4 {
log.Printf("Path too short: %d", len(location))
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
log.Printf("[WARNING] Bad format for fileId in notification %s", fileId)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Badly formatted ID"}`))
return
}
// 1. Check user directly
// 2. Check workflow execution authorization
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[INFO] INITIAL Api authentication failed in notification mark: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
ctx := GetContext(request)
notification, err := GetNotification(ctx, fileId)
if err != nil {
log.Printf("[WARNING] Failed getting notification %s for user %s: %s", fileId, user.Id, err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false, "reason": "Bad userId or notification doesn't exist"}`))
return
}
if notification.Personal && notification.UserId != user.Id {
log.Printf("[WARNING] Bad user for notification. %s (wanted) vs %s", notification.UserId, user.Id)
resp.WriteHeader(403)
resp.Write([]byte(`{"success": false, "reason": "Bad userId or notification doesn't exist"}`))
return
}
if notification.OrgId != user.ActiveOrg.Id {
log.Printf("[WARNING] Bad org for notification. %s (wanted) vs %s", notification.OrgId, user.ActiveOrg.Id)
resp.WriteHeader(403)
resp.Write([]byte(`{"success": false, "reason": "Bad userId or notification doesn't exist"}`))
return
}
notification.ModifiedBy = user.Username
// Look for the "disabled" query in the url
if request.URL.Query().Get("disabled") == "true" {
notification.Ignored = true
//log.Printf("[AUDIT] Marked %s as ignored by user %s (%s)", notification.Id, user.Username, user.Id)
} else if request.URL.Query().Get("disabled") == "false" {
notification.Ignored = false
}
err = markNotificationRead(ctx, notification)
if err != nil {
log.Printf("[WARNING] Failed updating notification %s (%s) to read: %s", notification.Title, notification.Id, err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false, "reason": "Failed to mark it as read"}`))
return
}
log.Printf("[AUDIT] Marked %s as read by user %s (%s)", notification.Id, user.Username, user.Id)
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true}`))
return
}
func HandleClearNotifications(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
// 1. Check user directly
// 2. Check workflow execution authorization
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[INFO] INITIAL Api authentication failed in notification list: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
/*
if user.Role != "admin" {
log.Printf("[AUTH] User isn't admin")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Need to be admin to list files"}`)))
return
}
*/
ctx := GetContext(request)
//notifications, err := GetUserNotifications(ctx, user.Id)
notifications, err := GetOrgNotifications(ctx, user.ActiveOrg.Id)
if err != nil && len(notifications) == 0 {
log.Printf("[ERROR] Failed to get notifications (clear): %s", err)
resp.WriteHeader(500)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Error getting notifications."}`)))
return
}
for _, notification := range notifications {
// Not including this as we want to mark as read for all users in the org
// We stopped using personal vs org notifications
// Also added index to track by updated time
//if user.Id != notification.UserId {
// continue
//}
notification.ModifiedBy = user.Username
err = markNotificationRead(ctx, ¬ification)
if err != nil {
log.Printf("[WARNING] Failed updating notification %s (%s) to read (clear): %s", notification.Title, notification.Id, err)
continue
}
}
log.Printf("[AUDIT] Cleared %d notifications for user %s (%s) in org %s (%s)", len(notifications), user.Username, user.Id, user.ActiveOrg.Name, user.ActiveOrg.Id)
cacheKey := fmt.Sprintf("notifications_%s", user.ActiveOrg.Id)
DeleteCache(ctx, cacheKey)
cacheKey = fmt.Sprintf("notifications_%s", user.Id)
DeleteCache(ctx, cacheKey)
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true}`))
}
func HandleGetNotifications(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
// 1. Check user directly
// 2. Check workflow execution authorization
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[INFO] INITIAL Api authentication failed in notification list: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
/*
if user.Role != "admin" {
log.Printf("[AUTH] User isn't admin")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Need to be admin to list files"}`)))
return
}
*/
// Should be made org-wide instead? Right now, it's cross org
ctx := GetContext(request)
//notifications, err := GetUserNotifications(ctx, user.Id)
notifications, err := GetOrgNotifications(ctx, user.ActiveOrg.Id)
if err != nil && len(notifications) == 0 {
log.Printf("[ERROR] Failed to get notifications: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Error getting notifications."}`)))
return
}
//log.Printf("[AUDIT] Got %d notifications for org %s (%s)", len(notifications), user.ActiveOrg.Name, user.ActiveOrg.Id)
newNotifications := []Notification{}
for _, notification := range notifications {
// Check how long ago?
//if notification.Read {
// continue
//}
if notification.Personal {
continue
}
//if notification.UserId != user.Id {
// continue
//}
notification.UserId = ""
//notification.OrgId = ""
newNotifications = append(newNotifications, notification)
}
sort.Slice(notifications[:], func(i, j int) bool {
return notifications[i].UpdatedAt > notifications[j].UpdatedAt
})
notificationResponse := NotificationResponse{
Success: true,
Notifications: newNotifications,
}
//log.Printf("[DEBUG] Got %d notifications for user %s", len(notifications), user.Id)
newBody, err := json.Marshal(notificationResponse)
if err != nil {
log.Printf("[ERROR] Failed marshaling files: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false, "reason": "Failed to marshal files"}`))
return
}
resp.WriteHeader(200)
resp.Write([]byte(newBody))
}
// how to make sure that the notification workflow bucket always empties itself:
// call sendToNotificationWorkflow with the first cached notification
func sendToNotificationWorkflow(ctx context.Context, notification Notification, userApikey, workflowId string, relieveNotifications bool) error {
/*
// FIXME: Was used for disabling it before due to possible issues with infinite loops.
if project.Environment != "onprem" {
log.Printf("[DEBUG] Skipping notification workflow send for workflow %s as workflows are disabled for cloud for now.", workflowId)
return nil
}
*/
if len(workflowId) < 10 {
return nil
}
if notification.Ignored {
log.Printf("[DEBUG] Skipping notification workflow send for notification %s as it's ignored. WorkflowId: %#v", notification.Id, workflowId)
return nil
}
log.Printf("[DEBUG] Sending notification to workflow with id: %#v", workflowId)
cachedNotifications := NotificationCached{}
// caclulate hash of notification title + workflow id
unHashed := fmt.Sprintf("%s_%s", notification.Description, workflowId)
// Calculate SHA-256 hash
hasher := sha256.New()
hasher.Write([]byte(unHashed))
hashBytes := hasher.Sum(nil)
// Convert the hash to a hexadecimal string
cacheKey := hex.EncodeToString(hashBytes)
cacheData := []byte{}
// check if cache exists
cache, err := GetCache(ctx, cacheKey)
if err != nil {
/*
log.Printf("[ERROR] Failed getting cached notifications %s for notification %s: %s. Assuming no notifications are found!",
cacheKey,
notification.Id,
err,
)
*/
cacheData = []byte{}
} else {
cacheData = []byte(cache.([]uint8))
}
//log.Printf("[DEBUG] Found %d cached notifications for %s workflow %s", len(cacheData), notification.Id, workflowId)
//log.Printf("[DEBUG] Using cacheKey: %s for notification bucketing for notification id: %s", cacheKey, notification.Id)
bucketingMinutes := os.Getenv("SHUFFLE_NOTIFICATION_BUCKETING_MINUTES")
if len(bucketingMinutes) == 0 {
bucketingMinutes = "2"
}
// convert to int
bucketingMinutesInt, err := strconv.ParseInt(bucketingMinutes, 10, 32)
if err != nil {
log.Printf("[ERROR] Failed converting bucketing minutes to int: %s. Defaulting to 10 minutes!", err)
bucketingMinutesInt = 2
}
// converting to int32
bucketingTime := int32(bucketingMinutesInt)
if !relieveNotifications {
// worry about the 1440 minutes as timeout later
if len(cacheData) == 0 {
timeNow := int64(time.Now().Unix())
// save to cache and send notification
cachedNotification := NotificationCached{
NotificationId: notification.Id,
OriginalNotification: notification.Id,
LastNotificationAttempted: notification.Id,
WorkflowId: workflowId,
LastUpdated: timeNow,
FirstUpdated: timeNow,
Amount: 1,
}
// marshal cachedNotifications
cacheData, err := json.Marshal(cachedNotification)
if err != nil {
log.Printf("[ERROR] Failed marshaling cached notifications for notification %s: %s", notification.Id, err)
return err
}
err = SetCache(ctx, cacheKey, cacheData, 1440)
if err != nil {
log.Printf("[ERROR] Failed saving cached notifications %s for notification %s: %s (0)",
cacheKey,
notification.Id,
err,
)
return err
}
notification.BucketDescription = fmt.Sprintf("First notification for %s workflow %s. If more notifications are sent within %d minutes, they will be added to the next notification in %d minutes",
notification.Id,
workflowId,
bucketingMinutesInt,
bucketingMinutesInt,
)
} else {
// unmarshal cached data
err := json.Unmarshal(cacheData, &cachedNotifications)
if err != nil {
log.Printf("[ERROR] Failed unmarshaling cached notifications: %s", err)
return err
}
// check cachedNotifications.cachedNotifications
log.Printf("[DEBUG] Found %d cached notifications for %s workflow %s",
cachedNotifications.Amount,
cachedNotifications.NotificationId,
workflowId,
)
cachedNotifications.Amount += 1
cachedNotifications.LastUpdated = int64(time.Now().Unix())
cachedNotifications.LastNotificationAttempted = notification.Id
// marshal cachedNotifications
cacheData, err := json.Marshal(cachedNotifications)
if err != nil {
log.Printf("[ERROR] Failed marshaling cached notifications for notification %s: %s", notification.Id, err)
return err
}
totalTimeElapsed := int64((cachedNotifications.LastUpdated - cachedNotifications.FirstUpdated)/60)
//log.Printf("[DEBUG] Time elapsed since first notification: %d for notification %s", totalTimeElapsed, notification.Id)
err = SetCache(ctx, cacheKey, cacheData, 1440)
if err != nil {
log.Printf("[ERROR] Failed saving cached notifications %s for notification %s: %s (1)",
cacheKey,
notification.Id,
err,
)
return err
}
// Literally only starts on the 2nd, not otherwise
if cachedNotifications.Amount == 2 {
log.Printf("[DEBUG] Starting timer for %d minutes for relieving notificaions through %s notification", bucketingTime, notification.Id)
timeAfter := time.Duration(bucketingTime) * time.Minute
time.AfterFunc(timeAfter, func() {
// Read from cache again
cache, err := GetCache(ctx, cacheKey)
if err != nil {
log.Printf("[ERROR] Failed getting cached notifications %s for notification %s: %s. Assuming no notifications are found. that shouldn't happen.",
cacheKey,
notification.Id,
err,
)
}
// Test if it's a string or uint8
var cacheData []byte
tmpString, ok := cache.(string)
if !ok {
tmpUint8, ok := cache.([]uint8)
if !ok {
log.Printf("[ERROR] Failed setting cache data for notification %s. Cache casting failed", notification.Id)
return
} else {
cacheData = []byte(tmpUint8)
}
} else {
cacheData = []byte(tmpString)
}
// unmarshal cached data
var newCachedNotifications NotificationCached
err = json.Unmarshal(cacheData, &newCachedNotifications)
if err != nil {
log.Printf("[ERROR] Failed unmarshaling cached notifications for notification %s: %s", notification.Id, err)
return
}
notification.BucketDescription = fmt.Sprintf("Accumilated %d notifications in %d minutes. (Bucketing time: %d)",
newCachedNotifications.Amount - 1,
totalTimeElapsed,
bucketingMinutesInt,
)
_ = sendToNotificationWorkflow(ctx, notification, userApikey, workflowId, true)
err = DeleteCache(ctx, cacheKey)
if err != nil {
log.Printf("[ERROR] Failed deleting cached notifications %s for notification %s: %s. Assuming everything is okay and moving on",
cacheKey,
notification.Id,
err,
)
}
})
return errors.New(
"Notification with id "+ notification.Id + " was the second bucketed notification. " +
"It is responsible for relieving the bucket. " +
"We have its cache stored at: " + cacheKey,
)
}
return errors.New("Notification with id"+ notification.Id + " won't be sent and is bucketed. We have its cache stored at: " + cacheKey)
}
}
if strings.Contains(strings.ToLower(notification.ReferenceUrl), strings.ToLower(workflowId)) {
return errors.New("Same workflow ID as notification ID. Stopped for infinite loop")
}
log.Printf("[DEBUG] Should send notifications to workflow %s", workflowId)
backendUrl := os.Getenv("BASE_URL")
if project.Environment == "cloud" {
// Doesn't work multi-region
backendUrl = "https://shuffler.io"
}
// Callback to itself onprem.
if len(backendUrl) == 0 {
backendUrl = "http://localhost:5001"
}
if len(os.Getenv("SHUFFLE_CLOUDRUN_URL")) > 0 {
backendUrl = os.Getenv("SHUFFLE_CLOUDRUN_URL")
}
b, err := json.Marshal(notification)
if err != nil {
log.Printf("[DEBUG] Failed marshaling notification: %s", err)
return err
}
executionUrl := fmt.Sprintf("%s/api/v1/workflows/%s/execute", backendUrl, workflowId)
//log.Printf("\n\n[DEBUG] Notification workflow: %s. APIKEY: %#v\n\n", executionUrl, userApikey)
client := &http.Client{
Timeout: 10 * time.Second,
}
req, err := http.NewRequest(
"POST",
executionUrl,
bytes.NewBuffer(b),
)
req.Header.Add("Authorization", fmt.Sprintf(`Bearer %s`, userApikey))
req.Header.Add("Org-Id", notification.OrgId)
newresp, err := client.Do(req)
if err != nil {
return err
}
defer newresp.Body.Close()
respBody, err := ioutil.ReadAll(newresp.Body)
if err != nil {
return err
}
_ = respBody
//log.Printf("[DEBUG] Finished notification request to %s with status %d. Data: %s", executionUrl, newresp.StatusCode, string(respBody))
log.Printf("[DEBUG] Finished notification request to %s with status %d. If status is not 200, an error is created.", executionUrl, newresp.StatusCode)
if newresp.StatusCode != 200 {
return errors.New(fmt.Sprintf("Got status code %d when sending notification for org %s", newresp.StatusCode, notification.OrgId))
}
return nil
}
func forwardNotificationRequest(ctx context.Context, title, description, referenceUrl, orgId string) error {
if !strings.Contains(referenceUrl, "execution_id") && !strings.Contains(referenceUrl, "detection") {
log.Printf("[DEBUG] Notification doesn't contain execution ID and detection. Skipping (1)")
return nil
}
// Find execution id
executionId := ""
userApikey := ""
if strings.Contains(referenceUrl, "execution_id") {
executionId = strings.Split(referenceUrl, "execution_id=")[1]
if len(executionId) == 0 {
log.Printf("[DEBUG] Notification doesn't contain execution ID. Skipping (2)")
return nil
}
if strings.Contains(executionId, "&") {
executionId = strings.Split(executionId, "&")[0]
}
// Get the execution
exec, err := GetWorkflowExecution(ctx, executionId)
if err != nil {
log.Printf("[DEBUG] Failed getting execution from notification %s: %s", executionId, err)
return err
}
userApikey = exec.Authorization
}
if len(userApikey) == 0 {
auth := os.Getenv("AUTH")
if len(auth) > 0 {
userApikey = auth
}
}
notification := Notification{
Title: title,
Description: description,
ReferenceUrl: referenceUrl,
OrgId: orgId,
ExecutionId: executionId,
}
b, err := json.Marshal(notification)
if err != nil {
log.Printf("[DEBUG] Failed marshaling notification: %s", err)
return err
}
backendUrl := os.Getenv("BASE_URL")
if len(os.Getenv("SHUFFLE_CLOUDRUN_URL")) > 0 {
backendUrl = os.Getenv("SHUFFLE_CLOUDRUN_URL")
}
if len(backendUrl) == 0 {
log.Printf("[ERROR] No backend URL set for notification forwarding")
return errors.New("No backend URL set for notification")
}
executionUrl := fmt.Sprintf("%s/api/v1/notifications", backendUrl)
client := &http.Client{
Timeout: 5 * time.Second,
}
req, err := http.NewRequest(
"POST",
executionUrl,
bytes.NewBuffer(b),
)
// Environment auth if possible.
req.Header.Add("Authorization", fmt.Sprintf(`Bearer %s`, userApikey))
envName := os.Getenv("ENVIRONMENT_NAME")
req.Header.Add("Org-Id", notification.OrgId)
if len(envName) > 0 {
req.Header.Add("ENVIRONMENT_NAME", envName)
}
newresp, err := client.Do(req)
if err != nil {
log.Printf("[ERROR] Failed sending notification to backend: %s", err)
return err
}
defer newresp.Body.Close()
respBody, err := ioutil.ReadAll(newresp.Body)
if err != nil {
log.Printf("[ERROR] Failed reading response body from backend: %s", err)
return err
}
log.Printf("[DEBUG] Finished notification request to %s with status %d. Data: %s", executionUrl, newresp.StatusCode, string(respBody))
return nil
}
func CreateOrgNotification(ctx context.Context, title, description, referenceUrl, orgId string, adminsOnly bool) error {
if len(orgId) == 0 {
log.Printf("[ERROR] No org ID provided to create notification '%s'", title)
return errors.New("No org ID provided")
}
if project.Environment == "" {
auth := os.Getenv("AUTH")
org := os.Getenv("ORG")
environment := os.Getenv("ENVIRONMENT_NAME")
if len(auth) == 0 || len(org) == 0 || len(environment) == 0 {
log.Printf("[ERROR] Not generating notification, as no environment has been detected: %#v. This should not happen in Orborus.", project.Environment)
return nil
}
// Overriding it for Orborus to ensure we have a way to manage
project.Environment = "worker"
}
// Check if the referenceUrl is already in cache or not
if len(referenceUrl) > 0 {
// Have a 0-0.5 sec timeout here?
cacheKey := fmt.Sprintf("notification-%s", referenceUrl)
_, err := GetCache(ctx, cacheKey)
if err == nil {
// Avoiding duplicates for the same workflow+execution
if project.Environment != "cloud" {
//log.Printf("[DEBUG] Found cached notification for %s", referenceUrl)
}
return nil
} else {
if project.Environment != "cloud" {
//log.Printf("[DEBUG] No cached notification for %s. Creating one", referenceUrl)
}
err := SetCache(ctx, cacheKey, []byte("1"), 1)
if err != nil {
log.Printf("[ERROR] Failed saving cached notification %s: %s", cacheKey, err)
}
}
}
// FIXME: Send a request to the backend here from worker when optimized
if project.Environment == "worker" {
log.Printf("[DEBUG] Creating backend notification for org %s", orgId)
forwardNotificationRequest(ctx, title, description, referenceUrl, orgId)
return nil
}
log.Printf("[DEBUG] Creating notification for org '%s'", orgId)
notifications, err := GetOrgNotifications(ctx, orgId)
if err != nil {
log.Printf("\n\n\n[ERROR] Failed getting org notifications for %s: %s", orgId, err)
return err
}
matchingNotifications := []Notification{}
for _, notification := range notifications {
if notification.Personal {
continue
}
// notification.Title == title &&
//log.Printf("%s vs %s", notification.ReferenceUrl, referenceUrl)
if notification.Title == title && notification.Description == description {
matchingNotifications = append(matchingNotifications, notification)
}
}
org, err := GetOrg(ctx, orgId)
if err != nil {
log.Printf("[WARNING] Error getting org %s in createOrgNotification: %s", orgId, err)
return err
}
generatedId := uuid.NewV4().String()
mainNotification := Notification{
Title: title,
Description: description,
Id: generatedId,
OrgId: orgId,
OrgName: org.Name,
UserId: "",
Tags: []string{},
Amount: 1,
ReferenceUrl: referenceUrl,
OrgNotificationId: "",
Dismissable: true,
Personal: false,
Read: false,
CreatedAt: int64(time.Now().Unix()),
UpdatedAt: int64(time.Now().Unix()),
}
selectedApikey := ""
authOrg := org
if org.Defaults.NotificationWorkflow == "parent" && org.CreatorOrg != "" {
log.Printf("[DEBUG] Sending notification to parent org %s' notification workflow", org.CreatorOrg)
parentOrg, err := GetOrg(ctx, org.CreatorOrg)
if err != nil {
log.Printf("[WARNING] Error getting parent org %s in createOrgNotification: %s", orgId, err)
return err
}
// Overwriting to make sure access rights are correct
authOrg = parentOrg
org.Defaults.NotificationWorkflow = parentOrg.Defaults.NotificationWorkflow
}
for _, user := range authOrg.Users {
if user.Role == "admin" && len(user.ApiKey) > 0 && len(selectedApikey) == 0 {
// Checking if it's the right active org
// FIXME: Should it need to be in the active org? Shouldn't matter? :thinking:
foundUser, err := GetUser(ctx, user.Id)
if err == nil {
if foundUser.ActiveOrg.Id == orgId {
log.Printf("[DEBUG] Using the apikey of user %s (%s) for notification for org %s", foundUser.Username, foundUser.Id, orgId)
selectedApikey = foundUser.ApiKey
}
}
}
}
if len(matchingNotifications) > 0 {
// FIXME: This may have bugs for old workflows with new users (not being rediscovered)
if project.Environment != "cloud" {
log.Printf("[INFO] Reopening notification with title %#v for users in org %s", title, orgId)
}
usersHandled := []string{}
// Make sure to only reopen one per user
for _, notification := range matchingNotifications {
if ArrayContains(usersHandled, notification.UserId) {
//log.Printf("[DEBUG] Skipping notification %s for user %s as it's already been handled", notification.Title, notification.UserId)
continue
}
//if notification.Read == false {
// log.Printf("[DEBUG] Incrementing notification %s for user %s as it's NOT been read", notification.Title, notification.UserId)
// notification.Amount += 1
// usersHandled = append(usersHandled, notification.UserId)
// continue
//}
notification.Amount += 1
notification.Read = false
notification.ReferenceUrl = referenceUrl
// Added ignore as someone could want to never see a specific alert again due to e.g. expecting a 404 on purpose
if notification.Ignored {
notification.Read = true
mainNotification.Ignored = true
}
err = SetNotification(ctx, notification)
if err != nil {
log.Printf("[WARNING] Failed to reopen notification %s for user %s", notification.Title, notification.UserId)
} else {
//log.Printf("[INFO] Reopened and incremented notification %s for %s", notification.Title, notification.UserId)
usersHandled = append(usersHandled, notification.UserId)
}
}
if mainNotification.Ignored {
log.Printf("[INFO] Ignored notification %s for %s", mainNotification.Title, mainNotification.UserId)
} else {
err = sendToNotificationWorkflow(ctx, mainNotification, selectedApikey, org.Defaults.NotificationWorkflow, false)
if err != nil {
if !strings.Contains(err.Error(), "cache stored") && !strings.Contains(err.Error(), "Same workflow") {
log.Printf("[ERROR] Failed sending notification to workflowId %s for reference %s (2): %s", org.Defaults.NotificationWorkflow, mainNotification.Id, err)
}
}
}
return nil
} else {
log.Printf("[INFO] New notification with title %#v is being made for users in org %s", title, orgId)
// Only gonna load this after
// All the other personal ones are kind of irrelevant
err = SetNotification(ctx, mainNotification)
if err != nil {
log.Printf("[WARNING] Failed making org notification with title %#v for org %s", title, orgId)
return err
}
// 1. Find users in org
// 2. Make notification for each of them
// 3. Make reference to org notification
//NotificationWorkflow string `json:"notification_workflow" datastore:"notification_workflow"`
filteredUsers := []User{}
if adminsOnly == false {
filteredUsers = org.Users
} else {
for _, user := range org.Users {
if user.Role == "admin" {
filteredUsers = append(filteredUsers, user)
}
}
}
selectedApikey := ""
for _, user := range filteredUsers {
if user.Role == "admin" && len(user.ApiKey) > 0 && len(selectedApikey) == 0 {
// Checking if it's the right active org
// FIXME: Should it need to be in the active org? Shouldn't matter? :thinking:
foundUser, err := GetUser(ctx, user.Id)
if err == nil {
if foundUser.ActiveOrg.Id == orgId {
log.Printf("[DEBUG] Using the apikey of user %s (%s) for notification for org %s", foundUser.Username, foundUser.Id, orgId)
selectedApikey = user.ApiKey
}
}
}
//log.Printf("[DEBUG] Made notification for user %s (%s)", user.Username, user.Id)
// Skipping personal notifications. Making them orgwide instead
// FIXME: Point of personal was to make it possible to see them across
// orgs. But that's not really used anymore.
/*
newNotification := mainNotification
newNotification.Id = uuid.NewV4().String()
newNotification.OrgNotificationId = generatedId
newNotification.UserId = user.Id
newNotification.Personal = true
err = SetNotification(ctx, newNotification)
if err != nil {
log.Printf("[WARNING] Failed making USER notification with title %#v for user %s in org %s", title, user.Id, orgId)
}
*/
}
if len(org.Defaults.NotificationWorkflow) > 0 {
if len(selectedApikey) == 0 {
log.Printf("[ERROR] Didn't find an apikey to use when sending notifications for org %s to workflow %s", org.Id, org.Defaults.NotificationWorkflow)
}
workflow, err := GetWorkflow(ctx, org.Defaults.NotificationWorkflow)
if err != nil {
log.Printf("[WARNING] Failed getting workflow with ID %s: %s", org.Defaults.NotificationWorkflow, err)
return err
}
if workflow.OrgId != mainNotification.OrgId {
log.Printf("[WARNING] Can't access workflow %s with org %s (%s): %s", workflow.ID, mainNotification.OrgName, mainNotification.OrgId, workflow.Org)
// Get parent org if it exists and check too
if len(org.ManagerOrgs) > 0 {
parentOrg, err := GetOrg(ctx, org.ManagerOrgs[0].Id)
if err != nil {
log.Printf("[WARNING] Error getting parent org %s in createOrgNotification (2): %s", orgId, err)
return err
}
if org.Defaults.NotificationWorkflow != parentOrg.Defaults.NotificationWorkflow {
return errors.New(fmt.Sprintf("Org %s does not have access to workflow with ID %s", mainNotification.OrgId, workflow.ID))
} else {
log.Printf("[DEBUG] Running with parent orgs' notification workflow")
}
} else {
return errors.New(fmt.Sprintf("Org %s does not have access to workflow with ID %s", mainNotification.OrgId, workflow.ID))
}
}
err = sendToNotificationWorkflow(ctx, mainNotification, selectedApikey, org.Defaults.NotificationWorkflow, false)
if err != nil {
log.Printf("[ERROR] Failed sending notification to workflowId %s for reference %s: %s", org.Defaults.NotificationWorkflow, mainNotification.Id, err)
}
}
}
return nil
}
func HandleCreateNotification(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
// Unmarshal body to the Notification struct
// Done first so we can use the data for auth
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf("[ERROR] Failed reading body in create notification api: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
//log.Printf("[DEBUG] Creating notification based on: %s", string(body))
notification := Notification{}
err = json.Unmarshal(body, ¬ification)
if err != nil {
log.Printf("[ERROR] Failed unmarshaling body in create notification api: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
// 1. Check user directly
// 2. Check workflow execution authorization
skipUserCheck := false
orgId := ""
ctx := GetContext(request)
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[AUDIT] INITIAL Api authentication failed in Create notification api: %s", err)
// Environmentauth
// Why don't we have a function for this?
newOrgId := request.Header.Get("Org-Id")
environment := request.Header.Get("ENVIRONMENT_NAME")
apikey := request.Header.Get("Authorization")
if len(newOrgId) > 0 {
orgId = newOrgId
}
if len(orgId) > 0 && len(environment) > 0 && len(apikey) > 0 {
log.Printf("[DEBUG] HANDLING ENVIRONMENT AUTH")
authHeaderParts := strings.Split(apikey, " ")
if len(authHeaderParts) != 2 {
log.Printf("[INFO] Invalid authorization header in create notification api")
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if authHeaderParts[0] != "Bearer" {
log.Printf("[INFO] Invalid authorization header in create notification api")
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
authKey := authHeaderParts[1]
environments, err := GetEnvironments(ctx, orgId)
if err != nil {
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "Failed getting environments"}`))
return
}
found := false
for _, env := range environments {
if env.Name == environment && env.Auth == authKey {
found = true
break
}
}
if !found {
log.Printf("[AUDIT] Invalid authorization header in create notification api for Orborus request")