-
Notifications
You must be signed in to change notification settings - Fork 0
/
alert_notification.go
356 lines (328 loc) · 10.7 KB
/
alert_notification.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
package alert
import (
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"time"
"github.com/ca-risken/core/pkg/model"
"github.com/ca-risken/core/proto/alert"
"github.com/ca-risken/core/proto/finding"
"github.com/golang/protobuf/ptypes/empty"
"github.com/vikyd/zero"
"gorm.io/gorm"
)
/**
* Notification
*/
func (a *AlertService) ListNotification(ctx context.Context, req *alert.ListNotificationRequest) (*alert.ListNotificationResponse, error) {
if err := req.Validate(); err != nil {
return nil, err
}
return a.listNotification(ctx, req, true)
}
func (a *AlertService) ListNotificationForInternal(ctx context.Context, req *alert.ListNotificationForInternalRequest) (*alert.ListNotificationForInternalResponse, error) {
if err := req.Validate(); err != nil {
return nil, err
}
resp, err := a.listNotification(ctx, &alert.ListNotificationRequest{
ProjectId: req.ProjectId,
Type: req.Type,
}, false)
if err != nil {
return nil, err
}
return &alert.ListNotificationForInternalResponse{
Notification: resp.Notification,
}, nil
}
func (a *AlertService) listNotification(ctx context.Context, req *alert.ListNotificationRequest, mask bool) (*alert.ListNotificationResponse, error) {
converted := convertListNotificationRequest(req)
list, err := a.repository.ListNotification(ctx, converted.ProjectId, converted.Type, converted.FromAt, converted.ToAt)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return &alert.ListNotificationResponse{}, nil
}
return nil, err
}
data := alert.ListNotificationResponse{}
for _, d := range *list {
convertedNotification, err := a.convertNotification(ctx, &d, mask)
if err != nil {
a.logger.Errorf(ctx, "Failed to convert Notification. error: %v", err)
return nil, err
}
data.Notification = append(data.Notification, convertedNotification)
}
return &data, nil
}
func convertListNotificationRequest(req *alert.ListNotificationRequest) *alert.ListNotificationRequest {
converted := alert.ListNotificationRequest{
ProjectId: req.ProjectId,
Type: req.Type,
FromAt: req.FromAt,
ToAt: req.ToAt,
}
if converted.ToAt == 0 {
converted.ToAt = time.Now().Unix()
}
return &converted
}
func (a *AlertService) GetNotification(ctx context.Context, req *alert.GetNotificationRequest) (*alert.GetNotificationResponse, error) {
if err := req.Validate(); err != nil {
return nil, err
}
data, err := a.repository.GetNotification(ctx, req.ProjectId, req.NotificationId)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return &alert.GetNotificationResponse{}, nil
}
return nil, err
}
convertedNotification, err := a.convertNotification(ctx, data, true)
if err != nil {
a.logger.Errorf(ctx, "Failed to convert Notification. error: %v", err)
return nil, err
}
return &alert.GetNotificationResponse{Notification: convertedNotification}, nil
}
func (a *AlertService) PutNotification(ctx context.Context, req *alert.PutNotificationRequest) (*alert.PutNotificationResponse, error) {
err := req.Notification.Validate()
if err != nil {
return nil, err
}
var existData *model.Notification
if !zero.IsZeroVal(req.Notification.NotificationId) {
existData, err = a.repository.GetNotification(ctx, req.ProjectId, req.Notification.NotificationId)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return &alert.PutNotificationResponse{}, nil
}
return nil, err
}
}
data := &model.Notification{
NotificationID: req.Notification.NotificationId,
Name: req.Notification.Name,
ProjectID: req.Notification.ProjectId,
Type: req.Notification.Type,
NotifySetting: req.Notification.NotifySetting,
}
if !zero.IsZeroVal(existData) {
switch existData.Type {
case "slack":
convertedNotifySetting, err := a.replaceSlackNotifySetting(ctx, existData.NotifySetting, data.NotifySetting)
if err != nil {
return nil, err
}
newNotifySetting, err := json.Marshal(convertedNotifySetting)
if err != nil {
a.logger.Errorf(ctx, "Error occured when marshal update.NotifySetting. err: %v", err)
return nil, err
}
data.NotifySetting = string(newNotifySetting)
default:
a.logger.Warnf(ctx, "This notification_type is unimprement. type: %v", existData.Type)
}
}
// Fiding upsert
registerdData, err := a.repository.UpsertNotification(ctx, data)
if err != nil {
return nil, err
}
convertedNotification, err := a.convertNotification(ctx, registerdData, true)
if err != nil {
a.logger.Errorf(ctx, "Failed to convert Notification. error: %v", err)
return nil, err
}
return &alert.PutNotificationResponse{Notification: convertedNotification}, nil
}
func (a *AlertService) replaceSlackNotifySetting(ctx context.Context, jsonNotifySettingExist, jsonNotifySettingUpdate string) (slackNotifySetting, error) {
var notifySettingUpdate slackNotifySetting
if err := json.Unmarshal([]byte(jsonNotifySettingUpdate), ¬ifySettingUpdate); err != nil {
if err != nil {
a.logger.Errorf(ctx, "Error occured when unmarshal update.NotifySetting. err: %v", err)
return slackNotifySetting{}, err
}
}
var notifySettingExist slackNotifySetting
if err := json.Unmarshal([]byte(jsonNotifySettingExist), ¬ifySettingExist); err != nil {
if err != nil {
a.logger.Errorf(ctx, "Error occured when unmarshal exist.NotifySetting. err: %v", err)
return slackNotifySetting{}, err
}
}
if !zero.IsZeroVal(notifySettingUpdate.WebhookURL) {
return notifySettingUpdate, nil
}
notifySettingUpdate.WebhookURL = notifySettingExist.WebhookURL
return notifySettingUpdate, nil
}
func (a *AlertService) DeleteNotification(ctx context.Context, req *alert.DeleteNotificationRequest) (*empty.Empty, error) {
if err := req.Validate(); err != nil {
return nil, err
}
notifications, err := a.repository.ListAlertCondNotification(ctx, req.ProjectId, 0, req.NotificationId, 0, time.Now().Unix())
if err != nil {
return nil, err
}
for _, n := range *notifications {
if err = a.repository.DeleteAlertCondNotification(ctx, n.ProjectID, n.AlertConditionID, n.NotificationID); err != nil {
return nil, err
}
}
err = a.repository.DeleteNotification(ctx, req.ProjectId, req.NotificationId)
if err != nil {
return nil, err
}
return &empty.Empty{}, nil
}
func (a *AlertService) TestNotification(ctx context.Context, req *alert.TestNotificationRequest) (*empty.Empty, error) {
if err := req.Validate(); err != nil {
return nil, err
}
notification, err := a.repository.GetNotification(ctx, req.ProjectId, req.NotificationId)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return &empty.Empty{}, nil
}
return nil, err
}
switch notification.Type {
case "slack":
err = a.sendSlackTestNotification(ctx, a.baseURL, notification.NotifySetting, a.defaultLocale)
if err != nil {
a.logger.Errorf(ctx, "Error occured when sending test slack notification. err: %v", err)
return nil, err
}
default:
a.logger.Warnf(ctx, "This notification_type is unimprement. type: %v", notification.Type)
}
return &empty.Empty{}, nil
}
func (a *AlertService) RequestAuthzNotification(ctx context.Context, req *alert.RequestAuthzNotificationRequest) (*empty.Empty, error) {
if err := req.Validate(); err != nil {
return nil, err
}
notifications, err := a.repository.ListNotification(ctx, req.ProjectId, "slack", 0, time.Now().Unix())
sort.Slice((*notifications), func(i, j int) bool {
return (*notifications)[i].NotificationID < (*notifications)[j].NotificationID
})
notification := &(*notifications)[0]
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return &empty.Empty{}, nil
}
return nil, err
}
switch notification.Type {
case "slack":
err = a.sendSlackRequestAuthzNotification(ctx, a.baseURL, notification.NotifySetting, a.defaultLocale, req.UserName, req.ProjectName, req.ProjectId)
if err != nil {
a.logger.Errorf(ctx, "Error occured when sending request authz slack notification. err: %v", err)
return nil, err
}
default:
a.logger.Warnf(ctx, "This notification_type is unimprement. type: %v", notification.Type)
}
return &empty.Empty{}, nil
}
func (a *AlertService) convertNotification(ctx context.Context, n *model.Notification, mask bool) (*alert.Notification, error) {
if n == nil {
return &alert.Notification{}, nil
}
var err error
setting := n.NotifySetting
if mask {
setting, err = maskingNotifySetting(n.Type, setting)
if err != nil {
a.logger.Errorf(ctx, "Failed to masking notify setting. %v", err)
return &alert.Notification{}, err
}
}
return &alert.Notification{
NotificationId: n.NotificationID,
Name: n.Name,
ProjectId: n.ProjectID,
Type: n.Type,
NotifySetting: setting,
CreatedAt: n.CreatedAt.Unix(),
UpdatedAt: n.UpdatedAt.Unix(),
}, nil
}
func maskingNotifySetting(notificationType, notifySetting string) (string, error) {
switch notificationType {
case "slack":
var setting slackNotifySetting
if err := json.Unmarshal([]byte(notifySetting), &setting); err != nil {
return "", err
}
if setting.WebhookURL == "" {
return notifySetting, nil
}
setting.WebhookURL = maskRight(setting.WebhookURL, len(setting.WebhookURL)/2)
ret, err := json.Marshal(setting)
if err != nil {
return "", err
}
return string(ret), err
default:
return notifySetting, nil
}
}
func maskRight(s string, num int) string {
rs := []rune(s)
for i := num; i < len(rs); i++ {
rs[i] = '*'
}
return string(rs)
}
const (
MAX_NOTIFY_FINDING_NUM = 3
)
type findingDetail struct {
FindingCount int
Exampls []*findingExample
}
type findingExample struct {
FindingID uint64
Description string
ResourceName string
DataSource string
Score float32
Tags []string
}
func (a *AlertService) getFindingDetailsForNotification(ctx context.Context, projectID uint32, findingIDs *[]uint64) (
*findingDetail, error,
) {
findings := findingDetail{
FindingCount: len(*findingIDs),
}
for _, id := range *findingIDs {
if len(findings.Exampls) >= MAX_NOTIFY_FINDING_NUM {
break
}
ex := findingExample{}
// finding
resp, err := a.findingClient.GetFinding(ctx, &finding.GetFindingRequest{FindingId: id, ProjectId: projectID})
if err != nil {
return nil, fmt.Errorf("get finding error: err=%w", err)
}
ex.FindingID = resp.Finding.FindingId
ex.Description = resp.Finding.Description
ex.ResourceName = resp.Finding.ResourceName
ex.DataSource = resp.Finding.DataSource
ex.Score = resp.Finding.Score
// finding tag
tagResp, err := a.findingClient.ListFindingTag(ctx, &finding.ListFindingTagRequest{FindingId: id, ProjectId: projectID})
if err != nil {
return nil, fmt.Errorf("get finding tag error: err=%w", err)
}
for _, t := range tagResp.Tag {
ex.Tags = append(ex.Tags, t.Tag)
}
findings.Exampls = append(findings.Exampls, &ex)
}
return &findings, nil
}