Alerting: Remove the POST endpoint for the internal Grafana Alertmanager config (#103819)
* Remove POST config for Grafana Alertmanager * Delete auth + test for removed path * Alerting: Remove check for `alertingApiServer` toggle in UI (#103805) * Remove check for alertingApiServer in UI * Update tests to no longer care about alertingApiServer * Add contact points handlers now that we use alertingApiServer all the time * Fix test broken from removing camelCase for UIDs --------- Co-authored-by: Tom Ratcliffe <tom.ratcliffe@grafana.com>
This commit is contained in:
co-authored by
Tom Ratcliffe
parent
c47ab101d1
commit
a5288db624
@@ -10,8 +10,6 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/alertmanager/config"
|
||||
"github.com/prometheus/alertmanager/pkg/labels"
|
||||
"github.com/prometheus/common/model"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
@@ -354,49 +352,3 @@ func TestIntegrationAdminConfiguration_SendingToExternalAlertmanagers(t *testing
|
||||
}, 16*time.Second, 8*time.Second) // the sync interval is 2s so after 8s all alertmanagers (if any) most probably are started
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationAdminConfiguration_CannotCreateInhibitionRules(t *testing.T) {
|
||||
testinfra.SQLiteIntegrationTest(t)
|
||||
dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{
|
||||
DisableLegacyAlerting: true,
|
||||
EnableUnifiedAlerting: true,
|
||||
AppModeProduction: true,
|
||||
})
|
||||
grafanaListedAddr, env := testinfra.StartGrafanaEnv(t, dir, path)
|
||||
createUser(t, env.SQLStore, env.Cfg, user.CreateUserCommand{
|
||||
DefaultOrgRole: string(org.RoleAdmin),
|
||||
Password: "admin",
|
||||
Login: "admin",
|
||||
})
|
||||
client := newAlertingApiClient(grafanaListedAddr, "admin", "admin")
|
||||
|
||||
cfg := apimodels.PostableUserConfig{
|
||||
AlertmanagerConfig: apimodels.PostableApiAlertingConfig{
|
||||
Config: apimodels.Config{
|
||||
Route: &apimodels.Route{
|
||||
Receiver: "test",
|
||||
},
|
||||
InhibitRules: []config.InhibitRule{{
|
||||
SourceMatchers: config.Matchers{{
|
||||
Type: labels.MatchEqual,
|
||||
Name: "foo",
|
||||
Value: "bar",
|
||||
}},
|
||||
TargetMatchers: config.Matchers{{
|
||||
Type: labels.MatchEqual,
|
||||
Name: "bar",
|
||||
Value: "baz",
|
||||
}},
|
||||
}},
|
||||
},
|
||||
Receivers: []*apimodels.PostableApiReceiver{{
|
||||
Receiver: config.Receiver{
|
||||
Name: "test",
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
ok, err := client.PostConfiguration(t, cfg)
|
||||
require.False(t, ok)
|
||||
require.EqualError(t, err, "inhibition rules are not supported")
|
||||
}
|
||||
|
||||
@@ -1,554 +0,0 @@
|
||||
package alerting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/alertmanager/config"
|
||||
"github.com/prometheus/alertmanager/pkg/labels"
|
||||
"github.com/prometheus/alertmanager/timeinterval"
|
||||
"github.com/prometheus/common/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||
"github.com/grafana/grafana/pkg/services/org"
|
||||
"github.com/grafana/grafana/pkg/services/org/orgimpl"
|
||||
"github.com/grafana/grafana/pkg/services/quota/quotatest"
|
||||
"github.com/grafana/grafana/pkg/services/user"
|
||||
"github.com/grafana/grafana/pkg/tests/testinfra"
|
||||
)
|
||||
|
||||
func TestIntegrationAlertmanagerConfiguration(t *testing.T) {
|
||||
testinfra.SQLiteIntegrationTest(t)
|
||||
dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{
|
||||
DisableLegacyAlerting: true,
|
||||
EnableUnifiedAlerting: true,
|
||||
AppModeProduction: true,
|
||||
})
|
||||
grafanaListedAddr, env := testinfra.StartGrafanaEnv(t, dir, path)
|
||||
createUser(t, env.SQLStore, env.Cfg, user.CreateUserCommand{
|
||||
DefaultOrgRole: string(org.RoleAdmin),
|
||||
Password: "admin",
|
||||
Login: "admin",
|
||||
})
|
||||
client := newAlertingApiClient(grafanaListedAddr, "admin", "admin")
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
cfg apimodels.PostableUserConfig
|
||||
expErr string
|
||||
}{{
|
||||
name: "configuration with default route",
|
||||
cfg: apimodels.PostableUserConfig{
|
||||
AlertmanagerConfig: apimodels.PostableApiAlertingConfig{
|
||||
Config: apimodels.Config{
|
||||
Route: &apimodels.Route{
|
||||
Receiver: "test",
|
||||
},
|
||||
},
|
||||
Receivers: []*apimodels.PostableApiReceiver{{
|
||||
Receiver: config.Receiver{
|
||||
Name: "test",
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "configuration with UTF-8 matchers",
|
||||
cfg: apimodels.PostableUserConfig{
|
||||
AlertmanagerConfig: apimodels.PostableApiAlertingConfig{
|
||||
Config: apimodels.Config{
|
||||
Route: &apimodels.Route{
|
||||
Receiver: "test",
|
||||
Routes: []*apimodels.Route{{
|
||||
GroupBy: []model.LabelName{"foo🙂"},
|
||||
Matchers: config.Matchers{{
|
||||
Type: labels.MatchEqual,
|
||||
Name: "foo🙂",
|
||||
Value: "bar",
|
||||
}, {
|
||||
Type: labels.MatchNotEqual,
|
||||
Name: "_bar1",
|
||||
Value: "baz🙂",
|
||||
}, {
|
||||
Type: labels.MatchRegexp,
|
||||
Name: "0baz",
|
||||
Value: "[a-zA-Z0-9]+,?",
|
||||
}, {
|
||||
Type: labels.MatchNotRegexp,
|
||||
Name: "corge",
|
||||
Value: "^[0-9]+((,[0-9]{3})*(,[0-9]{0,3})?)?$",
|
||||
}, {
|
||||
Type: labels.MatchEqual,
|
||||
Name: "Προμηθέας", // Prometheus in Greek
|
||||
Value: "Prom",
|
||||
}, {
|
||||
Type: labels.MatchNotEqual,
|
||||
Name: "犬", // Dog in Japanese
|
||||
Value: "Shiba Inu",
|
||||
}},
|
||||
}},
|
||||
},
|
||||
},
|
||||
Receivers: []*apimodels.PostableApiReceiver{{
|
||||
Receiver: config.Receiver{
|
||||
Name: "test",
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "configuration with UTF-8 object matchers",
|
||||
cfg: apimodels.PostableUserConfig{
|
||||
AlertmanagerConfig: apimodels.PostableApiAlertingConfig{
|
||||
Config: apimodels.Config{
|
||||
Route: &apimodels.Route{
|
||||
Receiver: "test",
|
||||
Routes: []*apimodels.Route{{
|
||||
GroupBy: []model.LabelName{"foo🙂"},
|
||||
ObjectMatchers: apimodels.ObjectMatchers{{
|
||||
Type: labels.MatchEqual,
|
||||
Name: "foo🙂",
|
||||
Value: "bar",
|
||||
}, {
|
||||
Type: labels.MatchNotEqual,
|
||||
Name: "_bar1",
|
||||
Value: "baz🙂",
|
||||
}, {
|
||||
Type: labels.MatchRegexp,
|
||||
Name: "0baz",
|
||||
Value: "[a-zA-Z0-9]+,?",
|
||||
}, {
|
||||
Type: labels.MatchNotRegexp,
|
||||
Name: "corge",
|
||||
Value: "^[0-9]+((,[0-9]{3})*(,[0-9]{0,3})?)?$",
|
||||
}, {
|
||||
Type: labels.MatchEqual,
|
||||
Name: "Προμηθέας", // Prometheus in Greek
|
||||
Value: "Prom",
|
||||
}, {
|
||||
Type: labels.MatchNotEqual,
|
||||
Name: "犬", // Dog in Japanese
|
||||
Value: "Shiba Inu",
|
||||
}},
|
||||
}},
|
||||
},
|
||||
},
|
||||
Receivers: []*apimodels.PostableApiReceiver{{
|
||||
Receiver: config.Receiver{
|
||||
Name: "test",
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "configuration with UTF-8 in both matchers and object matchers",
|
||||
cfg: apimodels.PostableUserConfig{
|
||||
AlertmanagerConfig: apimodels.PostableApiAlertingConfig{
|
||||
Config: apimodels.Config{
|
||||
Route: &apimodels.Route{
|
||||
Receiver: "test",
|
||||
Routes: []*apimodels.Route{{
|
||||
GroupBy: []model.LabelName{"foo🙂"},
|
||||
Matchers: config.Matchers{{
|
||||
Type: labels.MatchEqual,
|
||||
Name: "foo🙂",
|
||||
Value: "bar",
|
||||
}, {
|
||||
Type: labels.MatchNotEqual,
|
||||
Name: "_bar1",
|
||||
Value: "baz🙂",
|
||||
}, {
|
||||
Type: labels.MatchRegexp,
|
||||
Name: "0baz",
|
||||
Value: "[a-zA-Z0-9]+,?",
|
||||
}, {
|
||||
Type: labels.MatchNotRegexp,
|
||||
Name: "corge",
|
||||
Value: "^[0-9]+((,[0-9]{3})*(,[0-9]{0,3})?)?$",
|
||||
}},
|
||||
ObjectMatchers: apimodels.ObjectMatchers{{
|
||||
Type: labels.MatchEqual,
|
||||
Name: "Προμηθέας", // Prometheus in Greek
|
||||
Value: "Prom",
|
||||
}, {
|
||||
Type: labels.MatchNotEqual,
|
||||
Name: "犬", // Dog in Japanese
|
||||
Value: "Shiba Inu",
|
||||
}},
|
||||
}},
|
||||
},
|
||||
},
|
||||
Receivers: []*apimodels.PostableApiReceiver{{
|
||||
Receiver: config.Receiver{
|
||||
Name: "test",
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
// TODO: Mute time intervals is deprecated in Alertmanager and scheduled to be
|
||||
// removed before version 1.0. Remove this test when support for mute time
|
||||
// intervals is removed.
|
||||
name: "configuration with mute time intervals",
|
||||
cfg: apimodels.PostableUserConfig{
|
||||
AlertmanagerConfig: apimodels.PostableApiAlertingConfig{
|
||||
Config: apimodels.Config{
|
||||
Route: &apimodels.Route{
|
||||
Receiver: "test",
|
||||
Routes: []*apimodels.Route{{
|
||||
MuteTimeIntervals: []string{"weekends"},
|
||||
}},
|
||||
},
|
||||
MuteTimeIntervals: []config.MuteTimeInterval{{
|
||||
Name: "weekends",
|
||||
TimeIntervals: []timeinterval.TimeInterval{{
|
||||
Weekdays: []timeinterval.WeekdayRange{{
|
||||
InclusiveRange: timeinterval.InclusiveRange{
|
||||
Begin: 1,
|
||||
End: 5,
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}},
|
||||
},
|
||||
Receivers: []*apimodels.PostableApiReceiver{{
|
||||
Receiver: config.Receiver{
|
||||
Name: "test",
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "configuration with time intervals",
|
||||
cfg: apimodels.PostableUserConfig{
|
||||
AlertmanagerConfig: apimodels.PostableApiAlertingConfig{
|
||||
Config: apimodels.Config{
|
||||
Route: &apimodels.Route{
|
||||
Receiver: "test",
|
||||
Routes: []*apimodels.Route{{
|
||||
MuteTimeIntervals: []string{"weekends"},
|
||||
}},
|
||||
},
|
||||
TimeIntervals: []config.TimeInterval{{
|
||||
Name: "weekends",
|
||||
TimeIntervals: []timeinterval.TimeInterval{{
|
||||
Weekdays: []timeinterval.WeekdayRange{{
|
||||
InclusiveRange: timeinterval.InclusiveRange{
|
||||
Begin: 1,
|
||||
End: 5,
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}},
|
||||
},
|
||||
Receivers: []*apimodels.PostableApiReceiver{{
|
||||
Receiver: config.Receiver{
|
||||
Name: "test",
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ok, err := client.PostConfiguration(t, tc.cfg)
|
||||
if tc.expErr != "" {
|
||||
require.EqualError(t, err, tc.expErr)
|
||||
require.False(t, ok)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationAlertmanagerConfigurationIsTransactional(t *testing.T) {
|
||||
testinfra.SQLiteIntegrationTest(t)
|
||||
|
||||
dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{
|
||||
DisableLegacyAlerting: true,
|
||||
EnableUnifiedAlerting: true,
|
||||
NGAlertAlertmanagerConfigPollInterval: 2 * time.Second,
|
||||
DisableAnonymous: true,
|
||||
AppModeProduction: true,
|
||||
})
|
||||
|
||||
grafanaListedAddr, env := testinfra.StartGrafanaEnv(t, dir, path)
|
||||
|
||||
orgService, err := orgimpl.ProvideService(env.SQLStore, env.Cfg, quotatest.New(false, nil))
|
||||
require.NoError(t, err)
|
||||
|
||||
// editor from main organisation requests configuration
|
||||
alertConfigURL := fmt.Sprintf("http://editor:editor@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
|
||||
|
||||
// create user under main organisation
|
||||
userID := createUser(t, env.SQLStore, env.Cfg, user.CreateUserCommand{
|
||||
DefaultOrgRole: string(org.RoleEditor),
|
||||
Password: "editor",
|
||||
Login: "editor",
|
||||
})
|
||||
|
||||
// create another organisation
|
||||
newOrg, err := orgService.CreateWithMember(context.Background(), &org.CreateOrgCommand{Name: "another org", UserID: userID})
|
||||
require.NoError(t, err)
|
||||
orgID := newOrg.ID
|
||||
|
||||
// create user under different organisation
|
||||
createUser(t, env.SQLStore, env.Cfg, user.CreateUserCommand{
|
||||
DefaultOrgRole: string(org.RoleEditor),
|
||||
Password: "editor-42",
|
||||
Login: "editor-42",
|
||||
OrgID: orgID,
|
||||
})
|
||||
|
||||
// On a blank start with no configuration, it saves and delivers the default configuration.
|
||||
{
|
||||
resp := getRequest(t, alertConfigURL, http.StatusOK) // nolint
|
||||
require.JSONEq(t, defaultAlertmanagerConfigJSON, getBody(t, resp.Body))
|
||||
}
|
||||
|
||||
// When creating new configuration, if it fails to apply - it does not save it.
|
||||
{
|
||||
payload := `
|
||||
{
|
||||
"template_files": {},
|
||||
"alertmanager_config": {
|
||||
"route": {
|
||||
"receiver": "slack.receiver"
|
||||
},
|
||||
"receivers": [{
|
||||
"name": "slack.receiver",
|
||||
"grafana_managed_receiver_configs": [{
|
||||
"settings": {
|
||||
"iconEmoji": "",
|
||||
"iconUrl": "",
|
||||
"mentionGroups": "",
|
||||
"mentionUsers": "",
|
||||
"recipient": "#unified-alerting-test",
|
||||
"username": ""
|
||||
},
|
||||
"secureSettings": {},
|
||||
"type": "slack",
|
||||
"name": "slack.receiver",
|
||||
"disableResolveMessage": false,
|
||||
"uid": ""
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
`
|
||||
resp := postRequest(t, alertConfigURL, payload, http.StatusBadRequest) // nolint
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
var res map[string]any
|
||||
require.NoError(t, json.Unmarshal(b, &res))
|
||||
require.Regexp(t, `^failed to save and apply Alertmanager configuration: failed to validate integration "slack.receiver" \(UID [^\)]+\) of type "slack": token must be specified when using the Slack chat API`, res["message"])
|
||||
resp = getRequest(t, alertConfigURL, http.StatusOK) // nolint
|
||||
|
||||
require.JSONEq(t, defaultAlertmanagerConfigJSON, getBody(t, resp.Body))
|
||||
}
|
||||
|
||||
// editor42 from organisation 42 posts configuration
|
||||
alertConfigURL = fmt.Sprintf("http://editor-42:editor-42@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
|
||||
|
||||
// Before we start operating, make sure we've synced this org.
|
||||
require.Eventually(t, func() bool {
|
||||
resp, err := http.Get(alertConfigURL) // nolint
|
||||
require.NoError(t, err)
|
||||
return resp.StatusCode == http.StatusOK
|
||||
}, 10*time.Second, 2*time.Second)
|
||||
|
||||
// Post the alertmanager config.
|
||||
{
|
||||
mockChannel := newMockNotificationChannel(t, grafanaListedAddr)
|
||||
amConfig := getAlertmanagerConfig(mockChannel.server.Addr)
|
||||
postRequest(t, alertConfigURL, amConfig, http.StatusAccepted) // nolint
|
||||
|
||||
// Verifying that the new configuration is returned
|
||||
resp := getRequest(t, alertConfigURL, http.StatusOK) // nolint
|
||||
b := getBody(t, resp.Body)
|
||||
re := regexp.MustCompile(`"uid":"([\w|-]*)"`)
|
||||
e := getExpAlertmanagerConfigFromAPI(mockChannel.server.Addr)
|
||||
require.JSONEq(t, e, string(re.ReplaceAll([]byte(b), []byte(`"uid":""`))))
|
||||
}
|
||||
|
||||
// verify that main organisation still gets the default configuration
|
||||
alertConfigURL = fmt.Sprintf("http://editor:editor@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
|
||||
{
|
||||
resp := getRequest(t, alertConfigURL, http.StatusOK) // nolint
|
||||
require.JSONEq(t, defaultAlertmanagerConfigJSON, getBody(t, resp.Body))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationAlertmanagerConfigurationPersistSecrets(t *testing.T) {
|
||||
testinfra.SQLiteIntegrationTest(t)
|
||||
|
||||
dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{
|
||||
DisableLegacyAlerting: true,
|
||||
EnableUnifiedAlerting: true,
|
||||
DisableAnonymous: true,
|
||||
AppModeProduction: true,
|
||||
DisableFeatureToggles: []string{featuremgmt.FlagAlertingApiServer},
|
||||
})
|
||||
|
||||
grafanaListedAddr, env := testinfra.StartGrafanaEnv(t, dir, path)
|
||||
alertConfigURL := fmt.Sprintf("http://editor:editor@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
|
||||
|
||||
createUser(t, env.SQLStore, env.Cfg, user.CreateUserCommand{
|
||||
DefaultOrgRole: string(org.RoleEditor),
|
||||
Password: "editor",
|
||||
Login: "editor",
|
||||
})
|
||||
generatedUID := ""
|
||||
|
||||
// create a new configuration that has a secret
|
||||
{
|
||||
payload := `
|
||||
{
|
||||
"template_files": {},
|
||||
"alertmanager_config": {
|
||||
"route": {
|
||||
"receiver": "slack.receiver"
|
||||
},
|
||||
"receivers": [{
|
||||
"name": "slack.receiver",
|
||||
"grafana_managed_receiver_configs": [{
|
||||
"settings": {
|
||||
"recipient": "#unified-alerting-test"
|
||||
},
|
||||
"secureSettings": {
|
||||
"url": "http://averysecureurl.com/webhook"
|
||||
},
|
||||
"type": "slack",
|
||||
"name": "slack.receiver",
|
||||
"disableResolveMessage": false
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
`
|
||||
resp := postRequest(t, alertConfigURL, payload, http.StatusAccepted) // nolint
|
||||
require.JSONEq(t, `{"message":"configuration created"}`, getBody(t, resp.Body))
|
||||
}
|
||||
|
||||
// Try to update a receiver with unknown UID
|
||||
{
|
||||
// Then, update the recipient
|
||||
payload := `
|
||||
{
|
||||
"template_files": {},
|
||||
"alertmanager_config": {
|
||||
"route": {
|
||||
"receiver": "slack.receiver"
|
||||
},
|
||||
"receivers": [{
|
||||
"name": "slack.receiver",
|
||||
"grafana_managed_receiver_configs": [{
|
||||
"settings": {
|
||||
"recipient": "#unified-alerting-test-but-updated"
|
||||
},
|
||||
"secureFields": {
|
||||
"url": true
|
||||
},
|
||||
"type": "slack",
|
||||
"name": "slack.receiver",
|
||||
"disableResolveMessage": false,
|
||||
"uid": "invalid"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
resp := postRequest(t, alertConfigURL, payload, http.StatusBadRequest) // nolint
|
||||
s := getBody(t, resp.Body)
|
||||
var res map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(s), &res))
|
||||
require.Equal(t, "unknown receiver: invalid", res["message"])
|
||||
}
|
||||
|
||||
// The secure settings must be present
|
||||
{
|
||||
resp := getRequest(t, alertConfigURL, http.StatusOK) // nolint
|
||||
var c apimodels.GettableUserConfig
|
||||
bb := getBody(t, resp.Body)
|
||||
err := json.Unmarshal([]byte(bb), &c)
|
||||
require.NoError(t, err)
|
||||
m := c.GetGrafanaReceiverMap()
|
||||
assert.Len(t, m, 1)
|
||||
for k := range m {
|
||||
generatedUID = m[k].UID
|
||||
}
|
||||
|
||||
// Then, update the recipient
|
||||
payload := fmt.Sprintf(`
|
||||
{
|
||||
"template_files": {},
|
||||
"alertmanager_config": {
|
||||
"route": {
|
||||
"receiver": "slack.receiver"
|
||||
},
|
||||
"receivers": [{
|
||||
"name": "slack.receiver",
|
||||
"grafana_managed_receiver_configs": [{
|
||||
"settings": {
|
||||
"recipient": "#unified-alerting-test-but-updated"
|
||||
},
|
||||
"secureFields": {
|
||||
"url": true
|
||||
},
|
||||
"type": "slack",
|
||||
"name": "slack.receiver",
|
||||
"disableResolveMessage": false,
|
||||
"uid": %q
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
`, generatedUID)
|
||||
|
||||
resp = postRequest(t, alertConfigURL, payload, http.StatusAccepted) // nolint
|
||||
require.JSONEq(t, `{"message": "configuration created"}`, getBody(t, resp.Body))
|
||||
}
|
||||
|
||||
// The secure settings must be present
|
||||
{
|
||||
resp := getRequest(t, alertConfigURL, http.StatusOK) // nolint
|
||||
require.JSONEq(t, fmt.Sprintf(`
|
||||
{
|
||||
"template_files": {},
|
||||
"alertmanager_config": {
|
||||
"route": {
|
||||
"receiver": "slack.receiver"
|
||||
},
|
||||
"receivers": [{
|
||||
"name": "slack.receiver",
|
||||
"grafana_managed_receiver_configs": [{
|
||||
"uid": %q,
|
||||
"name": "slack.receiver",
|
||||
"type": "slack",
|
||||
"disableResolveMessage": false,
|
||||
"settings": {
|
||||
"recipient": "#unified-alerting-test-but-updated"
|
||||
},
|
||||
"secureFields": {
|
||||
"url": true
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
`, generatedUID), getBody(t, resp.Body))
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package alerting
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -16,7 +17,6 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/grafana/grafana/pkg/apimachinery/errutil"
|
||||
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||
"github.com/grafana/grafana/pkg/services/org"
|
||||
"github.com/grafana/grafana/pkg/services/user"
|
||||
@@ -32,9 +32,6 @@ func TestIntegrationAMConfigAccess(t *testing.T) {
|
||||
EnableUnifiedAlerting: true,
|
||||
DisableAnonymous: true,
|
||||
AppModeProduction: true,
|
||||
DisableFeatureToggles: []string{
|
||||
featuremgmt.FlagAlertingApiServer,
|
||||
},
|
||||
})
|
||||
|
||||
grafanaListedAddr, env := testinfra.StartGrafanaEnv(t, dir, path)
|
||||
@@ -63,8 +60,9 @@ func TestIntegrationAMConfigAccess(t *testing.T) {
|
||||
expBody string
|
||||
}
|
||||
|
||||
t.Run("when creating alertmanager configuration", func(t *testing.T) {
|
||||
body := `
|
||||
// Create alertmanager config
|
||||
cfg := apimodels.PostableUserConfig{}
|
||||
amConfig := `
|
||||
{
|
||||
"alertmanager_config": {
|
||||
"route": {
|
||||
@@ -85,51 +83,10 @@ func TestIntegrationAMConfigAccess(t *testing.T) {
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
testCases := []testCase{
|
||||
{
|
||||
desc: "un-authenticated request should fail",
|
||||
url: "http://%s/api/alertmanager/grafana/config/api/v1/alerts",
|
||||
expStatus: http.StatusUnauthorized,
|
||||
expBody: `"message":"Unauthorized"`,
|
||||
},
|
||||
{
|
||||
desc: "viewer request should fail",
|
||||
url: "http://viewer:viewer@%s/api/alertmanager/grafana/config/api/v1/alerts",
|
||||
expStatus: http.StatusForbidden,
|
||||
expBody: `"title":"Access denied"`,
|
||||
},
|
||||
{
|
||||
desc: "editor request should succeed",
|
||||
url: "http://editor:editor@%s/api/alertmanager/grafana/config/api/v1/alerts",
|
||||
expStatus: http.StatusAccepted,
|
||||
expBody: `{"message":"configuration created"}`,
|
||||
},
|
||||
{
|
||||
desc: "admin request should succeed",
|
||||
url: "http://admin:admin@%s/api/alertmanager/grafana/config/api/v1/alerts",
|
||||
expStatus: http.StatusAccepted,
|
||||
expBody: `{"message":"configuration created"}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
url := fmt.Sprintf(tc.url, grafanaListedAddr)
|
||||
buf := bytes.NewReader([]byte(body))
|
||||
// nolint:gosec
|
||||
resp, err := http.Post(url, "application/json", buf)
|
||||
t.Cleanup(func() {
|
||||
require.NoError(t, resp.Body.Close())
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.expStatus, resp.StatusCode)
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(b), tc.expBody)
|
||||
})
|
||||
}
|
||||
})
|
||||
err := json.Unmarshal([]byte(amConfig), &cfg)
|
||||
require.NoError(t, err)
|
||||
err = env.Server.HTTPServer.AlertNG.MultiOrgAlertmanager.SaveAndApplyAlertmanagerConfiguration(context.Background(), 1, cfg)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("when retrieve alertmanager configuration", func(t *testing.T) {
|
||||
cfgTemplate := `
|
||||
@@ -329,7 +286,7 @@ func TestIntegrationAMConfigAccess(t *testing.T) {
|
||||
})
|
||||
|
||||
var silences apimodels.GettableSilences
|
||||
err := json.Unmarshal(blob, &silences)
|
||||
err = json.Unmarshal(blob, &silences)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, silences, 2)
|
||||
silenceIDs := make([]string, 0, len(silences))
|
||||
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/grafana/grafana/pkg/expr"
|
||||
"github.com/grafana/grafana/pkg/services/ngalert/notifier"
|
||||
"github.com/grafana/grafana/pkg/util"
|
||||
|
||||
"github.com/grafana/grafana/pkg/infra/db"
|
||||
@@ -249,112 +248,6 @@ func TestIntegrationTestReceivers(t *testing.T) {
|
||||
require.JSONEq(t, expectedJSON, string(b))
|
||||
})
|
||||
|
||||
t.Run("assert working receiver with existing secure settings returns OK", func(t *testing.T) {
|
||||
// Setup Grafana and its Database
|
||||
dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{
|
||||
DisableLegacyAlerting: true,
|
||||
EnableUnifiedAlerting: true,
|
||||
AppModeProduction: true,
|
||||
})
|
||||
|
||||
grafanaListedAddr, env := testinfra.StartGrafanaEnv(t, dir, path)
|
||||
|
||||
createUser(t, env.SQLStore, env.Cfg, user.CreateUserCommand{
|
||||
DefaultOrgRole: string(org.RoleEditor),
|
||||
Login: "grafana",
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
mockChannel := newMockNotificationChannel(t, grafanaListedAddr)
|
||||
amConfig := createAlertmanagerConfig(`{
|
||||
"alertmanager_config": {
|
||||
"route": {
|
||||
"receiver": "receiver-1"
|
||||
},
|
||||
"receivers": [{
|
||||
"name":"receiver-1",
|
||||
"grafana_managed_receiver_configs": [
|
||||
{
|
||||
"uid": "",
|
||||
"name": "receiver-1",
|
||||
"type": "slack",
|
||||
"disableResolveMessage": false,
|
||||
"settings": {},
|
||||
"secureSettings": {"url": "http://CHANNEL_ADDR/slack_recv1/slack_test_without_token"}
|
||||
}
|
||||
]
|
||||
}]
|
||||
}
|
||||
}`, mockChannel.server.Addr)
|
||||
|
||||
// Set up responses
|
||||
mockChannel.responses["slack_recv1"] = `{"ok": true}`
|
||||
|
||||
// Post config
|
||||
u := fmt.Sprintf("http://grafana:password@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
|
||||
_ = postRequest(t, u, amConfig, http.StatusAccepted) // nolint
|
||||
|
||||
// Get am config with UID and without secureSettings
|
||||
resp := getRequest(t, u, http.StatusOK)
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
config, err := notifier.Load(b)
|
||||
require.NoError(t, err)
|
||||
body, err := json.Marshal(apimodels.TestReceiversConfigBodyParams{
|
||||
Receivers: config.AlertmanagerConfig.Receivers,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Test using the am config without secureSettings
|
||||
testReceiversURL := fmt.Sprintf("http://grafana:password@%s/api/alertmanager/grafana/config/api/v1/receivers/test", grafanaListedAddr)
|
||||
// nolint
|
||||
resp = postRequest(t, testReceiversURL, string(body), http.StatusOK)
|
||||
t.Cleanup(func() {
|
||||
err := resp.Body.Close()
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
b, err = io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result apimodels.TestReceiversResult
|
||||
require.NoError(t, json.Unmarshal(b, &result))
|
||||
require.Len(t, result.Receivers, 1)
|
||||
require.Len(t, result.Receivers[0].Configs, 1)
|
||||
|
||||
expectedJSON := fmt.Sprintf(`{
|
||||
"alert": {
|
||||
"annotations": {
|
||||
"summary": "Notification test",
|
||||
"__dashboardUid__": "dashboard_uid",
|
||||
"__orgId__": "1",
|
||||
"__panelId__": "1",
|
||||
"__value_string__": "[ var='B' labels={__name__=go_threads, instance=host.docker.internal:3000, job=grafana} value=22 ], [ var='C' labels={__name__=go_threads, instance=host.docker.internal:3000, job=grafana} value=1 ]",
|
||||
"__values__": "{\"B\":22,\"C\":1}"
|
||||
},
|
||||
"labels": {
|
||||
"alertname": "TestAlert",
|
||||
"grafana_folder": "Test Folder",
|
||||
"instance": "Grafana"
|
||||
}
|
||||
},
|
||||
"receivers": [{
|
||||
"name":"receiver-1",
|
||||
"grafana_managed_receiver_configs": [
|
||||
{
|
||||
"name": "receiver-1",
|
||||
"uid": "%s",
|
||||
"status": "ok"
|
||||
}
|
||||
]
|
||||
}],
|
||||
"notified_at": "%s"
|
||||
}`,
|
||||
result.Receivers[0].Configs[0].UID,
|
||||
result.NotifiedAt.Format(time.RFC3339Nano))
|
||||
require.JSONEq(t, expectedJSON, string(b))
|
||||
})
|
||||
|
||||
t.Run("assert invalid receiver returns 400 Bad Request", func(t *testing.T) {
|
||||
// Setup Grafana and its Database
|
||||
dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{
|
||||
@@ -1008,8 +901,11 @@ func TestIntegrationNotificationChannels(t *testing.T) {
|
||||
apiClient.CreateFolder(t, "default", "default")
|
||||
|
||||
// Post the alertmanager config.
|
||||
u := fmt.Sprintf("http://grafana:password@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
|
||||
_ = postRequest(t, u, amConfig, http.StatusAccepted) // nolint
|
||||
cfg := apimodels.PostableUserConfig{}
|
||||
err := json.Unmarshal([]byte(amConfig), &cfg)
|
||||
require.NoError(t, err)
|
||||
err = env.Server.HTTPServer.AlertNG.MultiOrgAlertmanager.SaveAndApplyAlertmanagerConfiguration(context.Background(), 1, cfg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verifying that all the receivers and routes have been registered.
|
||||
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
|
||||
@@ -1025,7 +921,7 @@ func TestIntegrationNotificationChannels(t *testing.T) {
|
||||
b = getBody(t, resp.Body)
|
||||
|
||||
var receivers []apimodels.Receiver
|
||||
err := json.Unmarshal([]byte(b), &receivers)
|
||||
err = json.Unmarshal([]byte(b), &receivers)
|
||||
require.NoError(t, err)
|
||||
for _, rcv := range receivers {
|
||||
require.NotNil(t, rcv.Name)
|
||||
|
||||
@@ -3288,7 +3288,7 @@ func TestIntegrationAlertRuleCRUD(t *testing.T) {
|
||||
"intervalSeconds":60,
|
||||
"is_paused": false,
|
||||
"version":1,
|
||||
"uid":"uid",
|
||||
"uid":"uid",
|
||||
"guid": "guid",
|
||||
"namespace_uid":"nsuid",
|
||||
"rule_group":"arulegroup",
|
||||
@@ -4451,32 +4451,6 @@ func TestIntegrationRuleNotificationSettings(t *testing.T) {
|
||||
t.Log(body)
|
||||
})
|
||||
|
||||
t.Run("create with '...' groupBy followed by config post should succeed", func(t *testing.T) {
|
||||
var copyD testData
|
||||
err = json.Unmarshal(testDataRaw, ©D)
|
||||
group := copyD.RuleGroup
|
||||
ns := group.Rules[0].GrafanaManagedAlert.NotificationSettings
|
||||
ns.GroupBy = []string{ngmodels.FolderTitleLabel, model.AlertNameLabel, ngmodels.GroupByAll}
|
||||
|
||||
_, status, body := apiClient.PostRulesGroupWithStatus(t, folder, &group, false)
|
||||
require.Equalf(t, http.StatusAccepted, status, body)
|
||||
|
||||
// Now update the config with no changes.
|
||||
_, status, body = apiClient.GetAlertmanagerConfigWithStatus(t)
|
||||
if !assert.Equalf(t, http.StatusOK, status, body) {
|
||||
return
|
||||
}
|
||||
|
||||
cfg := apimodels.PostableUserConfig{}
|
||||
|
||||
err = json.Unmarshal([]byte(body), &cfg)
|
||||
require.NoError(t, err)
|
||||
|
||||
ok, err := apiClient.PostConfiguration(t, cfg)
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("should create rule and generate route", func(t *testing.T) {
|
||||
_, status, body := apiClient.PostRulesGroupWithStatus(t, folder, &d.RuleGroup, false)
|
||||
require.Equalf(t, http.StatusAccepted, status, body)
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -420,40 +419,6 @@ func (a apiClient) UpdateAlertRuleOrgQuota(t *testing.T, orgID int64, limit int6
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
func (a apiClient) PostConfiguration(t *testing.T, c apimodels.PostableUserConfig) (bool, error) {
|
||||
t.Helper()
|
||||
|
||||
b, err := json.Marshal(c)
|
||||
require.NoError(t, err)
|
||||
|
||||
u := fmt.Sprintf("%s/api/alertmanager/grafana/config/api/v1/alerts", a.url)
|
||||
req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(b))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp)
|
||||
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
b, err = io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
data := struct {
|
||||
Message string `json:"message"`
|
||||
}{}
|
||||
require.NoError(t, json.Unmarshal(b, &data))
|
||||
|
||||
if resp.StatusCode == http.StatusAccepted {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, errors.New(data.Message)
|
||||
}
|
||||
|
||||
func (a apiClient) PostRulesGroupWithStatus(t *testing.T, folder string, group *apimodels.PostableRuleGroupConfig, permanentlyDelete bool) (apimodels.UpdateRuleGroupResponse, int, string) {
|
||||
t.Helper()
|
||||
buf := bytes.Buffer{}
|
||||
|
||||
Reference in New Issue
Block a user