-
Notifications
You must be signed in to change notification settings - Fork 119
/
slack.go
244 lines (209 loc) · 6.21 KB
/
slack.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
package slack
// <!-- START clutchdoc -->
// description: Posts events to a configured Slack workspace and channel.
// <!-- END clutchdoc -->
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
"text/template"
"github.com/golang/protobuf/ptypes/any"
"github.com/slack-go/slack"
"github.com/uber-go/tally/v4"
"go.uber.org/zap"
"google.golang.org/protobuf/encoding/protojson"
auditv1 "github.com/lyft/clutch/backend/api/audit/v1"
auditconfigv1 "github.com/lyft/clutch/backend/api/config/service/audit/v1"
configv1 "github.com/lyft/clutch/backend/api/config/service/auditsink/slack/v1"
"github.com/lyft/clutch/backend/gateway/log"
"github.com/lyft/clutch/backend/service"
"github.com/lyft/clutch/backend/service/auditsink"
)
const (
Name = "clutch.service.auditsink.slack"
defaultNone = "None"
)
func New(cfg *any.Any, logger *zap.Logger, scope tally.Scope) (service.Service, error) {
config := &configv1.SlackConfig{}
if err := cfg.UnmarshalTo(config); err != nil {
return nil, err
}
s := &svc{
logger: logger,
filter: config.Filter,
overrides: NewOverrideLookup(config.Overrides),
scope: scope,
slack: slack.New(config.Token),
channel: config.Channel,
}
return s, nil
}
// The struct is used in a Go template and the fields need to be exported
type auditTemplateData struct {
Request map[string]interface{}
Response map[string]interface{}
}
// TODO: (sperry) expand on helper funcs
// helper functions to format values in the Go template
var funcMap = template.FuncMap{
// for inputs that are type slice/map, returns a formatted slack list
// currently only iterates 1-level deep
"slackList": slackList,
}
type svc struct {
logger *zap.Logger
scope tally.Scope
filter *auditconfigv1.Filter
overrides OverrideLookup
slack *slack.Client
channel string
}
func (s *svc) Write(event *auditv1.Event) error {
if !auditsink.Filter(s.filter, event) {
return nil
}
switch event.GetEventType().(type) {
case *auditv1.Event_Event:
return s.writeRequestEvent(event.GetEvent())
default:
return nil
}
}
func (s *svc) writeRequestEvent(event *auditv1.RequestEvent) error {
// Get user ID for pretty message printing.
user, err := s.slack.GetUserByEmail(event.Username)
var username string
if err != nil {
s.logger.Warn(
"failure to get user information from slack",
zap.String("username", event.Username),
zap.Error(err),
)
username = event.Username
} else {
username = fmt.Sprintf("<@%s>", user.ID)
}
messageText := s.auditEventToMessage(username, event)
// Post
if _, _, err := s.slack.PostMessage(s.channel, slack.MsgOptionText(messageText, false)); err != nil {
return err
}
return nil
}
func formatText(username string, event *auditv1.RequestEvent) string {
// Make text: `user` performed `/path/to/action` via `service` using Clutch on resources: ...
const messageFormat = "`%s` performed `%s` via `%s` using Clutch on resource(s):"
messageText := fmt.Sprintf(
messageFormat,
username,
event.MethodName,
event.ServiceName,
)
// - resourceName (`resourceTypeUrl`)
const resourceFormat = "\n- %s (`%s`)"
for _, resource := range event.Resources {
messageText += fmt.Sprintf(resourceFormat, resource.Id, resource.TypeUrl)
}
return messageText
}
// FormatCustomText applies the audit event metadata to the custom slack message
func FormatCustomText(message string, event *auditv1.RequestEvent) (string, error) {
tmpl, err := template.New("customText").Funcs(funcMap).Parse(message)
if err != nil {
return "", err
}
data, err := getAuditTemplateData(event)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return "", err
}
// When a value is nil, the Go Template sets the value as "<no value>".
sanitized := strings.ReplaceAll(buf.String(), "<no value>", defaultNone)
return strings.TrimSpace(sanitized), nil
}
func (s *svc) auditEventToMessage(username string, event *auditv1.RequestEvent) string {
message := formatText(username, event)
// check for a custom message override for the slack event
cm, ok := s.overrides.GetOverrideMessage(event.ServiceName, event.MethodName)
if ok {
if customText, err := FormatCustomText(cm, event); err != nil {
s.logger.Error("create custom message error", log.ErrorField(err))
} else {
// append custom message to the default message
message = fmt.Sprintf("%s\n%s", message, customText)
}
}
return message
}
// returns the API request/response details saved in an audit event
func getAuditTemplateData(event *auditv1.RequestEvent) (*auditTemplateData, error) {
// proto -> json
reqJSON, err := protojson.Marshal(event.RequestMetadata.Body)
if err != nil {
return nil, err
}
respJSON, err := protojson.Marshal(event.ResponseMetadata.Body)
if err != nil {
return nil, err
}
var requestMetadata map[string]interface{}
var responseMetadata map[string]interface{}
// json -> map[string]interface{}
err = json.Unmarshal(reqJSON, &requestMetadata)
if err != nil {
return nil, err
}
err = json.Unmarshal(respJSON, &responseMetadata)
if err != nil {
return nil, err
}
return &auditTemplateData{
Request: requestMetadata,
Response: responseMetadata,
}, nil
}
// helper func for formatting custom slack messages
// for inputs that are type slice/map, returns a formatted slack list
func slackList(data interface{}) string {
if data == nil {
return defaultNone
}
var b strings.Builder
const sliceItemFormat = "\n- %v"
const mapItemFormat = "\n- %v: %v"
switch reflect.TypeOf(data).Kind() {
case reflect.Slice:
s := reflect.ValueOf(data)
if s.Len() == 0 {
return defaultNone
}
// example:
// - foo
// - bar
for i := 0; i < s.Len(); i++ {
fmt.Fprintf(&b, sliceItemFormat, s.Index(i).Interface())
}
return b.String()
case reflect.Map:
m := reflect.ValueOf(data)
if m.Len() == 0 {
return defaultNone
}
// example:
// - foo: value
// - bar: value
for _, k := range m.MapKeys() {
v := m.MapIndex(k)
fmt.Fprintf(&b, mapItemFormat, k.Interface(), v.Interface())
}
return b.String()
}
// We don't return an error so that the custom slack message is still returned
// in this way, the user will know they didn't pass the correct input type to slackList
return "ERR_INPUT_NOT_SLICE_OR_MAP"
}