-
Notifications
You must be signed in to change notification settings - Fork 780
/
api.go
469 lines (403 loc) · 15.5 KB
/
api.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
package alertmanager
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"reflect"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/template"
commoncfg "github.com/prometheus/common/config"
"gopkg.in/yaml.v2"
"github.com/cortexproject/cortex/pkg/alertmanager/alertspb"
"github.com/cortexproject/cortex/pkg/tenant"
"github.com/cortexproject/cortex/pkg/util"
"github.com/cortexproject/cortex/pkg/util/concurrency"
util_log "github.com/cortexproject/cortex/pkg/util/log"
)
const (
errMarshallingYAML = "error marshalling YAML Alertmanager config"
errValidatingConfig = "error validating Alertmanager config"
errReadingConfiguration = "unable to read the Alertmanager config"
errStoringConfiguration = "unable to store the Alertmanager config"
errDeletingConfiguration = "unable to delete the Alertmanager config"
errNoOrgID = "unable to determine the OrgID"
errListAllUser = "unable to list the Alertmanager users"
errConfigurationTooBig = "Alertmanager configuration is too big, limit: %d bytes"
errTooManyTemplates = "too many templates in the configuration: %d (limit: %d)"
errTemplateTooBig = "template %s is too big: %d bytes (limit: %d bytes)"
fetchConcurrency = 16
)
var (
errPasswordFileNotAllowed = errors.New("setting password_file, bearer_token_file and credentials_file is not allowed")
errOAuth2SecretFileNotAllowed = errors.New("setting OAuth2 client_secret_file is not allowed")
errTLSFileNotAllowed = errors.New("setting TLS ca_file, cert_file and key_file is not allowed")
errSlackAPIURLFileNotAllowed = errors.New("setting Slack api_url_file and global slack_api_url_file is not allowed")
errVictorOpsAPIKeyFileNotAllowed = errors.New("setting VictorOps api_key_file is not allowed")
errOpsGenieAPIKeyFileNotAllowed = errors.New("setting OpsGenie api_key_file is not allowed")
)
// UserConfig is used to communicate a users alertmanager configs
type UserConfig struct {
TemplateFiles map[string]string `yaml:"template_files"`
AlertmanagerConfig string `yaml:"alertmanager_config"`
}
func (am *MultitenantAlertmanager) GetUserConfig(w http.ResponseWriter, r *http.Request) {
logger := util_log.WithContext(r.Context(), am.logger)
userID, err := tenant.TenantID(r.Context())
if err != nil {
level.Error(logger).Log("msg", errNoOrgID, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errNoOrgID, err.Error()), http.StatusUnauthorized)
return
}
cfg, err := am.store.GetAlertConfig(r.Context(), userID)
if err != nil {
if err == alertspb.ErrNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
d, err := yaml.Marshal(&UserConfig{
TemplateFiles: alertspb.ParseTemplates(cfg),
AlertmanagerConfig: cfg.RawConfig,
})
if err != nil {
level.Error(logger).Log("msg", errMarshallingYAML, "err", err, "user", userID)
http.Error(w, fmt.Sprintf("%s: %s", errMarshallingYAML, err.Error()), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/yaml")
if _, err := w.Write(d); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (am *MultitenantAlertmanager) SetUserConfig(w http.ResponseWriter, r *http.Request) {
logger := util_log.WithContext(r.Context(), am.logger)
userID, err := tenant.TenantID(r.Context())
if err != nil {
level.Error(logger).Log("msg", errNoOrgID, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errNoOrgID, err.Error()), http.StatusUnauthorized)
return
}
var input io.Reader
maxConfigSize := am.limits.AlertmanagerMaxConfigSize(userID)
if maxConfigSize > 0 {
// LimitReader will return EOF after reading specified number of bytes. To check if
// we have read too many bytes, allow one extra byte.
input = io.LimitReader(r.Body, int64(maxConfigSize)+1)
} else {
input = r.Body
}
payload, err := io.ReadAll(input)
if err != nil {
level.Error(logger).Log("msg", errReadingConfiguration, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errReadingConfiguration, err.Error()), http.StatusBadRequest)
return
}
if maxConfigSize > 0 && len(payload) > maxConfigSize {
msg := fmt.Sprintf(errConfigurationTooBig, maxConfigSize)
level.Warn(logger).Log("msg", msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
cfg := &UserConfig{}
err = yaml.Unmarshal(payload, cfg)
if err != nil {
level.Error(logger).Log("msg", errMarshallingYAML, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errMarshallingYAML, err.Error()), http.StatusBadRequest)
return
}
cfgDesc := alertspb.ToProto(cfg.AlertmanagerConfig, cfg.TemplateFiles, userID)
if err := validateUserConfig(logger, cfgDesc, am.limits, userID); err != nil {
level.Warn(logger).Log("msg", errValidatingConfig, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errValidatingConfig, err.Error()), http.StatusBadRequest)
return
}
err = am.store.SetAlertConfig(r.Context(), cfgDesc)
if err != nil {
level.Error(logger).Log("msg", errStoringConfiguration, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errStoringConfiguration, err.Error()), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
// DeleteUserConfig is exposed via user-visible API (if enabled, uses DELETE method), but also as an internal endpoint using POST method.
// Note that if no config exists for a user, StatusOK is returned.
func (am *MultitenantAlertmanager) DeleteUserConfig(w http.ResponseWriter, r *http.Request) {
logger := util_log.WithContext(r.Context(), am.logger)
userID, err := tenant.TenantID(r.Context())
if err != nil {
level.Error(logger).Log("msg", errNoOrgID, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errNoOrgID, err.Error()), http.StatusUnauthorized)
return
}
err = am.store.DeleteAlertConfig(r.Context(), userID)
if err != nil {
level.Error(logger).Log("msg", errDeletingConfiguration, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errDeletingConfiguration, err.Error()), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// Partially copied from: https://github.com/prometheus/alertmanager/blob/8e861c646bf67599a1704fc843c6a94d519ce312/cli/check_config.go#L65-L96
func validateUserConfig(logger log.Logger, cfg alertspb.AlertConfigDesc, limits Limits, user string) error {
// We don't have a valid use case for empty configurations. If a tenant does not have a
// configuration set and issue a request to the Alertmanager, we'll a) upload an empty
// config and b) immediately start an Alertmanager instance for them if a fallback
// configuration is provisioned.
if cfg.RawConfig == "" {
return fmt.Errorf("configuration provided is empty, if you'd like to remove your configuration please use the delete configuration endpoint")
}
amCfg, err := config.Load(cfg.RawConfig)
if err != nil {
return err
}
// Validate the config recursively scanning it.
if err := validateAlertmanagerConfig(amCfg); err != nil {
return err
}
// Validate templates referenced in the alertmanager config.
for _, name := range amCfg.Templates {
if err := validateTemplateFilename(name); err != nil {
return err
}
}
// Check template limits.
if l := limits.AlertmanagerMaxTemplatesCount(user); l > 0 && len(cfg.Templates) > l {
return fmt.Errorf(errTooManyTemplates, len(cfg.Templates), l)
}
if maxSize := limits.AlertmanagerMaxTemplateSize(user); maxSize > 0 {
for _, tmpl := range cfg.Templates {
if size := len(tmpl.GetBody()); size > maxSize {
return fmt.Errorf(errTemplateTooBig, tmpl.GetFilename(), size, maxSize)
}
}
}
// Validate template files.
for _, tmpl := range cfg.Templates {
if err := validateTemplateFilename(tmpl.Filename); err != nil {
return err
}
}
// Create templates on disk in a temporary directory.
// Note: This means the validation will succeed if we can write to tmp but
// not to configured data dir, and on the flipside, it'll fail if we can't write
// to tmpDir. Ignoring both cases for now as they're ultra rare but will revisit if
// we see this in the wild.
userTempDir, err := os.MkdirTemp("", "validate-config-"+cfg.User)
if err != nil {
return err
}
defer os.RemoveAll(userTempDir)
for _, tmpl := range cfg.Templates {
templateFilepath, err := safeTemplateFilepath(userTempDir, tmpl.Filename)
if err != nil {
level.Error(logger).Log("msg", "unable to create template file path", "err", err, "user", cfg.User)
return err
}
if _, err = storeTemplateFile(templateFilepath, tmpl.Body); err != nil {
level.Error(logger).Log("msg", "unable to store template file", "err", err, "user", cfg.User)
return fmt.Errorf("unable to store template file '%s'", tmpl.Filename)
}
}
templateFiles := make([]string, len(amCfg.Templates))
for i, t := range amCfg.Templates {
templateFiles[i] = filepath.Join(userTempDir, t)
}
_, err = template.FromGlobs(templateFiles...)
if err != nil {
return err
}
// Note: Not validating the MultitenantAlertmanager.transformConfig function as that
// that function shouldn't break configuration. Only way it can fail is if the base
// autoWebhookURL itself is broken. In that case, I would argue, we should accept the config
// not reject it.
return nil
}
func (am *MultitenantAlertmanager) ListAllConfigs(w http.ResponseWriter, r *http.Request) {
logger := util_log.WithContext(r.Context(), am.logger)
userIDs, err := am.store.ListAllUsers(r.Context())
if err != nil {
level.Error(logger).Log("msg", "failed to list users of alertmanager", "err", err)
http.Error(w, fmt.Sprintf("%s: %s", errListAllUser, err.Error()), http.StatusInternalServerError)
return
}
done := make(chan struct{})
iter := make(chan interface{})
go func() {
util.StreamWriteYAMLResponse(w, iter, logger)
close(done)
}()
err = concurrency.ForEachUser(r.Context(), userIDs, fetchConcurrency, func(ctx context.Context, userID string) error {
cfg, err := am.store.GetAlertConfig(ctx, userID)
if errors.Is(err, alertspb.ErrNotFound) {
return nil
} else if err != nil {
return errors.Wrapf(err, "failed to fetch alertmanager config for user %s", userID)
}
data := map[string]*UserConfig{
userID: {
TemplateFiles: alertspb.ParseTemplates(cfg),
AlertmanagerConfig: cfg.RawConfig,
},
}
select {
case iter <- data:
case <-done: // stop early, if sending response has already finished
}
return nil
})
if err != nil {
level.Error(logger).Log("msg", "failed to list all alertmanager configs", "err", err)
}
close(iter)
<-done
}
// validateAlertmanagerConfig recursively scans the input config looking for data types for which
// we have a specific validation and, whenever encountered, it runs their validation. Returns the
// first error or nil if validation succeeds.
func validateAlertmanagerConfig(cfg interface{}) error {
v := reflect.ValueOf(cfg)
t := v.Type()
// Skip invalid, the zero value or a nil pointer (checked by zero value).
if !v.IsValid() || v.IsZero() {
return nil
}
// If the input config is a pointer then we need to get its value.
// At this point the pointer value can't be nil.
if v.Kind() == reflect.Ptr {
v = v.Elem()
t = v.Type()
}
// Check if the input config is a data type for which we have a specific validation.
// At this point the value can't be a pointer anymore.
switch t {
case reflect.TypeOf(config.GlobalConfig{}):
if err := validateGlobalConfig(v.Interface().(config.GlobalConfig)); err != nil {
return err
}
case reflect.TypeOf(commoncfg.HTTPClientConfig{}):
if err := validateReceiverHTTPConfig(v.Interface().(commoncfg.HTTPClientConfig)); err != nil {
return err
}
case reflect.TypeOf(config.OpsGenieConfig{}):
if err := validateOpsGenieConfig(v.Interface().(config.OpsGenieConfig)); err != nil {
return err
}
case reflect.TypeOf(commoncfg.TLSConfig{}):
if err := validateReceiverTLSConfig(v.Interface().(commoncfg.TLSConfig)); err != nil {
return err
}
case reflect.TypeOf(config.SlackConfig{}):
if err := validateSlackConfig(v.Interface().(config.SlackConfig)); err != nil {
return err
}
case reflect.TypeOf(config.VictorOpsConfig{}):
if err := validateVictorOpsConfig(v.Interface().(config.VictorOpsConfig)); err != nil {
return err
}
}
// If the input config is a struct, recursively iterate on all fields.
if t.Kind() == reflect.Struct {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fieldValue := v.FieldByIndex(field.Index)
// Skip any field value which can't be converted to interface (eg. primitive types).
if fieldValue.CanInterface() {
if err := validateAlertmanagerConfig(fieldValue.Interface()); err != nil {
return err
}
}
}
}
if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
fieldValue := v.Index(i)
// Skip any field value which can't be converted to interface (eg. primitive types).
if fieldValue.CanInterface() {
if err := validateAlertmanagerConfig(fieldValue.Interface()); err != nil {
return err
}
}
}
}
if t.Kind() == reflect.Map {
for _, key := range v.MapKeys() {
fieldValue := v.MapIndex(key)
// Skip any field value which can't be converted to interface (eg. primitive types).
if fieldValue.CanInterface() {
if err := validateAlertmanagerConfig(fieldValue.Interface()); err != nil {
return err
}
}
}
}
return nil
}
// validateReceiverHTTPConfig validates the HTTP config and returns an error if it contains
// settings not allowed by Cortex.
func validateReceiverHTTPConfig(cfg commoncfg.HTTPClientConfig) error {
if cfg.BasicAuth != nil && cfg.BasicAuth.PasswordFile != "" {
return errPasswordFileNotAllowed
}
if cfg.Authorization != nil && cfg.Authorization.CredentialsFile != "" {
return errPasswordFileNotAllowed
}
if cfg.BearerTokenFile != "" {
return errPasswordFileNotAllowed
}
if cfg.OAuth2 != nil && cfg.OAuth2.ClientSecretFile != "" {
return errOAuth2SecretFileNotAllowed
}
return validateReceiverTLSConfig(cfg.TLSConfig)
}
// validateReceiverTLSConfig validates the TLS config and returns an error if it contains
// settings not allowed by Cortex.
func validateReceiverTLSConfig(cfg commoncfg.TLSConfig) error {
if cfg.CAFile != "" || cfg.CertFile != "" || cfg.KeyFile != "" {
return errTLSFileNotAllowed
}
return nil
}
// validateGlobalConfig validates the Global config and returns an error if it contains
// settings now allowed by Cortex.
func validateGlobalConfig(cfg config.GlobalConfig) error {
if cfg.OpsGenieAPIKeyFile != "" {
return errOpsGenieAPIKeyFileNotAllowed
}
if cfg.SlackAPIURLFile != "" {
return errSlackAPIURLFileNotAllowed
}
return nil
}
// validateOpsGenieConfig validates the OpsGenie config and returns an error if it contains
// settings now allowed by Cortex.
func validateOpsGenieConfig(cfg config.OpsGenieConfig) error {
if cfg.APIKeyFile != "" {
return errOpsGenieAPIKeyFileNotAllowed
}
return nil
}
// validateSlackConfig validates the Slack config and returns an error if it contains
// settings now allowed by Cortex.
func validateSlackConfig(cfg config.SlackConfig) error {
if cfg.APIURLFile != "" {
return errSlackAPIURLFileNotAllowed
}
return nil
}
// validateVictorOpsConfig validates the VictorOps config and returns an error if it contains
// settings now allowed by Cortex.
func validateVictorOpsConfig(cfg config.VictorOpsConfig) error {
if cfg.APIKeyFile != "" {
return errVictorOpsAPIKeyFileNotAllowed
}
return nil
}