Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

chore: store v2 config for notification channels in db (#12984)

Naman Vermae4cd8dbf10fc
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index 7c366ac060..e146a5f3ac 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -184,6 +184,7 @@ components:
headers:
additionalProperties:
type: string
+ nullable: true
type: object
html:
type: string
@@ -217,6 +218,7 @@ components:
metadata:
additionalProperties:
type: string
+ nullable: true
type: object
sendResolved:
nullable: true
@@ -258,6 +260,7 @@ components:
type: string
customFields:
additionalProperties: {}
+ nullable: true
type: object
description:
type: string
@@ -268,6 +271,7 @@ components:
labels:
items:
type: string
+ nullable: true
type: array
priority:
type: string
@@ -346,6 +350,7 @@ components:
details:
additionalProperties:
type: string
+ nullable: true
type: object
message:
type: string
@@ -374,6 +379,7 @@ components:
details:
additionalProperties:
type: string
+ nullable: true
type: object
group:
type: string
@@ -451,6 +457,7 @@ components:
actions:
items:
$ref: '#/components/schemas/AlertmanagertypesChannelSlackAction'
+ nullable: true
type: array
apiUrl:
format: password
@@ -464,6 +471,7 @@ components:
fields:
items:
$ref: '#/components/schemas/AlertmanagertypesChannelSlackField'
+ nullable: true
type: array
footer:
type: string
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index 80fbb0453f..93b798f16f 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -104,9 +104,9 @@ export interface AlertmanagertypesChannelSlackFieldDTO {
export interface AlertmanagertypesChannelSlackConfigDTO {
/**
- * @type array
+ * @type array,null
*/
- actions?: AlertmanagertypesChannelSlackActionDTO[];
+ actions?: AlertmanagertypesChannelSlackActionDTO[] | null;
/**
* @type string
* @format password
@@ -125,9 +125,9 @@ export interface AlertmanagertypesChannelSlackConfigDTO {
*/
fallback?: string;
/**
- * @type array
+ * @type array,null
*/
- fields?: AlertmanagertypesChannelSlackFieldDTO[];
+ fields?: AlertmanagertypesChannelSlackFieldDTO[] | null;
/**
* @type string
*/
@@ -166,13 +166,19 @@ export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTy
export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelEmailConfigDTOKind {
email = 'email',
}
-export type AlertmanagertypesChannelEmailConfigDTOHeaders = {
+export type AlertmanagertypesChannelEmailConfigDTOHeadersAnyOf = {
[key: string]: string;
};
+/**
+ * @nullable
+ */
+export type AlertmanagertypesChannelEmailConfigDTOHeaders =
+ AlertmanagertypesChannelEmailConfigDTOHeadersAnyOf | null;
+
export interface AlertmanagertypesChannelEmailConfigDTO {
/**
- * @type object
+ * @type object,null
*/
headers?: AlertmanagertypesChannelEmailConfigDTOHeaders;
/**
@@ -239,10 +245,16 @@ export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTy
export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelPagerdutyConfigDTOKind {
pagerduty = 'pagerduty',
}
-export type AlertmanagertypesChannelPagerdutyConfigDTODetails = {
+export type AlertmanagertypesChannelPagerdutyConfigDTODetailsAnyOf = {
[key: string]: string;
};
+/**
+ * @nullable
+ */
+export type AlertmanagertypesChannelPagerdutyConfigDTODetails =
+ AlertmanagertypesChannelPagerdutyConfigDTODetailsAnyOf | null;
+
export interface AlertmanagertypesChannelPagerdutyConfigDTO {
/**
* @type string
@@ -265,7 +277,7 @@ export interface AlertmanagertypesChannelPagerdutyConfigDTO {
*/
description?: string;
/**
- * @type object
+ * @type object,null
*/
details?: AlertmanagertypesChannelPagerdutyConfigDTODetails;
/**
@@ -307,10 +319,16 @@ export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTy
export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelOpsgenieConfigDTOKind {
opsgenie = 'opsgenie',
}
-export type AlertmanagertypesChannelOpsgenieConfigDTODetails = {
+export type AlertmanagertypesChannelOpsgenieConfigDTODetailsAnyOf = {
[key: string]: string;
};
+/**
+ * @nullable
+ */
+export type AlertmanagertypesChannelOpsgenieConfigDTODetails =
+ AlertmanagertypesChannelOpsgenieConfigDTODetailsAnyOf | null;
+
export interface AlertmanagertypesChannelOpsgenieConfigDTO {
/**
* @type string
@@ -326,7 +344,7 @@ export interface AlertmanagertypesChannelOpsgenieConfigDTO {
*/
description?: string;
/**
- * @type object
+ * @type object,null
*/
details?: AlertmanagertypesChannelOpsgenieConfigDTODetails;
/**
@@ -423,10 +441,16 @@ export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTy
export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfigDTOKind {
jira = 'jira',
}
-export type AlertmanagertypesChannelJiraConfigDTOCustomFields = {
+export type AlertmanagertypesChannelJiraConfigDTOCustomFieldsAnyOf = {
[key: string]: unknown;
};
+/**
+ * @nullable
+ */
+export type AlertmanagertypesChannelJiraConfigDTOCustomFields =
+ AlertmanagertypesChannelJiraConfigDTOCustomFieldsAnyOf | null;
+
export interface AlertmanagertypesChannelJiraConfigDTO {
/**
* @type string
@@ -434,7 +458,7 @@ export interface AlertmanagertypesChannelJiraConfigDTO {
*/
apiToken: string;
/**
- * @type object
+ * @type object,null
*/
customFields?: AlertmanagertypesChannelJiraConfigDTOCustomFields;
/**
@@ -450,9 +474,9 @@ export interface AlertmanagertypesChannelJiraConfigDTO {
*/
issueType: string;
/**
- * @type array
+ * @type array,null
*/
- labels?: string[];
+ labels?: string[] | null;
/**
* @type string
*/
@@ -543,17 +567,23 @@ export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTy
export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelIncidentIOConfigDTOKind {
incidentio = 'incidentio',
}
-export type AlertmanagertypesChannelIncidentIOConfigDTOMetadata = {
+export type AlertmanagertypesChannelIncidentIOConfigDTOMetadataAnyOf = {
[key: string]: string;
};
+/**
+ * @nullable
+ */
+export type AlertmanagertypesChannelIncidentIOConfigDTOMetadata =
+ AlertmanagertypesChannelIncidentIOConfigDTOMetadataAnyOf | null;
+
export interface AlertmanagertypesChannelIncidentIOConfigDTO {
/**
* @type string
*/
description?: string;
/**
- * @type object
+ * @type object,null
*/
metadata?: AlertmanagertypesChannelIncidentIOConfigDTOMetadata;
/**
diff --git a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/config.go b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/config.go
index dcdea607c1..203202119b 100644
--- a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/config.go
+++ b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/config.go
@@ -187,7 +187,7 @@ func (store *config) ListChannels(ctx context.Context, orgID string, params *ale
}
if !params.Kind.IsZero() {
- q = q.Where("type = ?", params.Kind.ToStoredType())
+ q = q.Where("type = ?", params.Kind.StringValue())
}
q = q.
diff --git a/pkg/alertmanager/signozalertmanager/handler.go b/pkg/alertmanager/signozalertmanager/handler.go
index 000b04cf1d..16061a4de3 100644
--- a/pkg/alertmanager/signozalertmanager/handler.go
+++ b/pkg/alertmanager/signozalertmanager/handler.go
@@ -98,11 +98,12 @@ func (handler *handler) ListChannels(rw http.ResponseWriter, req *http.Request)
}
// This ensures that the UI receives an empty array instead of null
- if len(channels) == 0 {
- channels = make([]*alertmanagertypes.Channel, 0)
+ v1Channels := make([]*alertmanagertypes.Channel, 0, len(channels))
+ for _, channel := range channels {
+ v1Channels = append(v1Channels, channel.ToV1Channel())
}
- render.Success(rw, http.StatusOK, channels)
+ render.Success(rw, http.StatusOK, v1Channels)
}
func (handler *handler) ListAllChannels(rw http.ResponseWriter, req *http.Request) {
@@ -152,7 +153,7 @@ func (handler *handler) GetChannelByID(rw http.ResponseWriter, req *http.Request
return
}
- render.Success(rw, http.StatusOK, channel)
+ render.Success(rw, http.StatusOK, channel.ToV1Channel())
}
func (handler *handler) UpdateChannelByID(rw http.ResponseWriter, req *http.Request) {
@@ -272,7 +273,7 @@ func (handler *handler) CreateChannel(rw http.ResponseWriter, req *http.Request)
return
}
- render.Success(rw, http.StatusCreated, channel)
+ render.Success(rw, http.StatusCreated, channel.ToV1Channel())
}
func (handler *handler) CreateRoutePolicy(rw http.ResponseWriter, req *http.Request) {
diff --git a/pkg/alertmanager/signozalertmanager/provider.go b/pkg/alertmanager/signozalertmanager/provider.go
index 5f4d399b3a..a93e7059f2 100644
--- a/pkg/alertmanager/signozalertmanager/provider.go
+++ b/pkg/alertmanager/signozalertmanager/provider.go
@@ -262,7 +262,7 @@ func (provider *provider) CreateChannel(ctx context.Context, orgID string, recei
}
func (provider *provider) CreateNotificationChannel(ctx context.Context, orgID string, postable alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error) {
- receiver, err := postable.ToReceiver()
+ channel, receiver, err := postable.ToChannel(orgID)
if err != nil {
return nil, err
}
@@ -280,11 +280,6 @@ func (provider *provider) CreateNotificationChannel(ctx context.Context, orgID s
return nil, err
}
- channel, err := alertmanagertypes.NewChannelFromReceiverWithName(receiver, postable.Name, orgID)
- if err != nil {
- return nil, err
- }
-
err = provider.configStore.CreateChannel(ctx, channel, alertmanagertypes.WithCb(func(ctx context.Context) error {
return provider.configStore.Set(ctx, config)
}))
@@ -304,15 +299,11 @@ func (provider *provider) UpdateNotificationChannel(ctx context.Context, orgID s
return nil, err
}
- receiver, err := updatable.ToReceiver(channel.DisplayName)
+ receiver, err := channel.UpdateFromUpdatable(updatable)
if err != nil {
return nil, err
}
- if err := channel.Update(receiver); err != nil {
- return nil, err
- }
-
config, err := provider.configStore.Get(ctx, orgID)
if err != nil {
return nil, err
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index c000abd80d..362edc74d0 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -257,6 +257,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewAddCloudIntegrationTuplesFactory(sqlstore),
sqlmigration.NewAddNotificationChannelTuplesFactory(sqlstore),
sqlmigration.NewAddAIObservabilityQuickFiltersFactory(sqlstore),
+ sqlmigration.NewAddChannelSpecFactory(sqlschema),
)
}
diff --git a/pkg/sqlmigration/131_add_channel_config.go b/pkg/sqlmigration/131_add_channel_config.go
new file mode 100644
index 0000000000..ff90f9c98b
--- /dev/null
+++ b/pkg/sqlmigration/131_add_channel_config.go
@@ -0,0 +1,737 @@
+package sqlmigration
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "maps"
+ "slices"
+ "strings"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/sqlschema"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/migrate"
+)
+
+var channelSpecBackfillKinds = []channelSpecBackfillKind{
+ {kind: "slack", configsKey: "slack_configs", convert: convertSlackNotifierJSON},
+ {kind: "email", configsKey: "email_configs", convert: convertEmailNotifierJSON},
+ {kind: "webhook", configsKey: "webhook_configs", convert: convertWebhookNotifierJSON},
+ {kind: "pagerduty", configsKey: "pagerduty_configs", convert: convertPagerdutyNotifierJSON},
+ {kind: "opsgenie", configsKey: "opsgenie_configs", convert: convertOpsgenieNotifierJSON},
+ {kind: "msteams", configsKey: "msteamsv2_configs", convert: convertMSTeamsNotifierJSON},
+ {kind: "googlechat", configsKey: "googlechat_configs", convert: convertGoogleChatNotifierJSON},
+ {kind: "jira", configsKey: "jira_configs", convert: convertJiraNotifierJSON},
+ {kind: "jsmops", configsKey: "jsmops_configs", convert: convertJSMOpsNotifierJSON},
+ {kind: "incidentio", configsKey: "incidentio_configs", convert: convertIncidentIONotifierJSON},
+}
+
+func NewAddChannelSpecFactory(sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(
+ factory.MustNewName("add_channel_spec"),
+ func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
+ return &addChannelSpec{sqlschema: sqlschema, logger: ps.Logger}, nil
+ },
+ )
+}
+
+func (migration *addChannelSpec) Register(migrations *migrate.Migrations) error {
+ return migrations.Register(migration.Up, migration.Down)
+}
+
+// Up adds the column and fills it from each channel's receiver, as a write
+// through a receiver does, pinning type to the kind the spec came from because
+// a read decodes the spec under it. The msteams kind, which v1 stored as
+// msteamsv2 after upstream's configs list, is renamed on every row. A receiver
+// v2 cannot represent, such as one carrying several notifiers or a notifier
+// kind v2 does not model, stays NULL and is logged; the repair endpoint is the
+// remedy for those.
+func (migration *addChannelSpec) Up(ctx context.Context, db *bun.DB) error {
+ table, uniqueConstraints, err := migration.sqlschema.GetTable(ctx, sqlschema.TableName("notification_channel"))
+ if err != nil {
+ return err
+ }
+
+ sqls := migration.sqlschema.Operator().AddColumn(table, uniqueConstraints, &sqlschema.Column{
+ Name: sqlschema.ColumnName("spec"),
+ DataType: sqlschema.DataTypeText,
+ Nullable: true,
+ }, nil)
+
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ _ = tx.Rollback()
+ }()
+
+ for _, sql := range sqls {
+ if _, err := tx.ExecContext(ctx, string(sql)); err != nil {
+ return err
+ }
+ }
+
+ if _, err := tx.NewUpdate().Model((*channelSpecBackfillRow)(nil)).Set("type = ?", "msteams").Where("type = ?", "msteamsv2").Exec(ctx); err != nil {
+ return err
+ }
+
+ rows := make([]*channelSpecBackfillRow, 0)
+ if err := tx.NewSelect().Model(&rows).Where("spec IS NULL").OrderExpr("org_id, id").Scan(ctx); err != nil {
+ return err
+ }
+
+ type orgStats struct{ total, filled, unrepresentable int }
+ statsByOrg := map[string]*orgStats{}
+ for _, row := range rows {
+ stats, ok := statsByOrg[row.OrgID]
+ if !ok {
+ stats = &orgStats{}
+ statsByOrg[row.OrgID] = stats
+ }
+ stats.total++
+
+ storedType, spec, err := channelSpecFromReceiverJSON(row.Data)
+ if err != nil {
+ stats.unrepresentable++
+ migration.logger.WarnContext(ctx, "leaving notification channel without a v2 spec", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
+ continue
+ }
+
+ encoded, err := marshalUnescaped(spec)
+ if err != nil {
+ return err
+ }
+
+ if _, err := tx.NewUpdate().
+ Model((*channelSpecBackfillRow)(nil)).
+ Set("spec = ?", string(encoded)).
+ Set("type = ?", storedType).
+ Where("id = ?", row.ID).
+ Exec(ctx); err != nil {
+ return err
+ }
+ stats.filled++
+ }
+
+ for _, orgID := range slices.Sorted(maps.Keys(statsByOrg)) {
+ stats := statsByOrg[orgID]
+ migration.logger.InfoContext(ctx, "filled v2 spec on notification channels", slog.String("org_id", orgID), slog.Int("total", stats.total), slog.Int("filled", stats.filled), slog.Int("unrepresentable", stats.unrepresentable))
+ }
+
+ return tx.Commit()
+}
+
+func (migration *addChannelSpec) Down(context.Context, *bun.DB) error {
+ return nil
+}
+
+type addChannelSpec struct {
+ sqlschema sqlschema.SQLSchema
+ logger *slog.Logger
+}
+
+type channelSpecBackfillRow struct {
+ bun.BaseModel `bun:"table:notification_channel"`
+
+ ID string `bun:"id,pk"`
+ OrgID string `bun:"org_id"`
+ Data string `bun:"data"`
+}
+
+// notifierJSON is one entry of a receiver's *_configs list as stored in
+// notification_channel.data.
+type notifierJSON map[string]json.RawMessage
+
+type channelSpecBackfillKind struct {
+ kind string
+ configsKey string
+ convert func(notifierJSON) (map[string]any, error)
+}
+
+// channelSpecFromReceiverJSON mirrors the v2 read of a stored receiver: one
+// notifier of a modelled kind, with the receiver's field names renamed to the
+// spec's and its unset templates left out. The type alongside is what a read
+// decodes the spec under.
+func channelSpecFromReceiverJSON(data string) (string, map[string]any, error) {
+ receiver := map[string]json.RawMessage{}
+ if err := json.Unmarshal([]byte(data), &receiver); err != nil {
+ return "", nil, err
+ }
+
+ total := 0
+ var found *channelSpecBackfillKind
+ var notifier notifierJSON
+ for key, raw := range receiver {
+ if !strings.HasSuffix(key, "_configs") {
+ continue
+ }
+
+ var list []notifierJSON
+ if err := json.Unmarshal(raw, &list); err != nil {
+ return "", nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "%s", key)
+ }
+ total += len(list)
+ if len(list) == 0 {
+ continue
+ }
+
+ for i := range channelSpecBackfillKinds {
+ if channelSpecBackfillKinds[i].configsKey == key {
+ found = &channelSpecBackfillKinds[i]
+ notifier = list[0]
+ }
+ }
+ }
+
+ if total > 1 {
+ return "", nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "carries %d notifier configurations; only one per channel is supported", total)
+ }
+ if found == nil {
+ return "", nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "carries no supported notifier configuration")
+ }
+
+ spec, err := found.convert(notifier)
+ if err != nil {
+ return "", nil, err
+ }
+
+ sendResolved, err := notifier.boolValue("send_resolved")
+ if err != nil {
+ return "", nil, err
+ }
+ spec["sendResolved"] = sendResolved
+
+ return found.kind, spec, nil
+}
+
+func convertSlackNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ if err := rejectAnyHTTPAuthJSON(notifier); err != nil {
+ return nil, err
+ }
+
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"api_url": "apiUrl", "channel": "channel"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyStrings(spec, map[string]string{"title": "title", "text": "text", "color": "color", "title_link": "titleLink", "pretext": "pretext", "fallback": "fallback", "footer": "footer"}); err != nil {
+ return nil, err
+ }
+ if spec["apiUrl"] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "slack: api_url is required")
+ }
+
+ fields, err := notifier.objectList("fields")
+ if err != nil {
+ return nil, err
+ }
+ if len(fields) > 0 {
+ converted := make([]map[string]any, 0, len(fields))
+ for _, field := range fields {
+ item := map[string]any{}
+ if err := field.copyStrings(item, map[string]string{"title": "title", "value": "value"}); err != nil {
+ return nil, err
+ }
+ if field.has("short") {
+ short, err := field.boolValue("short")
+ if err != nil {
+ return nil, err
+ }
+ item["short"] = short
+ }
+ converted = append(converted, item)
+ }
+ spec["fields"] = converted
+ }
+
+ actions, err := notifier.objectList("actions")
+ if err != nil {
+ return nil, err
+ }
+ if len(actions) > 0 {
+ converted := make([]map[string]any, 0, len(actions))
+ for _, action := range actions {
+ item := map[string]any{}
+ if err := action.copyStrings(item, map[string]string{"type": "type", "text": "text", "url": "url", "style": "style", "name": "name", "value": "value"}); err != nil {
+ return nil, err
+ }
+ if action.has("confirm") {
+ confirm, err := action.object("confirm")
+ if err != nil {
+ return nil, err
+ }
+ confirmation := map[string]any{}
+ if err := confirm.copyStrings(confirmation, map[string]string{"text": "text", "title": "title", "ok_text": "okText", "dismiss_text": "dismissText"}); err != nil {
+ return nil, err
+ }
+ item["confirm"] = confirmation
+ }
+ converted = append(converted, item)
+ }
+ spec["actions"] = converted
+ }
+
+ return spec, nil
+}
+
+func convertEmailNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"to": "to"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyStrings(spec, map[string]string{"html": "html"}); err != nil {
+ return nil, err
+ }
+ if spec["to"] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "email: to is required")
+ }
+ if err := notifier.copyNonEmptyObjects(spec, map[string]string{"headers": "headers"}); err != nil {
+ return nil, err
+ }
+
+ return spec, nil
+}
+
+func convertWebhookNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"url": "url"}); err != nil {
+ return nil, err
+ }
+ if spec["url"] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "webhook: url is required")
+ }
+
+ if err := rejectUnsupportedHTTPConfigJSON(notifier); err != nil {
+ return nil, err
+ }
+ httpConfig, err := notifier.object("http_config")
+ if err != nil {
+ return nil, err
+ }
+
+ username, password, err := extractBasicAuthJSON(httpConfig)
+ if err != nil {
+ return nil, err
+ }
+ bearerToken, err := extractBearerTokenJSON(httpConfig)
+ if err != nil {
+ return nil, err
+ }
+ if (username != "" || password != "") && bearerToken != "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "webhook: basic auth and bearer token cannot be combined")
+ }
+ spec["username"], spec["password"], spec["bearerToken"] = username, password, bearerToken
+
+ return spec, nil
+}
+
+func convertPagerdutyNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ if err := rejectAnyHTTPAuthJSON(notifier); err != nil {
+ return nil, err
+ }
+
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"routing_key": "routingKey", "url": "url", "severity": "severity", "component": "component", "group": "group", "class": "class"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyStrings(spec, map[string]string{"source": "source", "client": "client", "client_url": "clientUrl", "description": "description"}); err != nil {
+ return nil, err
+ }
+ if spec["routingKey"] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "pagerduty: routing_key is required")
+ }
+
+ details, err := notifier.object("details")
+ if err != nil {
+ return nil, err
+ }
+ if len(details) > 0 {
+ for key, raw := range details {
+ var value string
+ if err := json.Unmarshal(raw, &value); err != nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "pagerduty: details.%s is not a string", key)
+ }
+ }
+ spec["details"] = notifier["details"]
+ }
+
+ return spec, nil
+}
+
+func convertOpsgenieNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ if err := rejectAnyHTTPAuthJSON(notifier); err != nil {
+ return nil, err
+ }
+
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"api_key": "apiKey", "api_url": "apiUrl", "priority": "priority"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyStrings(spec, map[string]string{"message": "message", "description": "description", "source": "source"}); err != nil {
+ return nil, err
+ }
+ if spec["apiKey"] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "opsgenie: api_key is required")
+ }
+ if err := notifier.copyNonEmptyObjects(spec, map[string]string{"details": "details"}); err != nil {
+ return nil, err
+ }
+
+ return spec, nil
+}
+
+func convertMSTeamsNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ return convertWebhookURLNotifierJSON("msteams", notifier)
+}
+
+func convertGoogleChatNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ return convertWebhookURLNotifierJSON("googlechat", notifier)
+}
+
+func convertWebhookURLNotifierJSON(name string, notifier notifierJSON) (map[string]any, error) {
+ if err := rejectAnyHTTPAuthJSON(notifier); err != nil {
+ return nil, err
+ }
+
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"webhook_url": "webhookUrl"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyStrings(spec, map[string]string{"title": "title", "text": "text"}); err != nil {
+ return nil, err
+ }
+ if spec["webhookUrl"] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "%s: webhook_url is required", name)
+ }
+
+ return spec, nil
+}
+
+func convertJiraNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"site": "site", "project": "project", "issue_type": "issueType", "priority": "priority", "resolve_transition": "resolveTransition", "reopen_transition": "reopenTransition", "wont_fix_resolution": "wontFixResolution"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyStrings(spec, map[string]string{"summary": "summary", "description": "description", "reopen_duration": "reopenDuration"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyObjects(spec, map[string]string{"custom_fields": "customFields"}); err != nil {
+ return nil, err
+ }
+
+ labels, err := notifier.list("labels")
+ if err != nil {
+ return nil, err
+ }
+ if len(labels) > 0 {
+ spec["labels"] = notifier["labels"]
+ }
+
+ if err := rejectUnsupportedHTTPConfigJSON(notifier); err != nil {
+ return nil, err
+ }
+ httpConfig, err := notifier.object("http_config")
+ if err != nil {
+ return nil, err
+ }
+ if httpConfig.has("authorization") {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "jira: http_config.authorization is not supported")
+ }
+ email, apiToken, err := extractBasicAuthJSON(httpConfig)
+ if err != nil {
+ return nil, err
+ }
+ spec["email"], spec["apiToken"] = email, apiToken
+
+ for _, required := range []string{"site", "project", "issueType", "email", "apiToken"} {
+ if spec[required] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "jira: %s is required", required)
+ }
+ }
+
+ return spec, nil
+}
+
+func convertJSMOpsNotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ if err := rejectAnyHTTPAuthJSON(notifier); err != nil {
+ return nil, err
+ }
+
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"api_key": "apiKey", "priority": "priority"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyStrings(spec, map[string]string{"message": "message", "description": "description", "tags": "tags"}); err != nil {
+ return nil, err
+ }
+ if spec["apiKey"] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "jsmops: api_key is required")
+ }
+
+ return spec, nil
+}
+
+func convertIncidentIONotifierJSON(notifier notifierJSON) (map[string]any, error) {
+ if err := rejectAnyHTTPAuthJSON(notifier); err != nil {
+ return nil, err
+ }
+
+ spec := map[string]any{}
+ if err := notifier.copyStrings(spec, map[string]string{"url": "url", "token": "token"}); err != nil {
+ return nil, err
+ }
+ if err := notifier.copyNonEmptyStrings(spec, map[string]string{"title": "title", "description": "description"}); err != nil {
+ return nil, err
+ }
+ if spec["url"] == "" || spec["token"] == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "incidentio: url and token are required")
+ }
+ if err := notifier.copyNonEmptyObjects(spec, map[string]string{"metadata": "metadata"}); err != nil {
+ return nil, err
+ }
+
+ return spec, nil
+}
+
+func rejectAnyHTTPAuthJSON(notifier notifierJSON) error {
+ httpConfig, err := notifier.object("http_config")
+ if err != nil {
+ return err
+ }
+ if httpConfig.has("basic_auth") {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.basic_auth is not supported")
+ }
+ if httpConfig.has("authorization") {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.authorization is not supported")
+ }
+
+ return rejectUnsupportedHTTPConfigJSON(notifier)
+}
+
+// rejectUnsupportedHTTPConfigJSON refuses every http_config setting the spec has
+// no field for, since a config that dropped it would unauthenticate or reroute
+// the channel on the next write. An absent follow_redirects or enable_http2 is
+// the upstream default, true; only an explicit false is refused.
+func rejectUnsupportedHTTPConfigJSON(notifier notifierJSON) error {
+ if !notifier.has("http_config") {
+ return nil
+ }
+ httpConfig, err := notifier.object("http_config")
+ if err != nil {
+ return err
+ }
+
+ for _, key := range []string{"oauth2", "http_headers"} {
+ if httpConfig.has(key) {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.%s is not supported", key)
+ }
+ }
+ for _, key := range []string{"bearer_token", "bearer_token_file", "proxy_url", "no_proxy"} {
+ value, err := httpConfig.stringValue(key)
+ if err != nil {
+ return err
+ }
+ if value != "" {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.%s is not supported", key)
+ }
+ }
+ if httpConfig.has("proxy_from_environment") {
+ fromEnvironment, err := httpConfig.boolValue("proxy_from_environment")
+ if err != nil {
+ return err
+ }
+ if fromEnvironment {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.proxy_from_environment is not supported")
+ }
+ }
+
+ tlsConfig, err := httpConfig.object("tls_config")
+ if err != nil {
+ return err
+ }
+ for key := range tlsConfig {
+ if key != "insecure_skip_verify" {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.tls_config is not supported")
+ }
+ }
+ if tlsConfig.has("insecure_skip_verify") {
+ insecure, err := tlsConfig.boolValue("insecure_skip_verify")
+ if err != nil {
+ return err
+ }
+ if insecure {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.tls_config is not supported")
+ }
+ }
+
+ for _, key := range []string{"follow_redirects", "enable_http2"} {
+ if !httpConfig.has(key) {
+ continue
+ }
+ enabled, err := httpConfig.boolValue(key)
+ if err != nil {
+ return err
+ }
+ if !enabled {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.%s cannot be disabled", key)
+ }
+ }
+
+ return nil
+}
+
+func extractBasicAuthJSON(httpConfig notifierJSON) (string, string, error) {
+ basicAuth, err := httpConfig.object("basic_auth")
+ if err != nil {
+ return "", "", err
+ }
+ if len(basicAuth) == 0 {
+ return "", "", nil
+ }
+
+ for key := range basicAuth {
+ if key != "username" && key != "password" {
+ return "", "", errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.basic_auth.%s is not supported", key)
+ }
+ }
+ username, err := basicAuth.stringValue("username")
+ if err != nil {
+ return "", "", err
+ }
+ password, err := basicAuth.stringValue("password")
+ if err != nil {
+ return "", "", err
+ }
+
+ return username, password, nil
+}
+
+func extractBearerTokenJSON(httpConfig notifierJSON) (string, error) {
+ if !httpConfig.has("authorization") {
+ return "", nil
+ }
+ authorization, err := httpConfig.object("authorization")
+ if err != nil {
+ return "", err
+ }
+
+ for key := range authorization {
+ if key != "type" && key != "credentials" {
+ return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.authorization.%s is not supported", key)
+ }
+ }
+ scheme, err := authorization.stringValue("type")
+ if err != nil {
+ return "", err
+ }
+ if !strings.EqualFold(scheme, "Bearer") {
+ return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "http_config.authorization.type %q is not supported", scheme)
+ }
+
+ return authorization.stringValue("credentials")
+}
+
+// has reports a key that is present and not null.
+func (n notifierJSON) has(key string) bool {
+ raw, ok := n[key]
+ return ok && string(raw) != "null"
+}
+
+func (n notifierJSON) stringValue(key string) (string, error) {
+ if !n.has(key) {
+ return "", nil
+ }
+ var value string
+ if err := json.Unmarshal(n[key], &value); err != nil {
+ return "", errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "%s", key)
+ }
+ return value, nil
+}
+
+func (n notifierJSON) boolValue(key string) (bool, error) {
+ if !n.has(key) {
+ return false, nil
+ }
+ var value bool
+ if err := json.Unmarshal(n[key], &value); err != nil {
+ return false, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "%s", key)
+ }
+ return value, nil
+}
+
+// object reads an absent key as an empty object; a caller that must tell the
+// two apart checks has first.
+func (n notifierJSON) object(key string) (notifierJSON, error) {
+ if !n.has(key) {
+ return notifierJSON{}, nil
+ }
+ value := notifierJSON{}
+ if err := json.Unmarshal(n[key], &value); err != nil {
+ return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "%s", key)
+ }
+ return value, nil
+}
+
+func (n notifierJSON) list(key string) ([]json.RawMessage, error) {
+ if !n.has(key) {
+ return nil, nil
+ }
+ var value []json.RawMessage
+ if err := json.Unmarshal(n[key], &value); err != nil {
+ return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "%s", key)
+ }
+ return value, nil
+}
+
+func (n notifierJSON) objectList(key string) ([]notifierJSON, error) {
+ if !n.has(key) {
+ return nil, nil
+ }
+ var value []notifierJSON
+ if err := json.Unmarshal(n[key], &value); err != nil {
+ return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "%s", key)
+ }
+ return value, nil
+}
+
+// copyStrings writes each field as the spec's plain string, "" when absent.
+func (n notifierJSON) copyStrings(spec map[string]any, keys map[string]string) error {
+ for from, to := range keys {
+ value, err := n.stringValue(from)
+ if err != nil {
+ return err
+ }
+ spec[to] = value
+ }
+ return nil
+}
+
+// copyNonEmptyStrings leaves an empty field out, which is how the spec spells
+// an unset template.
+func (n notifierJSON) copyNonEmptyStrings(spec map[string]any, keys map[string]string) error {
+ for from, to := range keys {
+ value, err := n.stringValue(from)
+ if err != nil {
+ return err
+ }
+ if value != "" {
+ spec[to] = value
+ }
+ }
+ return nil
+}
+
+func (n notifierJSON) copyNonEmptyObjects(spec map[string]any, keys map[string]string) error {
+ for from, to := range keys {
+ value, err := n.object(from)
+ if err != nil {
+ return err
+ }
+ if len(value) > 0 {
+ spec[to] = n[from]
+ }
+ }
+ return nil
+}
diff --git a/pkg/types/alertmanagertypes/channel.go b/pkg/types/alertmanagertypes/channel.go
index dd80bd339c..268d247a11 100644
--- a/pkg/types/alertmanagertypes/channel.go
+++ b/pkg/types/alertmanagertypes/channel.go
@@ -1,18 +1,14 @@
package alertmanagertypes
import (
+ "context"
"crypto/rand"
"encoding/json"
- "reflect"
"regexp"
"strings"
- "time"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types"
- "github.com/SigNoz/signoz/pkg/valuer"
- "github.com/prometheus/alertmanager/config"
- "github.com/swaggest/jsonschema-go"
"github.com/uptrace/bun"
)
@@ -30,20 +26,6 @@ var (
type Channels = []*Channel
-type GettableChannels = []*Channel
-
-// TODO: the oneOf emitted by JSONSchema is not the shape OpenAPI wants for a
-// discriminated union. OpenAPI's discriminator requires every oneOf branch to
-// be a $ref to a named component and a sibling property whose value selects
-// the variant. Our payload instead uses the *presence* of one of the 18
-// *_configs arrays to imply the type, so no discriminator can be attached.
-// Refactor PostableChannel into a {name, type, config} envelope (see
-// ruletypes.RuleThresholdData for the pattern) so each notification kind
-// becomes a named component and the discriminator can be wired up properly.
-type PostableChannel struct {
- Receiver
-}
-
// Channel represents a single receiver of the alertmanager config.
type Channel struct {
bun.BaseModel `bun:"table:notification_channel"`
@@ -55,45 +37,51 @@ type Channel struct {
// reference, so it keeps the v1 wire tag and Name stays off the v1 contract.
Name string `json:"-" bun:"name"`
DisplayName string `json:"name" required:"true" bun:"display_name"`
- Type string `json:"type" required:"true" bun:"type"`
- Data string `json:"data" required:"true" bun:"data"`
- OrgID string `json:"orgId" required:"true" bun:"org_id"`
+ // TODO: type this as ChannelKind once v1 is gone.
+ Type string `json:"type" required:"true" bun:"type"`
+ Data string `json:"data" required:"true" bun:"data"`
+ OrgID string `json:"orgId" required:"true" bun:"org_id"`
+
+ // Spec is the v2 spec a read returns, of the kind Type names. A v2 write
+ // stores it as the caller wrote it and a v1 write derives it from the
+ // defaulted receiver. Only a row the migration could not backfill has none.
+ // StoredSpec is the column, written by fillSpec and decoded by AfterScanRow.
+ Spec ChannelSpec `json:"-" bun:"-"`
+ StoredSpec string `json:"-" bun:"spec,type:text,nullzero"`
}
-// NewChannelFromReceiver creates a new Channel from a Receiver.
-// It can return nil if the receiver is the default receiver.
-// A receiver carries no internal name, so one is generated from its name.
-func NewChannelFromReceiver(receiver *Receiver, orgID string) (*Channel, error) {
- if receiver.Name == DefaultReceiverName {
- return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeAlertmanagerChannelInvalid, "cannot use %s name as a channel name", receiver.Name)
+var _ bun.AfterScanRowHook = (*Channel)(nil)
+
+// AfterScanRow decodes the stored spec under Type, which bun cannot do column by
+// column because the spec's Go type depends on it.
+func (c *Channel) AfterScanRow(context.Context) error {
+ if c.StoredSpec == "" {
+ c.Spec = nil
+ return nil
}
- // Initialize channel with common fields
- channel := Channel{
- Identifiable: types.Identifiable{
- ID: valuer.GenerateUUID(),
- },
- TimeAuditable: types.TimeAuditable{
- CreatedAt: time.Now(),
- UpdatedAt: time.Now(),
- },
- Name: generateChannelName(receiver.Name),
- DisplayName: receiver.Name,
- OrgID: orgID,
+ channelKind, ok := parseChannelKind(c.Type)
+ if !ok {
+ return errors.NewInternalf(errors.CodeInternal, "channel %q stores a spec under unmodelled type %q", c.DisplayName, c.Type)
}
- data, err := json.Marshal(receiver)
- if err != nil {
- return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "marshal receiver")
+ spec, _ := buildEmptyChannelSpecForKind(channelKind)
+ if err := json.Unmarshal([]byte(c.StoredSpec), spec); err != nil {
+ return errors.WrapInternalf(err, errors.CodeInternal, "unmarshal channel %q spec", c.DisplayName)
}
- channel.Data = string(data)
+ c.Spec = spec
- channel.Type = receiverChannelType(receiver)
- if channel.Type == "" {
- return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeAlertmanagerChannelInvalid, "channel '%s' must have at least one notification configuration (e.g., email_configs, webhook_configs, slack_configs)", receiver.Name)
+ return nil
+}
+
+func (c *Channel) fillSpec(spec ChannelSpec) error {
+ stored, err := json.Marshal(spec)
+ if err != nil {
+ return errors.WrapInternalf(err, errors.CodeInternal, "marshal channel %q spec", c.DisplayName)
}
+ c.Spec, c.StoredSpec = spec, string(stored)
- return &channel, nil
+ return nil
}
const channelNameSuffixLen = 8
@@ -137,57 +125,6 @@ func generateChannelName(displayName string) string {
return prefix + "-" + string(suffix)
}
-// NewChannelFromReceiverWithName overrides the name that NewChannelFromReceiver
-// generates.
-func NewChannelFromReceiverWithName(receiver *Receiver, name string, orgID string) (*Channel, error) {
- channel, err := NewChannelFromReceiver(receiver, orgID)
- if err != nil {
- return nil, err
- }
-
- channel.Name = name
-
- return channel, nil
-}
-
-// receiverChannelType returns the channel.Type discriminator. Walks
-// Receiver's own fields first (native), then the embed (upstream); first
-// non-empty *_configs slice wins.
-func receiverChannelType(receiver *Receiver) string {
- if t := nonEmptyConfigsField(reflect.ValueOf(*receiver)); t != "" {
- return t
- }
- if t := nonEmptyConfigsField(reflect.ValueOf(*receiver.Receiver)); t != "" {
- return t
- }
- return ""
-}
-
-func nonEmptyConfigsField(v reflect.Value) string {
- t := v.Type()
- for i := 0; i < t.NumField(); i++ {
- field := t.Field(i)
- fieldVal := v.Field(i)
-
- if fieldVal.Kind() != reflect.Slice || fieldVal.Len() == 0 {
- continue
- }
-
- yamlTag := field.Tag.Get("yaml")
- if yamlTag == "" {
- continue
- }
-
- // Extract the base type name (e.g., "email_configs" -> "email").
- matches := receiverTypeRegex.FindStringSubmatch(yamlTag)
- if len(matches) != 2 {
- continue
- }
- return matches[1]
- }
- return ""
-}
-
func NewConfigFromChannels(globalConfig GlobalConfig, routeConfig RouteConfig, channels Channels, orgID string) (*Config, error) {
cfg, err := NewDefaultConfig(
globalConfig,
@@ -228,64 +165,3 @@ func NewStatsFromChannels(channels Channels) map[string]any {
stats["alertmanager.channel.count"] = int64(len(channels))
return stats
}
-
-func (c *Channel) Update(receiver *Receiver) error {
- channel, err := NewChannelFromReceiverWithName(receiver, c.Name, c.OrgID)
- if err != nil {
- return err
- }
-
- if c.DisplayName != channel.DisplayName {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeAlertmanagerChannelNameMismatch, "cannot update channel name")
- }
-
- // Unreachable while the name is passed in above rather than derived from the
- // receiver, which is why this is internal rather than invalid input.
- if c.Name != channel.Name {
- return errors.NewInternalf(ErrCodeAlertmanagerChannelNameMismatch, "cannot update channel internal name")
- }
-
- c.Type = channel.Type
- c.Data = channel.Data
- c.UpdatedAt = time.Now()
-
- return nil
-}
-
-func (PostableChannel) JSONSchema() (jsonschema.Schema, error) {
- type alias PostableChannel
- reflector := &jsonschema.Reflector{}
-
- schema, err := reflector.Reflect(alias{}, jsonschema.DefinitionsPrefix("#/components/schemas/"))
- if err != nil {
- return jsonschema.Schema{}, err
- }
-
- schema.WithRequired("name")
-
- var oneOf []jsonschema.SchemaOrBool
- seen := map[string]struct{}{}
- // Walk both halves: native fields on Receiver, upstream on the embed. A native
- // field can shadow an upstream one with the same tag (e.g. jira_configs), so
- // dedupe to avoid emitting two identical oneOf branches.
- collect := func(t reflect.Type) {
- for i := 0; i < t.NumField(); i++ {
- jsonTag := strings.Split(t.Field(i).Tag.Get("json"), ",")[0]
- if !strings.HasSuffix(jsonTag, "_configs") {
- continue
- }
- if _, ok := seen[jsonTag]; ok {
- continue
- }
- seen[jsonTag] = struct{}{}
- branch := (&jsonschema.Schema{}).WithRequired(jsonTag)
- oneOf = append(oneOf, branch.ToSchemaOrBool())
- }
- }
- collect(reflect.TypeOf(Receiver{}))
- collect(reflect.TypeOf(config.Receiver{}))
-
- schema.WithOneOf(oneOf...)
-
- return schema, nil
-}
diff --git a/pkg/types/alertmanagertypes/channel_email.go b/pkg/types/alertmanagertypes/channel_email.go
index 0f2e7af562..45e7acb6cb 100644
--- a/pkg/types/alertmanagertypes/channel_email.go
+++ b/pkg/types/alertmanagertypes/channel_email.go
@@ -16,8 +16,20 @@ import (
type ChannelEmailConfig struct {
SendResolved *bool `json:"sendResolved,omitempty"`
To string `json:"to" required:"true"`
- HTML valuer.UnsetOrNonEmptyString `json:"html"`
- Headers map[string]string `json:"headers,omitempty"`
+ HTML valuer.UnsetOrNonEmptyString `json:"html,omitzero"`
+ Headers map[string]string `json:"headers,omitzero"`
+}
+
+func (c *ChannelEmailConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelEmailConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, config.DefaultEmailConfig.VSendResolved)
+ c.HTML.SetIfUnset(config.DefaultEmailConfig.HTML)
+
+ return c.Validate()
}
func (c ChannelEmailConfig) Validate() error {
diff --git a/pkg/types/alertmanagertypes/channel_googlechat.go b/pkg/types/alertmanagertypes/channel_googlechat.go
index 59afbf585a..52a888d790 100644
--- a/pkg/types/alertmanagertypes/channel_googlechat.go
+++ b/pkg/types/alertmanagertypes/channel_googlechat.go
@@ -10,8 +10,21 @@ import (
type ChannelGoogleChatConfig struct {
SendResolved *bool `json:"sendResolved,omitempty"`
WebhookURL string `json:"webhookUrl" required:"true" format:"password"`
- Title valuer.UnsetOrNonEmptyString `json:"title"`
- Text valuer.UnsetOrNonEmptyString `json:"text"`
+ Title valuer.UnsetOrNonEmptyString `json:"title,omitzero"`
+ Text valuer.UnsetOrNonEmptyString `json:"text,omitzero"`
+}
+
+func (c *ChannelGoogleChatConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelGoogleChatConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, DefaultGoogleChatReceiverConfig.VSendResolved)
+ c.Title.SetIfUnset(DefaultGoogleChatReceiverConfig.Title)
+ c.Text.SetIfUnset(DefaultGoogleChatReceiverConfig.Text)
+
+ return c.Validate()
}
func (c ChannelGoogleChatConfig) Validate() error {
diff --git a/pkg/types/alertmanagertypes/channel_incidentio.go b/pkg/types/alertmanagertypes/channel_incidentio.go
index 6855f34427..b104bb9f38 100644
--- a/pkg/types/alertmanagertypes/channel_incidentio.go
+++ b/pkg/types/alertmanagertypes/channel_incidentio.go
@@ -13,9 +13,22 @@ type ChannelIncidentIOConfig struct {
SendResolved *bool `json:"sendResolved,omitempty"`
URL string `json:"url" required:"true"`
Token string `json:"token" required:"true" format:"password"`
- Title valuer.UnsetOrNonEmptyString `json:"title"`
- Description valuer.UnsetOrNonEmptyString `json:"description"`
- Metadata map[string]string `json:"metadata,omitempty"`
+ Title valuer.UnsetOrNonEmptyString `json:"title,omitzero"`
+ Description valuer.UnsetOrNonEmptyString `json:"description,omitzero"`
+ Metadata map[string]string `json:"metadata,omitzero"`
+}
+
+func (c *ChannelIncidentIOConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelIncidentIOConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, DefaultIncidentIOReceiverConfig.VSendResolved)
+ c.Title.SetIfUnset(DefaultIncidentIOReceiverConfig.Title)
+ c.Description.SetIfUnset(DefaultIncidentIOReceiverConfig.Description)
+
+ return c.Validate()
}
func (c ChannelIncidentIOConfig) Validate() error {
diff --git a/pkg/types/alertmanagertypes/channel_jira.go b/pkg/types/alertmanagertypes/channel_jira.go
index 87ea3a4070..8a9714f7ea 100644
--- a/pkg/types/alertmanagertypes/channel_jira.go
+++ b/pkg/types/alertmanagertypes/channel_jira.go
@@ -19,20 +19,35 @@ type ChannelJiraConfig struct {
Site string `json:"site" required:"true"`
Project string `json:"project" required:"true"`
IssueType string `json:"issueType" required:"true"`
- Summary valuer.UnsetOrNonEmptyString `json:"summary"`
- Description valuer.UnsetOrNonEmptyString `json:"description"`
+ Summary valuer.UnsetOrNonEmptyString `json:"summary,omitzero"`
+ Description valuer.UnsetOrNonEmptyString `json:"description,omitzero"`
Priority string `json:"priority"`
- Labels []string `json:"labels,omitempty"`
+ Labels []string `json:"labels,omitzero"`
ResolveTransition string `json:"resolveTransition"`
ReopenTransition string `json:"reopenTransition"`
- ReopenDuration valuer.UnsetOrNonEmptyString `json:"reopenDuration"`
+ ReopenDuration valuer.UnsetOrNonEmptyString `json:"reopenDuration,omitzero"`
WontFixResolution string `json:"wontFixResolution"`
- CustomFields map[string]any `json:"customFields,omitempty"`
+ CustomFields map[string]any `json:"customFields,omitzero"`
Email string `json:"email" required:"true"`
APIToken string `json:"apiToken" required:"true" format:"password"`
}
+// UnmarshalJSON seeds send_resolved off, as JiraReceiverConfig does.
+func (c *ChannelJiraConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelJiraConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, false)
+ c.Summary.SetIfUnset(DefaultJiraSummaryTemplate)
+ c.Description.SetIfUnset(DefaultJiraDescriptionTemplate)
+ c.ReopenDuration.SetIfUnset(defaultJiraReopenDuration.String())
+
+ return c.Validate()
+}
+
func (c ChannelJiraConfig) Validate() error {
for _, required := range []struct {
value string
diff --git a/pkg/types/alertmanagertypes/channel_jsmops.go b/pkg/types/alertmanagertypes/channel_jsmops.go
index 5133d971ff..1f7303e445 100644
--- a/pkg/types/alertmanagertypes/channel_jsmops.go
+++ b/pkg/types/alertmanagertypes/channel_jsmops.go
@@ -12,11 +12,25 @@ import (
type ChannelJSMOpsConfig struct {
SendResolved *bool `json:"sendResolved,omitempty"`
APIKey string `json:"apiKey" required:"true" format:"password"`
- Message valuer.UnsetOrNonEmptyString `json:"message"`
- Description valuer.UnsetOrNonEmptyString `json:"description"`
+ Message valuer.UnsetOrNonEmptyString `json:"message,omitzero"`
+ Description valuer.UnsetOrNonEmptyString `json:"description,omitzero"`
Priority string `json:"priority"`
// Tags is the comma-separated list JSM Ops attaches to the alert.
- Tags valuer.UnsetOrNonEmptyString `json:"tags"`
+ Tags valuer.UnsetOrNonEmptyString `json:"tags,omitzero"`
+}
+
+func (c *ChannelJSMOpsConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelJSMOpsConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, DefaultJSMOpsReceiverConfig.VSendResolved)
+ c.Message.SetIfUnset(DefaultJSMOpsReceiverConfig.Message)
+ c.Description.SetIfUnset(DefaultJSMOpsReceiverConfig.Description)
+ c.Tags.SetIfUnset(DefaultJSMOpsReceiverConfig.Tags)
+
+ return c.Validate()
}
func (c ChannelJSMOpsConfig) Validate() error {
diff --git a/pkg/types/alertmanagertypes/channel_msteams.go b/pkg/types/alertmanagertypes/channel_msteams.go
index d375116f57..b26da967ed 100644
--- a/pkg/types/alertmanagertypes/channel_msteams.go
+++ b/pkg/types/alertmanagertypes/channel_msteams.go
@@ -9,8 +9,21 @@ import (
type ChannelMSTeamsConfig struct {
SendResolved *bool `json:"sendResolved,omitempty"`
WebhookURL string `json:"webhookUrl" required:"true" format:"password"`
- Title valuer.UnsetOrNonEmptyString `json:"title"`
- Text valuer.UnsetOrNonEmptyString `json:"text"`
+ Title valuer.UnsetOrNonEmptyString `json:"title,omitzero"`
+ Text valuer.UnsetOrNonEmptyString `json:"text,omitzero"`
+}
+
+func (c *ChannelMSTeamsConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelMSTeamsConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, config.DefaultMSTeamsV2Config.VSendResolved)
+ c.Title.SetIfUnset(config.DefaultMSTeamsV2Config.Title)
+ c.Text.SetIfUnset(config.DefaultMSTeamsV2Config.Text)
+
+ return c.Validate()
}
func (c ChannelMSTeamsConfig) Validate() error {
diff --git a/pkg/types/alertmanagertypes/channel_opsgenie.go b/pkg/types/alertmanagertypes/channel_opsgenie.go
index 4180b0ca8b..bcc0ddf541 100644
--- a/pkg/types/alertmanagertypes/channel_opsgenie.go
+++ b/pkg/types/alertmanagertypes/channel_opsgenie.go
@@ -10,13 +10,27 @@ type ChannelOpsgenieConfig struct {
SendResolved *bool `json:"sendResolved,omitempty"`
APIKey string `json:"apiKey" required:"true" format:"password"`
APIURL string `json:"apiUrl"`
- Message valuer.UnsetOrNonEmptyString `json:"message"`
- Description valuer.UnsetOrNonEmptyString `json:"description"`
- Source valuer.UnsetOrNonEmptyString `json:"source"`
- Details map[string]string `json:"details,omitempty"`
+ Message valuer.UnsetOrNonEmptyString `json:"message,omitzero"`
+ Description valuer.UnsetOrNonEmptyString `json:"description,omitzero"`
+ Source valuer.UnsetOrNonEmptyString `json:"source,omitzero"`
+ Details map[string]string `json:"details,omitzero"`
Priority string `json:"priority"`
}
+func (c *ChannelOpsgenieConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelOpsgenieConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, config.DefaultOpsGenieConfig.VSendResolved)
+ c.Message.SetIfUnset(config.DefaultOpsGenieConfig.Message)
+ c.Description.SetIfUnset(config.DefaultOpsGenieConfig.Description)
+ c.Source.SetIfUnset(config.DefaultOpsGenieConfig.Source)
+
+ return c.Validate()
+}
+
func (c ChannelOpsgenieConfig) Validate() error {
if c.APIKey == "" {
return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.apiKey is required for an opsgenie channel")
diff --git a/pkg/types/alertmanagertypes/channel_pagerduty.go b/pkg/types/alertmanagertypes/channel_pagerduty.go
index d6ccd2241c..680ea363fb 100644
--- a/pkg/types/alertmanagertypes/channel_pagerduty.go
+++ b/pkg/types/alertmanagertypes/channel_pagerduty.go
@@ -10,15 +10,39 @@ type ChannelPagerdutyConfig struct {
SendResolved *bool `json:"sendResolved,omitempty"`
RoutingKey string `json:"routingKey" required:"true" format:"password"`
URL string `json:"url"`
- Source valuer.UnsetOrNonEmptyString `json:"source"`
- Client valuer.UnsetOrNonEmptyString `json:"client"`
- ClientURL valuer.UnsetOrNonEmptyString `json:"clientUrl"`
- Description valuer.UnsetOrNonEmptyString `json:"description"`
+ Source valuer.UnsetOrNonEmptyString `json:"source,omitzero"`
+ Client valuer.UnsetOrNonEmptyString `json:"client,omitzero"`
+ ClientURL valuer.UnsetOrNonEmptyString `json:"clientUrl,omitzero"`
+ Description valuer.UnsetOrNonEmptyString `json:"description,omitzero"`
Severity string `json:"severity"`
Component string `json:"component"`
Group string `json:"group"`
Class string `json:"class"`
- Details map[string]string `json:"details,omitempty"`
+ Details map[string]string `json:"details,omitzero"`
+}
+
+func (c *ChannelPagerdutyConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelPagerdutyConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, config.DefaultPagerdutyConfig.VSendResolved)
+ c.Description.SetIfUnset(config.DefaultPagerdutyConfig.Description)
+ c.Client.SetIfUnset(config.DefaultPagerdutyConfig.Client)
+ c.ClientURL.SetIfUnset(config.DefaultPagerdutyConfig.ClientURL)
+ c.Source.SetIfUnset(c.Client.StringValue())
+
+ if c.Details == nil {
+ c.Details = make(map[string]string, len(config.DefaultPagerdutyDetails))
+ for key, value := range config.DefaultPagerdutyDetails {
+ if template, ok := value.(string); ok {
+ c.Details[key] = template
+ }
+ }
+ }
+
+ return c.Validate()
}
func (c ChannelPagerdutyConfig) Validate() error {
@@ -90,3 +114,32 @@ func newChannelPagerdutyConfigFromReceiver(name string, receiver *Receiver) (Cha
Details: details,
}, nil
}
+
+func newUpstreamDetails(details map[string]string) map[string]any {
+ if details == nil {
+ return nil
+ }
+
+ upstream := make(map[string]any, len(details))
+ for key, value := range details {
+ upstream[key] = value
+ }
+
+ return upstream
+}
+
+func extractStringDetails(name string, details map[string]any) (map[string]string, error) {
+ extracted := make(map[string]string, len(details))
+ for key, value := range details {
+ stringValue, ok := value.(string)
+ if !ok {
+ return nil, errors.NewInvalidInputf(
+ ErrCodeAlertmanagerChannelInvalid,
+ "channel %q sets a non-string value for details.%s, which is not supported", name, key,
+ )
+ }
+ extracted[key] = stringValue
+ }
+
+ return extracted, nil
+}
diff --git a/pkg/types/alertmanagertypes/channel_slack.go b/pkg/types/alertmanagertypes/channel_slack.go
index abf097e6e7..60b7266f35 100644
--- a/pkg/types/alertmanagertypes/channel_slack.go
+++ b/pkg/types/alertmanagertypes/channel_slack.go
@@ -10,15 +10,15 @@ type ChannelSlackConfig struct {
SendResolved *bool `json:"sendResolved,omitempty"`
APIURL string `json:"apiUrl" required:"true" format:"password"`
Channel string `json:"channel"`
- Title valuer.UnsetOrNonEmptyString `json:"title"`
- Text valuer.UnsetOrNonEmptyString `json:"text"`
- Color valuer.UnsetOrNonEmptyString `json:"color"`
- TitleLink valuer.UnsetOrNonEmptyString `json:"titleLink"`
- Pretext valuer.UnsetOrNonEmptyString `json:"pretext"`
- Fallback valuer.UnsetOrNonEmptyString `json:"fallback"`
- Footer valuer.UnsetOrNonEmptyString `json:"footer"`
- Fields []ChannelSlackField `json:"fields,omitempty"`
- Actions []ChannelSlackAction `json:"actions,omitempty"`
+ Title valuer.UnsetOrNonEmptyString `json:"title,omitzero"`
+ Text valuer.UnsetOrNonEmptyString `json:"text,omitzero"`
+ Color valuer.UnsetOrNonEmptyString `json:"color,omitzero"`
+ TitleLink valuer.UnsetOrNonEmptyString `json:"titleLink,omitzero"`
+ Pretext valuer.UnsetOrNonEmptyString `json:"pretext,omitzero"`
+ Fallback valuer.UnsetOrNonEmptyString `json:"fallback,omitzero"`
+ Footer valuer.UnsetOrNonEmptyString `json:"footer,omitzero"`
+ Fields []ChannelSlackField `json:"fields,omitzero"`
+ Actions []ChannelSlackAction `json:"actions,omitzero"`
}
type ChannelSlackField struct {
@@ -46,6 +46,24 @@ type ChannelSlackConfirmation struct {
DismissText string `json:"dismissText"`
}
+func (c *ChannelSlackConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelSlackConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, config.DefaultSlackConfig.VSendResolved)
+ c.Title.SetIfUnset(config.DefaultSlackConfig.Title)
+ c.Text.SetIfUnset(config.DefaultSlackConfig.Text)
+ c.Color.SetIfUnset(config.DefaultSlackConfig.Color)
+ c.TitleLink.SetIfUnset(config.DefaultSlackConfig.TitleLink)
+ c.Pretext.SetIfUnset(config.DefaultSlackConfig.Pretext)
+ c.Fallback.SetIfUnset(config.DefaultSlackConfig.Fallback)
+ c.Footer.SetIfUnset(config.DefaultSlackConfig.Footer)
+
+ return c.Validate()
+}
+
func (c ChannelSlackConfig) Validate() error {
if c.APIURL == "" {
return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.apiUrl is required for a slack channel")
diff --git a/pkg/types/alertmanagertypes/channel_webhook.go b/pkg/types/alertmanagertypes/channel_webhook.go
index 3de644f3cf..b02a3cdf7f 100644
--- a/pkg/types/alertmanagertypes/channel_webhook.go
+++ b/pkg/types/alertmanagertypes/channel_webhook.go
@@ -1,11 +1,16 @@
package alertmanagertypes
import (
+ "strings"
+
"github.com/SigNoz/signoz/pkg/errors"
"github.com/prometheus/alertmanager/config"
commoncfg "github.com/prometheus/common/config"
)
+// bearerAuthorizationType is the scheme SigNoz writes for token auth.
+const bearerAuthorizationType = "Bearer"
+
// ChannelWebhookConfig splits apart the two authentication modes the legacy API
// overloaded onto one password field, where an empty username meant the password
// was really a bearer token. Username or Password may be set without the other,
@@ -18,6 +23,17 @@ type ChannelWebhookConfig struct {
BearerToken string `json:"bearerToken" format:"password"`
}
+func (c *ChannelWebhookConfig) UnmarshalJSON(data []byte) error {
+ type alias ChannelWebhookConfig
+ if err := decodeStrict(data, (*alias)(c)); err != nil {
+ return err
+ }
+
+ fillSendResolved(&c.SendResolved, config.DefaultWebhookConfig.VSendResolved)
+
+ return c.Validate()
+}
+
func (c ChannelWebhookConfig) Validate() error {
if c.URL == "" {
return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.url is required for a webhook channel")
@@ -96,3 +112,16 @@ func newChannelWebhookConfigFromReceiver(name string, receiver *Receiver) (Chann
return webhook, nil
}
+
+func rejectHTTPAuthorizationBeyondBearer(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
+ if httpConfig == nil || httpConfig.Authorization == nil {
+ return nil
+ }
+
+ authorization := httpConfig.Authorization
+ if !strings.EqualFold(authorization.Type, bearerAuthorizationType) || *authorization != (commoncfg.Authorization{Type: authorization.Type, Credentials: authorization.Credentials}) {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.authorization with fields other than a bearer token, which is not supported", channelName)
+ }
+
+ return nil
+}
diff --git a/pkg/types/alertmanagertypes/channelconfig.go b/pkg/types/alertmanagertypes/channelconfig.go
index cd6be7a9e3..e2e76c5e2e 100644
--- a/pkg/types/alertmanagertypes/channelconfig.go
+++ b/pkg/types/alertmanagertypes/channelconfig.go
@@ -1,104 +1,50 @@
package alertmanagertypes
import (
- "bytes"
"encoding/json"
- "net/url"
"reflect"
- "slices"
- "strings"
"github.com/SigNoz/signoz/pkg/errors"
- "github.com/SigNoz/signoz/pkg/valuer"
- "github.com/prometheus/alertmanager/config"
- commoncfg "github.com/prometheus/common/config"
"github.com/swaggest/jsonschema-go"
)
-var (
- ErrCodeChannelUnsupportedKind = errors.MustNewCode("channel_unsupported_kind")
-)
-
-// ════════════════════════════════════════════════════════════════════════
-// Kind
-// ════════════════════════════════════════════════════════════════════════
-
-// ChannelKind selects which ChannelSpec a channel carries and which notifier
-// integration is built for it.
-type ChannelKind struct {
- valuer.String
+type ChannelConfig struct {
+ Kind ChannelKind `json:"kind" required:"true"`
+ Spec any `json:"spec" required:"true"`
}
-var (
- ChannelKindSlack = ChannelKind{valuer.NewString("slack")}
- ChannelKindEmail = ChannelKind{valuer.NewString("email")}
- ChannelKindWebhook = ChannelKind{valuer.NewString("webhook")}
- ChannelKindPagerduty = ChannelKind{valuer.NewString("pagerduty")}
- ChannelKindOpsgenie = ChannelKind{valuer.NewString("opsgenie")}
- ChannelKindMSTeams = ChannelKind{valuer.NewString("msteams")}
- ChannelKindGoogleChat = ChannelKind{valuer.NewString("googlechat")}
- ChannelKindJira = ChannelKind{valuer.NewString("jira")}
- ChannelKindJSMOps = ChannelKind{valuer.NewString("jsmops")}
- ChannelKindIncidentIO = ChannelKind{valuer.NewString("incidentio")}
-)
+func (c *ChannelConfig) UnmarshalJSON(data []byte) error {
+ var envelope struct {
+ Kind ChannelKind `json:"kind"`
-func (ChannelKind) Enum() []any {
- kinds := make([]any, 0, len(channelKinds))
- for _, channelKind := range channelKinds {
- kinds = append(kinds, channelKind.kind)
+ // json.RawMessage keeps spec bytes unparsed until Kind is known. Once
+ // Kind is known, this Spec can be decoded into the correct type.
+ Spec json.RawMessage `json:"spec"`
}
- return kinds
-}
-
-func (t ChannelKind) IsValid() bool {
- return slices.ContainsFunc(t.Enum(), func(v any) bool { return v == t })
-}
-
-// ToStoredType returns the Channel.Type a channel of this kind is stored under,
-// which matches the kind for all but msteams.
-func (t ChannelKind) ToStoredType() string {
- if t == ChannelKindMSTeams {
- return "msteamsv2"
+ if err := decodeStrict(data, &envelope); err != nil {
+ return err
}
-
- return t.StringValue()
-}
-
-// parseStoredChannelType inverts ToStoredType. It reports false for the notifier
-// kinds v1 accepted but v2 does not model.
-func parseStoredChannelType(stored string) (ChannelKind, bool) {
- for _, channelKind := range channelKinds {
- if channelKind.kind.ToStoredType() == stored {
- return channelKind.kind, true
- }
+ if len(envelope.Spec) == 0 {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec is required")
}
- return ChannelKind{}, false
-}
+ spec, ok := buildEmptyChannelSpecForKind(envelope.Kind)
+ if !ok {
+ return ErrUnsupportedChannelKind(envelope.Kind.StringValue())
+ }
-func ErrUnsupportedChannelKind(s string) error {
- return errors.Newf(
- errors.TypeInvalidInput,
- ErrCodeChannelUnsupportedKind,
- "unknown notification channel kind %q; allowed values: %s",
- s, allowedValuesForChannelKind(),
- )
-}
+ if err := json.Unmarshal(envelope.Spec, spec); err != nil {
+ return err
+ }
-// ════════════════════════════════════════════════════════════════════════
-// Union
-// ════════════════════════════════════════════════════════════════════════
+ c.Kind = envelope.Kind
+ c.Spec = spec
-// ChannelConfig is the discriminated union of per-kind configurations. The
-// envelope sits on config rather than the resource root, so clients narrow on
-// config.kind instead of every request and response flavor becoming a oneOf.
-type ChannelConfig struct {
- Kind ChannelKind `json:"kind" required:"true"`
- Spec any `json:"spec" required:"true"`
+ return nil
}
func (c ChannelConfig) Validate() error {
- newSpec, ok := newChannelSpec(c.Kind)
+ expected, ok := buildEmptyChannelSpecForKind(c.Kind)
if !ok {
return ErrUnsupportedChannelKind(c.Kind.StringValue())
}
@@ -107,42 +53,19 @@ func (c ChannelConfig) Validate() error {
return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec is required")
}
- spec, ok := c.Spec.(ChannelSpec)
- if !ok {
- return errors.NewInternalf(errors.CodeInternal, "config.spec was not decoded into a known type")
- }
-
- // A decoded config cannot disagree, because UnmarshalJSON builds the spec
- // from the kind. A caller assembling the struct can, and the conversion to a
- // receiver dispatches on the spec, so a mismatch would silently outrank the
- // declared kind.
- if reflect.TypeOf(spec) != reflect.TypeOf(newSpec()) {
- return errors.NewInternalf(errors.CodeInternal, "config.spec does not match kind %q", c.Kind.StringValue())
- }
-
- return spec.Validate()
-}
-
-func (c *ChannelConfig) UnmarshalJSON(data []byte) error {
- channelKindString, specJSON, err := extractKindAndSpec(data)
+ spec, err := c.toChannelSpec()
if err != nil {
return err
}
- factory, ok := newChannelSpec(ChannelKind{valuer.NewString(channelKindString)})
- if !ok {
- return ErrUnsupportedChannelKind(channelKindString)
- }
-
- spec, err := decodeChannelSpec(specJSON, factory(), channelKindString)
- if err != nil {
- return err
+ // Only a config assembled in Go gets here, and one can pair a spec with the
+ // wrong kind. The conversion to a receiver dispatches on the spec, so the
+ // mismatch would silently outrank the declared kind.
+ if reflect.TypeOf(spec) != reflect.TypeOf(expected) {
+ return errors.NewInternalf(errors.CodeInternal, "config.spec does not match kind %q", c.Kind.StringValue())
}
- c.Kind = ChannelKind{valuer.NewString(channelKindString)}
- c.Spec = *spec
-
- return nil
+ return spec.Validate()
}
// ChannelConfigVariant names one branch of the union. Each instantiation becomes
@@ -193,311 +116,6 @@ func (ChannelConfig) PrepareJSONSchema(s *jsonschema.Schema) error {
})
}
-// ════════════════════════════════════════════════════════════════════════
-// Specs
-// ════════════════════════════════════════════════════════════════════════
-
-type ChannelSpec interface {
- Validate() error
- toUndefaultedReceiver(displayName string) (*Receiver, error)
-}
-
-// ════════════════════════════════════════════════════════════════════════
-// Helpers
-// ════════════════════════════════════════════════════════════════════════
-
-// bearerAuthorizationType is the scheme SigNoz writes for token auth.
-const bearerAuthorizationType = "Bearer"
-
-// parseSecretURL and parseUpstreamURL wrap the two URL types upstream uses for
-// notifier endpoints. Callers holding an optional URL skip the call on an empty
-// string, so the field stays nil and is omitted rather than stored as an empty URL.
-func parseSecretURL(raw string) (*config.SecretURL, error) {
- parsed, err := parseUpstreamURL(raw)
- if err != nil {
- return nil, err
- }
-
- return (*config.SecretURL)(parsed), nil
-}
-
-func parseUpstreamURL(raw string) (*config.URL, error) {
- parsed, err := url.Parse(raw)
- if err != nil {
- return nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "parse url %q", raw)
- }
-
- return &config.URL{URL: parsed}, nil
-}
-
-func formatSecretURL(secretURL *config.SecretURL) string {
- if secretURL == nil {
- return ""
- }
-
- return formatUpstreamURL((*config.URL)(secretURL))
-}
-
-func formatUpstreamURL(upstreamURL *config.URL) string {
- if upstreamURL == nil || upstreamURL.URL == nil {
- return ""
- }
-
- return upstreamURL.String()
-}
-
-// PagerDuty is the one notifier whose details upstream types as map[string]any.
-func newUpstreamDetails(details map[string]string) map[string]any {
- if details == nil {
- return nil
- }
-
- upstream := make(map[string]any, len(details))
- for key, value := range details {
- upstream[key] = value
- }
-
- return upstream
-}
-
-func extractStringDetails(name string, details map[string]any) (map[string]string, error) {
- extracted := make(map[string]string, len(details))
- for key, value := range details {
- stringValue, ok := value.(string)
- if !ok {
- return nil, errors.NewInvalidInputf(
- ErrCodeAlertmanagerChannelInvalid,
- "channel %q sets a non-string value for details.%s, which is not supported", name, key,
- )
- }
- extracted[key] = stringValue
- }
-
- return extracted, nil
-}
-
-func rejectAnyHTTPAuth(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
- if httpConfig == nil {
- return nil
- }
-
- if httpConfig.BasicAuth != nil {
- return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.basic_auth, which is not supported", channelName)
- }
-
- if httpConfig.Authorization != nil {
- return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.authorization, which is not supported", channelName)
- }
-
- return rejectUnsupportedHTTPConfig(channelName, httpConfig)
-}
-
-func rejectUnsupportedHTTPConfig(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
- if httpConfig == nil {
- return nil
- }
-
- for _, field := range []struct {
- fieldName string
- isFieldConfigured bool
- }{
- {"oauth2", httpConfig.OAuth2 != nil},
- {"bearer_token", httpConfig.BearerToken != ""},
- {"bearer_token_file", httpConfig.BearerTokenFile != ""},
- {"proxy_url", httpConfig.ProxyURL.URL != nil && httpConfig.ProxyURL.String() != ""},
- {"no_proxy", httpConfig.NoProxy != ""},
- {"proxy_from_environment", httpConfig.ProxyFromEnvironment},
- {"http_headers", httpConfig.HTTPHeaders != nil},
- {"tls_config", httpConfig.TLSConfig != (commoncfg.TLSConfig{})},
- {"follow_redirects", !httpConfig.FollowRedirects},
- {"enable_http2", !httpConfig.EnableHTTP2},
- } {
- if field.isFieldConfigured {
- return errors.NewInvalidInputf(
- ErrCodeAlertmanagerChannelInvalid,
- "channel %q sets http_config.%s, which is not supported", channelName, field.fieldName,
- )
- }
- }
-
- return nil
-}
-
-func rejectHTTPBasicAuthBeyondPassword(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
- if httpConfig == nil || httpConfig.BasicAuth == nil {
- return nil
- }
-
- basicAuth := httpConfig.BasicAuth
- if *basicAuth != (commoncfg.BasicAuth{Username: basicAuth.Username, Password: basicAuth.Password}) {
- return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.basic_auth with fields other than username and password, which is not supported", channelName)
- }
-
- return nil
-}
-
-func rejectHTTPAuthorizationBeyondBearer(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
- if httpConfig == nil || httpConfig.Authorization == nil {
- return nil
- }
-
- authorization := httpConfig.Authorization
- if !strings.EqualFold(authorization.Type, bearerAuthorizationType) || *authorization != (commoncfg.Authorization{Type: authorization.Type, Credentials: authorization.Credentials}) {
- return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.authorization with fields other than a bearer token, which is not supported", channelName)
- }
-
- return nil
-}
-
-// channelKinds registers each notification kind with the spec constructor
-// UnmarshalJSON picks by kind and the extractor that reads a stored receiver
-// back. The ChannelKind enum derives from it; the JSON schema hooks stay
-// literal lists so each branch reads as one line.
-var channelKinds = []channelKindEntry{
- {
- kind: ChannelKindSlack,
- newSpec: func() ChannelSpec { return new(ChannelSlackConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.SlackConfigs) },
- extractSpec: newChannelSlackConfigFromReceiver,
- },
- {
- kind: ChannelKindEmail,
- newSpec: func() ChannelSpec { return new(ChannelEmailConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.EmailConfigs) },
- extractSpec: newChannelEmailConfigFromReceiver,
- },
- {
- kind: ChannelKindWebhook,
- newSpec: func() ChannelSpec { return new(ChannelWebhookConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.WebhookConfigs) },
- extractSpec: newChannelWebhookConfigFromReceiver,
- },
- {
- kind: ChannelKindPagerduty,
- newSpec: func() ChannelSpec { return new(ChannelPagerdutyConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.PagerdutyConfigs) },
- extractSpec: newChannelPagerdutyConfigFromReceiver,
- },
- {
- kind: ChannelKindOpsgenie,
- newSpec: func() ChannelSpec { return new(ChannelOpsgenieConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.OpsGenieConfigs) },
- extractSpec: newChannelOpsgenieConfigFromReceiver,
- },
- {
- kind: ChannelKindMSTeams,
- newSpec: func() ChannelSpec { return new(ChannelMSTeamsConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.MSTeamsV2Configs) },
- extractSpec: newChannelMSTeamsConfigFromReceiver,
- },
- {
- kind: ChannelKindGoogleChat,
- newSpec: func() ChannelSpec { return new(ChannelGoogleChatConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.GoogleChatConfigs) },
- extractSpec: newChannelGoogleChatConfigFromReceiver,
- },
- {
- kind: ChannelKindJira,
- newSpec: func() ChannelSpec { return new(ChannelJiraConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.JiraConfigs) },
- extractSpec: newChannelJiraConfigFromReceiver,
- },
- {
- kind: ChannelKindJSMOps,
- newSpec: func() ChannelSpec { return new(ChannelJSMOpsConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.JSMOpsConfigs) },
- extractSpec: newChannelJSMOpsConfigFromReceiver,
- },
- {
- kind: ChannelKindIncidentIO,
- newSpec: func() ChannelSpec { return new(ChannelIncidentIOConfig) },
- countConfigs: func(receiver *Receiver) int { return len(receiver.IncidentIOConfigs) },
- extractSpec: newChannelIncidentIOConfigFromReceiver,
- },
-}
-
-type channelKindEntry struct {
- kind ChannelKind
- newSpec func() ChannelSpec
- // countConfigs guards extractSpec, which reads the receiver's first config of
- // this kind and so must not be called when there is none.
- countConfigs func(receiver *Receiver) int
- extractSpec func(name string, receiver *Receiver) (ChannelSpec, error)
-}
-
-func newChannelSpec(kind ChannelKind) (func() ChannelSpec, bool) {
- for _, channelKind := range channelKinds {
- if channelKind.kind == kind {
- return channelKind.newSpec, true
- }
- }
- return nil, false
-}
-
-// resolveSendResolved falls back to the notifier's own upstream default, because
-// send_resolved has no omitempty: a zero value would marshal as an explicit false
-// and overwrite the default rather than leave it in place.
-func resolveSendResolved(sendResolved *bool, upstreamDefault bool) bool {
- if sendResolved == nil {
- return upstreamDefault
- }
-
- return *sendResolved
-}
-
-func allowedValuesForChannelKind() string {
- return formatAllowedValues((ChannelKind{}).Enum())
-}
-
-func formatAllowedValues(enum []any) string {
- values := make([]string, 0, len(enum))
- for _, value := range enum {
- stringValuer, ok := value.(interface{ StringValue() string })
- if !ok {
- continue
- }
-
- values = append(values, "`"+stringValuer.StringValue()+"`")
- }
- slices.Sort(values)
-
- return strings.Join(values, ", ")
-}
-
-// extractKindAndSpec parses a {"kind": "...", "spec": {...}} envelope. Unknown
-// keys are rejected here rather than by the caller's decoder: a custom
-// UnmarshalJSON receives raw bytes, so DisallowUnknownFields on the request body
-// does not reach inside config.
-func extractKindAndSpec(data []byte) (string, []byte, error) {
- var head struct {
- Kind string `json:"kind"`
- Spec json.RawMessage `json:"spec"`
- }
- dec := json.NewDecoder(bytes.NewReader(data))
- dec.DisallowUnknownFields()
- if err := dec.Decode(&head); err != nil {
- return "", nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "invalid channel config envelope")
- }
- return head.Kind, head.Spec, nil
-}
-
-// decodeChannelSpec rejects unknown fields so a spec meant for another kind is an
-// error rather than a silently empty struct, and validates before returning.
-func decodeChannelSpec[T ChannelSpec](specJSON []byte, target T, channelType string) (*T, error) {
- if len(specJSON) == 0 {
- return nil, errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "type %q: spec is required", channelType)
- }
- dec := json.NewDecoder(bytes.NewReader(specJSON))
- dec.DisallowUnknownFields()
- if err := dec.Decode(target); err != nil {
- return nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "type %q: invalid spec JSON", channelType)
- }
- if err := target.Validate(); err != nil {
- return nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "type %q: %s", channelType, err.Error())
- }
- return &target, nil
-}
-
// signozDiscriminatorKey is the extension key that signoz.attachDiscriminators
// promotes into a native OpenAPI 3 discriminator after reflection.
const signozDiscriminatorKey = "x-signoz-discriminator"
@@ -514,6 +132,18 @@ func channelVariantRef(spec string) string {
return schemaRef("AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypes" + spec)
}
+// toChannelSpec asserts what UnmarshalJSON decoded. Spec is any rather than
+// ChannelSpec because the OpenAPI reflector turns an interface field into an
+// empty component.
+func (c ChannelConfig) toChannelSpec() (ChannelSpec, error) {
+ spec, ok := c.Spec.(ChannelSpec)
+ if !ok {
+ return nil, errors.NewInternalf(errors.CodeInternal, "config.spec was not decoded into a known type")
+ }
+
+ return spec, nil
+}
+
// markDiscriminator tags a oneOf schema with x-signoz-discriminator, keyed on
// propertyName with the given value -> schema-ref mapping, so generated clients
// get a discriminated DTO instead of an intersection.
diff --git a/pkg/types/alertmanagertypes/channelconvertors.go b/pkg/types/alertmanagertypes/channelconvertors.go
index 3dbe6cef9c..b222b83dde 100644
--- a/pkg/types/alertmanagertypes/channelconvertors.go
+++ b/pkg/types/alertmanagertypes/channelconvertors.go
@@ -3,8 +3,11 @@ package alertmanagertypes
import (
"encoding/json"
"reflect"
+ "time"
"github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/prometheus/alertmanager/config"
)
@@ -12,13 +15,47 @@ import (
// API -> storage
// ════════════════════════════════════════════════════════════════════════
+// ToChannel returns the receiver alongside because the alertmanager config is
+// updated from it, not from the channel.
+func (p *PostableNotificationChannel) ToChannel(orgID string) (*Channel, *Receiver, error) {
+ receiver, err := p.ToReceiver()
+ if err != nil {
+ return nil, nil, err
+ }
+
+ data, err := json.Marshal(receiver)
+ if err != nil {
+ return nil, nil, errors.WrapInternalf(err, errors.CodeInternal, "marshal receiver")
+ }
+
+ spec, err := p.Config.toChannelSpec()
+ if err != nil {
+ return nil, nil, err
+ }
+
+ channel := &Channel{
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ TimeAuditable: types.TimeAuditable{CreatedAt: time.Now(), UpdatedAt: time.Now()},
+ Name: p.Name,
+ DisplayName: p.DisplayName,
+ Type: p.Config.Kind.StringValue(),
+ Data: string(data),
+ OrgID: orgID,
+ }
+ if err := channel.fillSpec(spec); err != nil {
+ return nil, nil, err
+ }
+
+ return channel, receiver, nil
+}
+
// ToReceiver hands the assembled receiver to newDefaultedReceiver, which is the
// only place upstream applies a notifier's defaults and validation — several
// integrations panic without them.
func (p *PostableNotificationChannel) ToReceiver() (*Receiver, error) {
- spec, ok := p.Config.Spec.(ChannelSpec)
- if !ok {
- return nil, errors.NewInternalf(errors.CodeInternal, "config.spec was not decoded into a known type")
+ spec, err := p.Config.toChannelSpec()
+ if err != nil {
+ return nil, err
}
receiver, err := spec.toUndefaultedReceiver(p.DisplayName)
@@ -45,22 +82,63 @@ func (t *TestableNotificationChannel) ToReceiver() (*Receiver, error) {
return postable.ToReceiver()
}
+func (c *Channel) UpdateFromUpdatable(updatable UpdatableNotificationChannel) (*Receiver, error) {
+ receiver, err := updatable.ToReceiver(c.DisplayName)
+ if err != nil {
+ return nil, err
+ }
+
+ data, err := json.Marshal(receiver)
+ if err != nil {
+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "marshal receiver")
+ }
+
+ spec, err := updatable.Config.toChannelSpec()
+ if err != nil {
+ return nil, err
+ }
+ if err := c.fillSpec(spec); err != nil {
+ return nil, err
+ }
+
+ c.Type = updatable.Config.Kind.StringValue()
+ c.Data = string(data)
+ c.UpdatedAt = time.Now()
+
+ return receiver, nil
+}
+
// ════════════════════════════════════════════════════════════════════════
// Storage -> API
// ════════════════════════════════════════════════════════════════════════
-// toPostableNotificationChannel derives the kind from the config the receiver
-// actually carries rather than from Channel.Type, so a row written with several
-// notifier kinds is rejected instead of reported under whichever one
-// receiverChannelType happened to pick.
-func (c *Channel) toPostableNotificationChannel() (*PostableNotificationChannel, error) {
+// toChannelConfig pairs the scanned spec with the kind Type names. Only a row
+// the migration could not backfill has none, so deriving it here reports why.
+func (c *Channel) toChannelConfig() (ChannelConfig, error) {
+ if c.Spec == nil {
+ return c.deriveChannelConfig()
+ }
+
+ channelKind, ok := parseChannelKind(c.Type)
+ if !ok {
+ return ChannelConfig{}, errors.NewInternalf(errors.CodeInternal, "channel %q carries a spec under unmodelled type %q", c.DisplayName, c.Type)
+ }
+
+ return ChannelConfig{Kind: channelKind, Spec: c.Spec}, nil
+}
+
+// deriveChannelConfig derives the kind from the config the receiver actually
+// carries rather than from Channel.Type, so a row written with several notifier
+// kinds is rejected instead of reported under whichever one receiverChannelType
+// happened to pick.
+func (c *Channel) deriveChannelConfig() (ChannelConfig, error) {
receiver := &Receiver{Receiver: &config.Receiver{}}
if err := json.Unmarshal([]byte(c.Data), receiver); err != nil {
- return nil, errors.WrapInternalf(err, errors.CodeInternal, "unmarshal channel %q", c.DisplayName)
+ return ChannelConfig{}, errors.WrapInternalf(err, errors.CodeInternal, "unmarshal channel %q", c.DisplayName)
}
if total := countNotifierConfigs(receiver); total > 1 {
- return nil, errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q carries %d notifier configurations; only one per channel is supported", c.DisplayName, total)
+ return ChannelConfig{}, errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q carries %d notifier configurations; only one per channel is supported", c.DisplayName, total)
}
for _, channelKind := range channelKinds {
@@ -70,17 +148,21 @@ func (c *Channel) toPostableNotificationChannel() (*PostableNotificationChannel,
spec, err := channelKind.extractSpec(c.DisplayName, receiver)
if err != nil {
- return nil, err
+ return ChannelConfig{}, err
+ }
+
+ // The derived config is stored and decoded back through the same
+ // validation a request goes through, so one that would not decode is
+ // unrepresentable rather than stored.
+ channelConfig := ChannelConfig{Kind: channelKind.kind, Spec: spec}
+ if err := channelConfig.Validate(); err != nil {
+ return ChannelConfig{}, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "channel %q: %s", c.DisplayName, err.Error())
}
- return &PostableNotificationChannel{
- Name: c.Name,
- DisplayName: c.DisplayName,
- Config: ChannelConfig{Kind: channelKind.kind, Spec: spec},
- }, nil
+ return channelConfig, nil
}
- return nil, errors.NewInvalidInputf(ErrCodeChannelUnsupportedKind, "channel %q carries no supported notifier configuration", c.DisplayName)
+ return ChannelConfig{}, errors.NewInvalidInputf(ErrCodeChannelUnsupportedKind, "channel %q carries no supported notifier configuration", c.DisplayName)
}
// countNotifierConfigs totals every *_configs entry on the receiver, including
@@ -111,15 +193,15 @@ func countConfigsFields(v reflect.Value) int {
}
func (c *Channel) ToGettableNotificationChannel() (*GettableNotificationChannel, error) {
- postable, err := c.toPostableNotificationChannel()
+ channelConfig, err := c.toChannelConfig()
if err != nil {
return nil, err
}
return &GettableNotificationChannel{
- Name: postable.Name,
- DisplayName: postable.DisplayName,
- Config: postable.Config,
+ Name: c.Name,
+ DisplayName: c.DisplayName,
+ Config: channelConfig,
ID: c.ID,
CreatedAt: c.CreatedAt,
UpdatedAt: c.UpdatedAt,
@@ -130,7 +212,7 @@ func (c *Channel) ToGettableNotificationChannel() (*GettableNotificationChannel,
// no ChannelKind models, which v1 allowed because it accepted every upstream
// notifier kind. One such row must not fail the whole page.
func (c *Channel) ToListedNotificationChannel() *ListedNotificationChannel {
- channelKind, _ := parseStoredChannelType(c.Type)
+ channelKind, _ := parseChannelKind(c.Type)
return &ListedNotificationChannel{
ID: c.ID,
diff --git a/pkg/types/alertmanagertypes/channelconvertors_test.go b/pkg/types/alertmanagertypes/channelconvertors_test.go
index 850cfd2bbc..36ca862c1e 100644
--- a/pkg/types/alertmanagertypes/channelconvertors_test.go
+++ b/pkg/types/alertmanagertypes/channelconvertors_test.go
@@ -18,7 +18,7 @@ import (
// field fails rather than going unasserted. Webhook is covered by
// TestPostableChannelToReceiverRoundTripsWebhookAuthModes, whose auth modes are
// mutually exclusive and so cannot all be set at once.
-func TestChannelToPostableChannelRoundTripsEveryFieldOfEveryKind(t *testing.T) {
+func TestDeriveChannelConfigRoundTripsEveryFieldOfEveryKind(t *testing.T) {
sendResolved := true
short := true
@@ -269,18 +269,14 @@ func TestChannelToPostableChannelRoundTripsEveryFieldOfEveryKind(t *testing.T) {
}
require.NoError(t, postable.Validate())
- receiver, err := postable.ToReceiver()
+ channel, _, err := postable.ToChannel("org-1")
require.NoError(t, err)
- channel, err := NewChannelFromReceiverWithName(receiver, postable.Name, "org-1")
+ derived, err := channel.deriveChannelConfig()
require.NoError(t, err)
- roundTripped, err := channel.toPostableNotificationChannel()
- require.NoError(t, err)
-
- assert.Equal(t, postable.Name, roundTripped.Name)
- assert.Equal(t, testCase.kind, roundTripped.Config.Kind)
- assert.Equal(t, testCase.expectedRoundTrip, roundTripped.Config.Spec)
+ assert.Equal(t, testCase.kind, derived.Kind)
+ assert.Equal(t, testCase.expectedRoundTrip, derived.Spec)
})
}
}
@@ -298,10 +294,7 @@ func TestPostableChannelToReceiverOmitsEmailTransportCredentials(t *testing.T) {
},
}
- receiver, err := postable.ToReceiver()
- require.NoError(t, err)
-
- channel, err := NewChannelFromReceiverWithName(receiver, postable.Name, "org-1")
+ channel, _, err := postable.ToChannel("org-1")
require.NoError(t, err)
for _, credentialKey := range []string{"auth_username", "auth_password", "auth_secret", "tls_config"} {
@@ -353,16 +346,13 @@ func TestPostableChannelToReceiverRoundTripsWebhookAuthModes(t *testing.T) {
}
require.NoError(t, postable.Validate())
- receiver, err := postable.ToReceiver()
- require.NoError(t, err)
-
- channel, err := NewChannelFromReceiverWithName(receiver, postable.Name, "org-1")
+ channel, _, err := postable.ToChannel("org-1")
require.NoError(t, err)
assert.Contains(t, channel.Data, testCase.expectedInData)
- roundTripped, err := channel.toPostableNotificationChannel()
+ derived, err := channel.deriveChannelConfig()
require.NoError(t, err)
- assert.Equal(t, testCase.expectedRoundTrip, roundTripped.Config.Spec)
+ assert.Equal(t, testCase.expectedRoundTrip, derived.Spec)
})
}
}
@@ -375,7 +365,7 @@ func TestRejectUnrepresentableHTTPConfigCoversEveryUpstreamMember(t *testing.T)
assert.Equal(t, 5, reflect.TypeFor[commoncfg.ProxyConfig]().NumField())
}
-func TestChannelToPostableChannelRejectsUnrepresentableChannels(t *testing.T) {
+func TestDeriveChannelConfigRejectsUnrepresentableChannels(t *testing.T) {
testCases := []struct {
description string
channel Channel
@@ -537,7 +527,7 @@ func TestChannelToPostableChannelRejectsUnrepresentableChannels(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.description, func(t *testing.T) {
- _, err := testCase.channel.toPostableNotificationChannel()
+ _, err := testCase.channel.deriveChannelConfig()
assert.Error(t, err)
})
}
@@ -545,7 +535,7 @@ func TestChannelToPostableChannelRejectsUnrepresentableChannels(t *testing.T) {
// The HTTP auth scheme is case-insensitive (RFC 7235) and Alertmanager sends
// the stored spelling verbatim, so a hand-written receiver may carry any casing.
-func TestChannelToPostableChannelReadsWebhookBearerSchemeCaseInsensitively(t *testing.T) {
+func TestDeriveChannelConfigReadsWebhookBearerSchemeCaseInsensitively(t *testing.T) {
sendResolved := config.DefaultWebhookConfig.VSendResolved
testCases := []struct {
@@ -574,10 +564,10 @@ func TestChannelToPostableChannelReadsWebhookBearerSchemeCaseInsensitively(t *te
t.Run(testCase.name, func(t *testing.T) {
channel := Channel{DisplayName: "hook", Data: testCase.storedChannelData}
- postable, err := channel.toPostableNotificationChannel()
+ derived, err := channel.deriveChannelConfig()
require.NoError(t, err)
- assert.Equal(t, ChannelKindWebhook, postable.Config.Kind)
- assert.Equal(t, testCase.expectedWebhookSpec, postable.Config.Spec)
+ assert.Equal(t, ChannelKindWebhook, derived.Kind)
+ assert.Equal(t, testCase.expectedWebhookSpec, derived.Spec)
})
}
}
diff --git a/pkg/types/alertmanagertypes/channelkind.go b/pkg/types/alertmanagertypes/channelkind.go
new file mode 100644
index 0000000000..e4bb26a782
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelkind.go
@@ -0,0 +1,78 @@
+package alertmanagertypes
+
+import (
+ "slices"
+ "strings"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+var (
+ ErrCodeChannelUnsupportedKind = errors.MustNewCode("channel_unsupported_kind")
+)
+
+// ChannelKind selects which ChannelSpec a channel carries and which notifier
+// integration is built for it.
+type ChannelKind struct {
+ valuer.String
+}
+
+var (
+ ChannelKindSlack = ChannelKind{valuer.NewString("slack")}
+ ChannelKindEmail = ChannelKind{valuer.NewString("email")}
+ ChannelKindWebhook = ChannelKind{valuer.NewString("webhook")}
+ ChannelKindPagerduty = ChannelKind{valuer.NewString("pagerduty")}
+ ChannelKindOpsgenie = ChannelKind{valuer.NewString("opsgenie")}
+ ChannelKindMSTeams = ChannelKind{valuer.NewString("msteams")}
+ ChannelKindGoogleChat = ChannelKind{valuer.NewString("googlechat")}
+ ChannelKindJira = ChannelKind{valuer.NewString("jira")}
+ ChannelKindJSMOps = ChannelKind{valuer.NewString("jsmops")}
+ ChannelKindIncidentIO = ChannelKind{valuer.NewString("incidentio")}
+)
+
+func (ChannelKind) Enum() []any {
+ kinds := make([]any, 0, len(channelKinds))
+ for _, channelKind := range channelKinds {
+ kinds = append(kinds, channelKind.kind)
+ }
+ return kinds
+}
+
+func (t ChannelKind) IsValid() bool {
+ return slices.ContainsFunc(t.Enum(), func(v any) bool { return v == t })
+}
+
+func ErrUnsupportedChannelKind(s string) error {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeChannelUnsupportedKind, "unknown notification channel kind %q; allowed values: %s", s, allowedValuesForChannelKind())
+}
+
+// parseChannelKind reads a stored type. It reports false for the notifier
+// kinds v1 accepted but v2 does not model.
+func parseChannelKind(storedType string) (ChannelKind, bool) {
+ channelKind := ChannelKind{valuer.NewString(storedType)}
+ if !channelKind.IsValid() {
+ return ChannelKind{}, false
+ }
+
+ return channelKind, true
+}
+
+func allowedValuesForChannelKind() string {
+ return formatAllowedValues((ChannelKind{}).Enum())
+}
+
+func formatAllowedValues(enum []any) string {
+ values := make([]string, 0, len(enum))
+ for _, value := range enum {
+ stringValuer, ok := value.(interface{ StringValue() string })
+ if !ok {
+ continue
+ }
+
+ values = append(values, "`"+stringValuer.StringValue()+"`")
+ }
+ slices.Sort(values)
+
+ return strings.Join(values, ", ")
+}
diff --git a/pkg/types/alertmanagertypes/channelkindregistry.go b/pkg/types/alertmanagertypes/channelkindregistry.go
new file mode 100644
index 0000000000..261605b689
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelkindregistry.go
@@ -0,0 +1,86 @@
+package alertmanagertypes
+
+type channelKindEntry struct {
+ kind ChannelKind
+ newEmptySpec func() ChannelSpec
+ // countConfigs guards extractSpec, which reads the receiver's first config of
+ // this kind and so must not be called when there is none.
+ countConfigs func(receiver *Receiver) int
+ extractSpec func(name string, receiver *Receiver) (ChannelSpec, error)
+}
+
+// channelKinds registers each notification kind with the spec constructor
+// UnmarshalJSON picks by kind and the extractor that reads a stored receiver
+// back. The ChannelKind enum derives from it; the JSON schema hooks stay
+// literal lists so each branch reads as one line.
+var channelKinds = []channelKindEntry{
+ {
+ kind: ChannelKindSlack,
+ newEmptySpec: func() ChannelSpec { return new(ChannelSlackConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.SlackConfigs) },
+ extractSpec: newChannelSlackConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindEmail,
+ newEmptySpec: func() ChannelSpec { return new(ChannelEmailConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.EmailConfigs) },
+ extractSpec: newChannelEmailConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindWebhook,
+ newEmptySpec: func() ChannelSpec { return new(ChannelWebhookConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.WebhookConfigs) },
+ extractSpec: newChannelWebhookConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindPagerduty,
+ newEmptySpec: func() ChannelSpec { return new(ChannelPagerdutyConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.PagerdutyConfigs) },
+ extractSpec: newChannelPagerdutyConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindOpsgenie,
+ newEmptySpec: func() ChannelSpec { return new(ChannelOpsgenieConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.OpsGenieConfigs) },
+ extractSpec: newChannelOpsgenieConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindMSTeams,
+ newEmptySpec: func() ChannelSpec { return new(ChannelMSTeamsConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.MSTeamsV2Configs) },
+ extractSpec: newChannelMSTeamsConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindGoogleChat,
+ newEmptySpec: func() ChannelSpec { return new(ChannelGoogleChatConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.GoogleChatConfigs) },
+ extractSpec: newChannelGoogleChatConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindJira,
+ newEmptySpec: func() ChannelSpec { return new(ChannelJiraConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.JiraConfigs) },
+ extractSpec: newChannelJiraConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindJSMOps,
+ newEmptySpec: func() ChannelSpec { return new(ChannelJSMOpsConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.JSMOpsConfigs) },
+ extractSpec: newChannelJSMOpsConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindIncidentIO,
+ newEmptySpec: func() ChannelSpec { return new(ChannelIncidentIOConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.IncidentIOConfigs) },
+ extractSpec: newChannelIncidentIOConfigFromReceiver,
+ },
+}
+
+func buildEmptyChannelSpecForKind(kind ChannelKind) (ChannelSpec, bool) {
+ for _, channelKind := range channelKinds {
+ if channelKind.kind == kind {
+ return channelKind.newEmptySpec(), true
+ }
+ }
+ return nil, false
+}
diff --git a/pkg/types/alertmanagertypes/channellist_test.go b/pkg/types/alertmanagertypes/channellist_test.go
index 81d345fb43..ae3b12ef64 100644
--- a/pkg/types/alertmanagertypes/channellist_test.go
+++ b/pkg/types/alertmanagertypes/channellist_test.go
@@ -53,23 +53,3 @@ func TestChannelToListedChannelLeavesUnmodelledKindsEmpty(t *testing.T) {
assert.Equal(t, "tg", listed.Name)
assert.True(t, listed.Kind.IsZero())
}
-
-// msteams is the only kind whose stored Channel.Type differs from the api kind,
-// so ToStoredType has to agree with the type the write path derives.
-func TestChannelKindMSTeamsIsStoredAsMSTeamsV2(t *testing.T) {
- assert.Equal(t, "msteamsv2", ChannelKindMSTeams.ToStoredType())
-
- postable := PostableNotificationChannel{
- Name: "channel",
- DisplayName: "channel",
- Config: ChannelConfig{Kind: ChannelKindMSTeams, Spec: &ChannelMSTeamsConfig{WebhookURL: "https://a"}},
- }
-
- receiver, err := postable.ToReceiver()
- require.NoError(t, err)
-
- channel, err := NewChannelFromReceiverWithName(receiver, postable.Name, "org-1")
- require.NoError(t, err)
-
- assert.Equal(t, "msteamsv2", channel.Type)
-}
diff --git a/pkg/types/alertmanagertypes/channelrepair.go b/pkg/types/alertmanagertypes/channelrepair.go
index b8b8ee47b3..f91c5152ea 100644
--- a/pkg/types/alertmanagertypes/channelrepair.go
+++ b/pkg/types/alertmanagertypes/channelrepair.go
@@ -93,7 +93,7 @@ func (c *Channel) Diagnose() *ChannelRepair {
return repair
}
- if _, err := c.toPostableNotificationChannel(); err != nil {
+ if _, err := c.toChannelConfig(); err != nil {
repair.Defect, repair.Detail = ChannelDefectUnrepresentable, err.Error()
return repair
}
@@ -117,7 +117,10 @@ func (c *Channel) Retype() error {
// SplitByNotifier turns a receiver carrying several notifier configurations into
// one channel per configuration. The first keeps this channel's identity so
-// references to it stay valid; the rest are new channels numbered after it.
+// references to it stay valid; the rest are new channels numbered after it. A
+// part of a kind v2 does not model is kept without a spec, as the migration
+// leaves such a row, so v1 still delivers through it until its own repair
+// deletes it.
func (c *Channel) SplitByNotifier() ([]*Channel, error) {
receiver, err := NewReceiver(c.Data)
if err != nil {
@@ -129,21 +132,28 @@ func (c *Channel) SplitByNotifier() ([]*Channel, error) {
return nil, errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q carries %d notifier configuration; nothing to split", c.DisplayName, len(singles))
}
- if err := c.Update(singles[0]); err != nil {
- return nil, err
- }
+ parts := make([]*Channel, 0, len(singles))
+ for i, single := range singles {
+ if i > 0 {
+ single.Name = fmt.Sprintf("%s (%d)", c.DisplayName, i+1)
+ }
- channels := []*Channel{c}
- for i, single := range singles[1:] {
- single.Name = fmt.Sprintf("%s (%d)", c.DisplayName, i+2)
- channel, err := NewChannelFromReceiver(single, c.OrgID)
+ var part *Channel
+ if hasModelledNotifier(single) {
+ part, err = NewChannelFromReceiver(single, c.OrgID)
+ } else {
+ part, err = newChannelWithoutSpec(single, c.OrgID)
+ }
if err != nil {
return nil, err
}
- channels = append(channels, channel)
+ parts = append(parts, part)
}
- return channels, nil
+ c.Type, c.Data, c.Spec, c.StoredSpec = parts[0].Type, parts[0].Data, parts[0].Spec, parts[0].StoredSpec
+ c.UpdatedAt = time.Now()
+
+ return append([]*Channel{c}, parts[1:]...), nil
}
func hasModelledNotifier(receiver *Receiver) bool {
diff --git a/pkg/types/alertmanagertypes/channelspec.go b/pkg/types/alertmanagertypes/channelspec.go
new file mode 100644
index 0000000000..7d7137b66c
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelspec.go
@@ -0,0 +1,131 @@
+package alertmanagertypes
+
+import (
+ "net/url"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/prometheus/alertmanager/config"
+ commoncfg "github.com/prometheus/common/config"
+)
+
+type ChannelSpec interface {
+ Validate() error
+ toUndefaultedReceiver(displayName string) (*Receiver, error)
+}
+
+// parseSecretURL and parseUpstreamURL wrap the two URL types upstream uses for
+// notifier endpoints. Callers holding an optional URL skip the call on an empty
+// string, so the field stays nil and is omitted rather than stored as an empty URL.
+func parseSecretURL(raw string) (*config.SecretURL, error) {
+ parsed, err := parseUpstreamURL(raw)
+ if err != nil {
+ return nil, err
+ }
+
+ return (*config.SecretURL)(parsed), nil
+}
+
+func parseUpstreamURL(raw string) (*config.URL, error) {
+ parsed, err := url.Parse(raw)
+ if err != nil {
+ return nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "parse url %q", raw)
+ }
+
+ return &config.URL{URL: parsed}, nil
+}
+
+func formatSecretURL(secretURL *config.SecretURL) string {
+ if secretURL == nil {
+ return ""
+ }
+
+ return formatUpstreamURL((*config.URL)(secretURL))
+}
+
+func formatUpstreamURL(upstreamURL *config.URL) string {
+ if upstreamURL == nil || upstreamURL.URL == nil {
+ return ""
+ }
+
+ return upstreamURL.String()
+}
+
+func rejectAnyHTTPAuth(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
+ if httpConfig == nil {
+ return nil
+ }
+
+ if httpConfig.BasicAuth != nil {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.basic_auth, which is not supported", channelName)
+ }
+
+ if httpConfig.Authorization != nil {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.authorization, which is not supported", channelName)
+ }
+
+ return rejectUnsupportedHTTPConfig(channelName, httpConfig)
+}
+
+func rejectUnsupportedHTTPConfig(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
+ if httpConfig == nil {
+ return nil
+ }
+
+ for _, field := range []struct {
+ fieldName string
+ isFieldConfigured bool
+ }{
+ {"oauth2", httpConfig.OAuth2 != nil},
+ {"bearer_token", httpConfig.BearerToken != ""},
+ {"bearer_token_file", httpConfig.BearerTokenFile != ""},
+ {"proxy_url", httpConfig.ProxyURL.URL != nil && httpConfig.ProxyURL.String() != ""},
+ {"no_proxy", httpConfig.NoProxy != ""},
+ {"proxy_from_environment", httpConfig.ProxyFromEnvironment},
+ {"http_headers", httpConfig.HTTPHeaders != nil},
+ {"tls_config", httpConfig.TLSConfig != (commoncfg.TLSConfig{})},
+ {"follow_redirects", !httpConfig.FollowRedirects},
+ {"enable_http2", !httpConfig.EnableHTTP2},
+ } {
+ if field.isFieldConfigured {
+ return errors.NewInvalidInputf(
+ ErrCodeAlertmanagerChannelInvalid,
+ "channel %q sets http_config.%s, which is not supported", channelName, field.fieldName,
+ )
+ }
+ }
+
+ return nil
+}
+
+func rejectHTTPBasicAuthBeyondPassword(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
+ if httpConfig == nil || httpConfig.BasicAuth == nil {
+ return nil
+ }
+
+ basicAuth := httpConfig.BasicAuth
+ if *basicAuth != (commoncfg.BasicAuth{Username: basicAuth.Username, Password: basicAuth.Password}) {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.basic_auth with fields other than username and password, which is not supported", channelName)
+ }
+
+ return nil
+}
+
+// fillSendResolved gives an omitted field its notifier default, so what is
+// stored and read back is what takes effect.
+func fillSendResolved(sendResolved **bool, upstreamDefault bool) {
+ if *sendResolved == nil {
+ value := upstreamDefault
+ *sendResolved = &value
+ }
+}
+
+// resolveSendResolved covers a spec assembled in code rather than decoded, whose
+// defaults were never filled. send_resolved has no omitempty, so a zero value
+// would marshal as an explicit false and overwrite the default rather than leave it.
+func resolveSendResolved(sendResolved *bool, upstreamDefault bool) bool {
+ if sendResolved == nil {
+ return upstreamDefault
+ }
+
+ return *sendResolved
+}
diff --git a/pkg/types/alertmanagertypes/channelv1.go b/pkg/types/alertmanagertypes/channelv1.go
new file mode 100644
index 0000000000..cb16a3c32f
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelv1.go
@@ -0,0 +1,181 @@
+package alertmanagertypes
+
+import (
+ "encoding/json"
+ "reflect"
+ "strings"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/prometheus/alertmanager/config"
+ "github.com/swaggest/jsonschema-go"
+)
+
+type PostableChannel struct {
+ Receiver
+}
+
+func (PostableChannel) JSONSchema() (jsonschema.Schema, error) {
+ type alias PostableChannel
+ reflector := &jsonschema.Reflector{}
+
+ schema, err := reflector.Reflect(alias{}, jsonschema.DefinitionsPrefix("#/components/schemas/"))
+ if err != nil {
+ return jsonschema.Schema{}, err
+ }
+
+ schema.WithRequired("name")
+
+ var oneOf []jsonschema.SchemaOrBool
+ seen := map[string]struct{}{}
+ // Walk both halves: native fields on Receiver, upstream on the embed. A native
+ // field can shadow an upstream one with the same tag (e.g. jira_configs), so
+ // dedupe to avoid emitting two identical oneOf branches.
+ collect := func(t reflect.Type) {
+ for i := 0; i < t.NumField(); i++ {
+ jsonTag := strings.Split(t.Field(i).Tag.Get("json"), ",")[0]
+ if !strings.HasSuffix(jsonTag, "_configs") {
+ continue
+ }
+ if _, ok := seen[jsonTag]; ok {
+ continue
+ }
+ seen[jsonTag] = struct{}{}
+ branch := (&jsonschema.Schema{}).WithRequired(jsonTag)
+ oneOf = append(oneOf, branch.ToSchemaOrBool())
+ }
+ }
+ collect(reflect.TypeOf(Receiver{}))
+ collect(reflect.TypeOf(config.Receiver{}))
+
+ schema.WithOneOf(oneOf...)
+
+ return schema, nil
+}
+
+// NewChannelFromReceiver builds the channel a v1 write carries. The receiver is
+// all there is, so the name is generated from its display name and the type and
+// spec derived from it.
+func NewChannelFromReceiver(receiver *Receiver, orgID string) (*Channel, error) {
+ channel, err := newChannelWithoutSpec(receiver, orgID)
+ if err != nil {
+ return nil, err
+ }
+
+ // A receiver v2 cannot represent is refused rather than stored, so every
+ // row written from here on reads through v2.
+ channelConfig, err := channel.deriveChannelConfig()
+ if err != nil {
+ return nil, err
+ }
+ spec, err := channelConfig.toChannelSpec()
+ if err != nil {
+ return nil, err
+ }
+ if err := channel.fillSpec(spec); err != nil {
+ return nil, err
+ }
+
+ return channel, nil
+}
+
+func (c *Channel) Update(receiver *Receiver) error {
+ channel, err := NewChannelFromReceiver(receiver, c.OrgID)
+ if err != nil {
+ return err
+ }
+
+ if c.DisplayName != channel.DisplayName {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeAlertmanagerChannelNameMismatch, "cannot update channel name")
+ }
+
+ c.Type = channel.Type
+ c.Data = channel.Data
+ c.Spec, c.StoredSpec = channel.Spec, channel.StoredSpec
+ c.UpdatedAt = time.Now()
+
+ return nil
+}
+
+// ToV1Channel copies the channel with its type named as v1 always has, after
+// upstream's msteamsv2_configs list rather than the kind. Goes with the v1 API.
+func (c *Channel) ToV1Channel() *Channel {
+ v1 := *c
+ if c.Type == ChannelKindMSTeams.StringValue() {
+ v1.Type = "msteamsv2"
+ }
+
+ return &v1
+}
+
+func newChannelWithoutSpec(receiver *Receiver, orgID string) (*Channel, error) {
+ if receiver.Name == DefaultReceiverName {
+ return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeAlertmanagerChannelInvalid, "cannot use %s name as a channel name", receiver.Name)
+ }
+
+ channelType := receiverChannelType(receiver)
+ if channelType == "" {
+ return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeAlertmanagerChannelInvalid, "channel '%s' must have at least one notification configuration (e.g., email_configs, webhook_configs, slack_configs)", receiver.Name)
+ }
+
+ data, err := json.Marshal(receiver)
+ if err != nil {
+ return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot save channel %q notification configuration", receiver.Name)
+ }
+
+ return &Channel{
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ TimeAuditable: types.TimeAuditable{CreatedAt: time.Now(), UpdatedAt: time.Now()},
+ Name: generateChannelName(receiver.Name),
+ DisplayName: receiver.Name,
+ Type: channelType,
+ Data: string(data),
+ OrgID: orgID,
+ }, nil
+}
+
+// receiverChannelType returns the type a channel is stored under: the kind for
+// a notifier v2 models, else the notifier's own *_configs name. For the latter
+// it walks Receiver's own fields first (native), then the embed (upstream);
+// first non-empty *_configs slice wins.
+func receiverChannelType(receiver *Receiver) string {
+ for _, channelKind := range channelKinds {
+ if channelKind.countConfigs(receiver) > 0 {
+ return channelKind.kind.StringValue()
+ }
+ }
+ if t := nonEmptyConfigsField(reflect.ValueOf(*receiver)); t != "" {
+ return t
+ }
+ if t := nonEmptyConfigsField(reflect.ValueOf(*receiver.Receiver)); t != "" {
+ return t
+ }
+ return ""
+}
+
+func nonEmptyConfigsField(v reflect.Value) string {
+ t := v.Type()
+ for i := 0; i < t.NumField(); i++ {
+ field := t.Field(i)
+ fieldVal := v.Field(i)
+
+ if fieldVal.Kind() != reflect.Slice || fieldVal.Len() == 0 {
+ continue
+ }
+
+ yamlTag := field.Tag.Get("yaml")
+ if yamlTag == "" {
+ continue
+ }
+
+ // Extract the base type name (e.g., "email_configs" -> "email").
+ matches := receiverTypeRegex.FindStringSubmatch(yamlTag)
+ if len(matches) != 2 {
+ continue
+ }
+ return matches[1]
+ }
+ return ""
+}
diff --git a/pkg/valuer/unset_or_non_empty_string.go b/pkg/valuer/unset_or_non_empty_string.go
index ac0bd65e03..21f9572b9d 100644
--- a/pkg/valuer/unset_or_non_empty_string.go
+++ b/pkg/valuer/unset_or_non_empty_string.go
@@ -44,6 +44,12 @@ func (enum UnsetOrNonEmptyString) IsZero() bool {
return enum.val == ""
}
+func (enum *UnsetOrNonEmptyString) SetIfUnset(val string) {
+ if enum.IsZero() {
+ enum.val = val
+ }
+}
+
func (enum UnsetOrNonEmptyString) StringValue() string {
return enum.val
}
diff --git a/tests/fixtures/notification_channel.py b/tests/fixtures/notification_channel.py
index 73c510ad6a..e9f3c00adc 100644
--- a/tests/fixtures/notification_channel.py
+++ b/tests/fixtures/notification_channel.py
@@ -1,4 +1,5 @@
# pylint: disable=line-too-long
+import hashlib
import json
import time
from collections.abc import Callable
@@ -8,6 +9,7 @@ import docker
import docker.errors
import pytest
import requests
+from sqlalchemy import sql
from testcontainers.core.container import Network
from wiremock.testing.testcontainer import WireMockContainer
@@ -46,6 +48,34 @@ def assert_email_channel_payload_clean(payload: str) -> None:
assert SMTP_TEST_FROM not in payload
+def rewrite_channel_as_legacy_receiver(signoz: types.SigNoz, channel_id: str, receiver: dict) -> None:
+ """Overwrite a channel row, and its receiver in the org's alertmanager config,
+ the way the spec migration leaves a row it cannot fill. Neither API writes
+ such rows any more, so tests that need one seed it here. The receiver's name
+ must be the channel's display name. The alertmanager picks the swapped
+ receiver up on its next poll of the stored config."""
+ configs_key = next(key for key in receiver if key.endswith("_configs"))
+ # Storage names the kind; only msteams differs from its upstream configs list.
+ notifier_type = "msteams" if configs_key == "msteamsv2_configs" else configs_key.removesuffix("_configs")
+ with signoz.sqlstore.conn.connect() as conn:
+ conn.execute(
+ sql.text("UPDATE notification_channel SET type = :type, data = :data, spec = NULL WHERE id = :id"),
+ {"id": channel_id, "type": notifier_type, "data": json.dumps(receiver)},
+ )
+ org_id, stored = conn.execute(
+ sql.text("SELECT c.org_id, c.config FROM alertmanager_config c JOIN notification_channel n ON n.org_id = c.org_id WHERE n.id = :id"),
+ {"id": channel_id},
+ ).one()
+ config = json.loads(stored)
+ config["receivers"] = [receiver if existing["name"] == receiver["name"] else existing for existing in config["receivers"]]
+ raw = json.dumps(config)
+ conn.execute(
+ sql.text("UPDATE alertmanager_config SET config = :config, hash = :hash WHERE org_id = :org_id"),
+ {"config": raw, "hash": hashlib.md5(raw.encode()).hexdigest(), "org_id": org_id},
+ )
+ conn.commit()
+
+
"""
Default notification channel configs shared across alertmanager tests.
"""
diff --git a/tests/integration/tests/alertmanager/04_notification_channels_v2.py b/tests/integration/tests/alertmanager/04_notification_channels_v2.py
index d4fb9a5347..47377373e3 100644
--- a/tests/integration/tests/alertmanager/04_notification_channels_v2.py
+++ b/tests/integration/tests/alertmanager/04_notification_channels_v2.py
@@ -18,15 +18,20 @@ V2_BASE_URL = "/api/v2/notification_channels"
DNS1123_LABEL = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
-_EDITOR_EMAIL = "[email protected]"
-_VIEWER_EMAIL = "[email protected]"
-_PASSWORD = "password123Z$"
-
@pytest.mark.parametrize(
- "kind,spec,assert_field,assert_value",
+ "kind,request_spec",
[
- pytest.param("slack", {"apiUrl": "https://hooks.slack.test/services/T/B/X", "channel": "#alerts", "title": "Alert", "text": "{{ .CommonLabels.alertname }}"}, "channel", "#alerts", id="slack"),
+ pytest.param(
+ "slack",
+ {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "channel": "#alerts",
+ "title": "Alert",
+ "text": "{{ .CommonLabels.alertname }}",
+ },
+ id="slack",
+ ),
pytest.param(
"slack",
{
@@ -36,42 +41,212 @@ _PASSWORD = "password123Z$"
"titleLink": "{{ .CommonLabels.ruleSource }}",
"footer": "platform · terraform",
"fields": [{"title": "Severity", "value": "{{ .CommonLabels.severity }}", "short": True}],
- "actions": [{"type": "button", "text": "Open in SigNoz", "url": "{{ .CommonLabels.ruleSource }}"}],
+ "actions": [{"type": "button", "text": "Open in SigNoz", "url": "{{ .CommonLabels.ruleSource }}", "style": "primary", "name": "open", "value": "signoz"}],
+ },
+ id="slack_with_fields_and_actions",
+ ),
+ pytest.param(
+ "slack",
+ {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "channel": "",
+ "fields": [],
+ "actions": [],
+ },
+ id="slack_with_empty_values",
+ ),
+ pytest.param(
+ "email",
+ {
+ "html": "<p>{{ .CommonLabels.alertname }}</p>",
+ },
+ id="email",
+ ),
+ pytest.param(
+ "email",
+ {
+ "headers": {},
+ },
+ id="email_with_empty_headers",
+ ),
+ pytest.param(
+ "webhook",
+ {
+ "url": "https://webhook.test/hook",
+ "username": "bob",
+ "password": "s3cret",
},
- "fields",
- [{"title": "Severity", "value": "{{ .CommonLabels.severity }}", "short": True}],
- id="slack-attachment",
+ id="webhook",
+ ),
+ pytest.param(
+ "webhook",
+ {
+ "url": "https://webhook.test/hook",
+ "username": "",
+ "password": "",
+ "bearerToken": "",
+ },
+ id="webhook_with_empty_auth",
+ ),
+ pytest.param(
+ "pagerduty",
+ {
+ "routingKey": "pd-routing-key",
+ "severity": "critical",
+ "class": "db",
+ "description": "{{ .CommonLabels.alertname }}",
+ },
+ id="pagerduty",
+ ),
+ pytest.param(
+ "pagerduty",
+ {
+ "routingKey": "pd-routing-key",
+ "url": "",
+ "severity": "",
+ "component": "",
+ "group": "",
+ "class": "",
+ "details": {},
+ },
+ id="pagerduty_with_empty_values",
+ ),
+ # A sent map reads back as sent, without the default entries.
+ pytest.param(
+ "pagerduty",
+ {
+ "routingKey": "pd-routing-key",
+ "details": {"env": "prod", "team": "platform"},
+ },
+ id="pagerduty_with_details",
+ ),
+ pytest.param(
+ "opsgenie",
+ {
+ "apiKey": "og-api-key",
+ "message": "{{ .CommonLabels.alertname }}",
+ "description": "{{ .CommonLabels.alertname }}",
+ "priority": "P2",
+ },
+ id="opsgenie",
+ ),
+ pytest.param(
+ "opsgenie",
+ {
+ "apiKey": "og-api-key",
+ "apiUrl": "",
+ "priority": "",
+ "details": {},
+ },
+ id="opsgenie_with_empty_values",
+ ),
+ pytest.param(
+ "msteams",
+ {
+ "webhookUrl": "https://teams.test/webhook/abc",
+ "title": "Alert",
+ "text": "{{ .CommonLabels.alertname }}",
+ },
+ id="msteams",
),
- pytest.param("email", {"to": "[email protected]", "html": "<p>{{ .CommonLabels.alertname }}</p>"}, "to", "[email protected]", id="email"),
- pytest.param("webhook", {"url": "https://webhook.test/hook", "username": "bob", "password": "s3cret"}, "username", "bob", id="webhook"),
- pytest.param("pagerduty", {"routingKey": "pd-routing-key", "severity": "critical", "class": "db", "description": "{{ .CommonLabels.alertname }}"}, "severity", "critical", id="pagerduty"),
- pytest.param("opsgenie", {"apiKey": "og-api-key", "message": "{{ .CommonLabels.alertname }}", "description": "{{ .CommonLabels.alertname }}", "priority": "P2"}, "priority", "P2", id="opsgenie"),
- pytest.param("msteams", {"webhookUrl": "https://teams.test/webhook/abc", "title": "Alert", "text": "{{ .CommonLabels.alertname }}"}, "title", "Alert", id="msteams"),
# The google chat notifier only accepts https URLs on chat.googleapis.com.
- pytest.param("googlechat", {"webhookUrl": "https://chat.googleapis.com/v1/spaces/A/messages?key=k&token=t", "title": "Alert", "text": "{{ .CommonLabels.alertname }}"}, "title", "Alert", id="googlechat"),
+ pytest.param(
+ "googlechat",
+ {
+ "webhookUrl": "https://chat.googleapis.com/v1/spaces/A/messages?key=k&token=t",
+ "title": "Alert",
+ "text": "{{ .CommonLabels.alertname }}",
+ },
+ id="googlechat",
+ ),
# The jira notifier only accepts Jira Cloud sites and basic auth.
- pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token", "summary": "Alert", "description": "{{ .CommonLabels.alertname }}", "customFields": {"customfield_10010": "Ops"}}, "project", "OPS", id="jira"),
- pytest.param("jsmops", {"apiKey": "jsm-api-key", "message": "Alert", "description": "{{ .CommonLabels.alertname }}", "priority": "P2"}, "priority", "P2", id="jsmops"),
+ pytest.param(
+ "jira",
+ {
+ "site": "https://acme.atlassian.net",
+ "project": "OPS",
+ "issueType": "Bug",
+ "email": "[email protected]",
+ "apiToken": "jira-api-token",
+ "summary": "Alert",
+ "description": "{{ .CommonLabels.alertname }}",
+ "customFields": {"customfield_10010": "Ops"},
+ },
+ id="jira",
+ ),
+ pytest.param(
+ "jira",
+ {
+ "site": "https://acme.atlassian.net",
+ "project": "OPS",
+ "issueType": "Bug",
+ "email": "[email protected]",
+ "apiToken": "jira-api-token",
+ "priority": "",
+ "labels": [],
+ "resolveTransition": "",
+ "reopenTransition": "",
+ "wontFixResolution": "",
+ "customFields": {},
+ },
+ id="jira_with_empty_values",
+ ),
+ pytest.param(
+ "jsmops",
+ {
+ "apiKey": "jsm-api-key",
+ "message": "Alert",
+ "description": "{{ .CommonLabels.alertname }}",
+ "priority": "P2",
+ },
+ id="jsmops",
+ ),
+ pytest.param(
+ "jsmops",
+ {
+ "apiKey": "jsm-api-key",
+ "priority": "",
+ },
+ id="jsmops_with_empty_priority",
+ ),
# The incident.io notifier only accepts an alert source's events URL.
- pytest.param("incidentio", {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF", "token": "incidentio-token", "title": "Alert", "description": "{{ .CommonLabels.alertname }}"}, "title", "Alert", id="incidentio"),
+ pytest.param(
+ "incidentio",
+ {
+ "url": "https://api.incident.io/v2/alert_events/http/01ABCDEF",
+ "token": "incidentio-token",
+ "title": "Alert",
+ "description": "{{ .CommonLabels.alertname }}",
+ },
+ id="incidentio",
+ ),
+ pytest.param(
+ "incidentio",
+ {
+ "url": "https://api.incident.io/v2/alert_events/http/01ABCDEF",
+ "token": "incidentio-token",
+ "metadata": {},
+ },
+ id="incidentio_with_empty_metadata",
+ ),
],
)
-def test_create_returns_the_channel_for_every_kind( # pylint: disable=too-many-arguments,too-many-positional-arguments
+def test_create_channel( # pylint: disable=too-many-arguments,too-many-positional-arguments
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
cleanup_notification_channels: list[str],
kind: str,
- spec: dict,
- assert_field: str,
- assert_value: str,
+ request_spec: dict,
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
name = f"v2-{kind}-{uuid.uuid4().hex[:8]}"
response = requests.post(
signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": name, "displayName": f"Display {name}", "config": {"kind": kind, "spec": spec}},
+ json={"name": name, "config": {"kind": kind, "spec": request_spec}},
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
)
@@ -80,121 +255,253 @@ def test_create_returns_the_channel_for_every_kind( # pylint: disable=too-many-
created = response.json()["data"]
cleanup_notification_channels.append(created["id"])
- assert created["name"] == name
- assert created["displayName"] == f"Display {name}"
- assert created["config"]["kind"] == kind
- assert created["config"]["spec"][assert_field] == assert_value
- assert created["createdAt"]
- assert created["updatedAt"]
-
-
- "kind,spec,expected_send_resolved",
- [
- pytest.param("slack", {"apiUrl": "https://hooks.slack.test/services/T/B/X", "title": "Alert", "text": "body"}, False, id="slack"),
- pytest.param("email", {"to": "[email protected]", "html": "<p>body</p>"}, False, id="email"),
- pytest.param("webhook", {"url": "https://webhook.test/hook"}, True, id="webhook"),
- pytest.param("pagerduty", {"routingKey": "pd-routing-key", "description": "body"}, True, id="pagerduty"),
- pytest.param("opsgenie", {"apiKey": "og-api-key", "message": "subject", "description": "body", "priority": "P2"}, True, id="opsgenie"),
- pytest.param("msteams", {"webhookUrl": "https://teams.test/webhook/abc", "title": "Alert", "text": "body"}, True, id="msteams"),
- pytest.param("googlechat", {"webhookUrl": "https://chat.googleapis.com/v1/spaces/A/messages?key=k&token=t", "title": "Alert", "text": "body"}, False, id="googlechat"),
- pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token", "summary": "Alert", "description": "body"}, False, id="jira"),
- pytest.param("jsmops", {"apiKey": "jsm-api-key", "message": "Alert", "description": "body"}, False, id="jsmops"),
- pytest.param("incidentio", {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF", "token": "incidentio-token", "title": "Alert", "description": "body"}, False, id="incidentio"),
- ],
-)
-def test_create_without_send_resolved_returns_the_notifier_default( # pylint: disable=too-many-arguments,too-many-positional-arguments
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- cleanup_notification_channels: list[str],
- kind: str,
- spec: dict,
- expected_send_resolved: bool,
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- name = f"v2-sendresolved-{kind}-{uuid.uuid4().hex[:8]}"
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": name, "config": {"kind": kind, "spec": spec}},
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{created['id']}"),
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
)
- assert response.status_code == HTTPStatus.CREATED, response.text
+ assert response.status_code == HTTPStatus.OK, response.text
+ fetched = response.json()["data"]
- created = response.json()["data"]
- cleanup_notification_channels.append(created["id"])
+ assert created["name"] == name
+ assert created["displayName"] == name
+ assert created["config"]["kind"] == kind
+ assert created["createdAt"]
+ assert created["updatedAt"]
- assert created["config"]["spec"]["sendResolved"] is expected_send_resolved
+ ## ensure that every field in the request is a part of the responses.
+ for spec_read in (created["config"]["spec"], fetched["config"]["spec"]):
+ for field, value in request_spec.items():
+ assert spec_read[field] == value, field
@pytest.mark.parametrize(
- "kind,spec,template_fields",
+ "kind,request_spec,expected_defaults,fields_without_default,fields_read_as_null",
[
- pytest.param("slack", {"apiUrl": "https://hooks.slack.test/services/T/B/X"}, ["title", "text"], id="slack"),
- pytest.param("email", {"to": "[email protected]"}, ["html"], id="email"),
- pytest.param("pagerduty", {"routingKey": "pd-routing-key"}, ["description"], id="pagerduty"),
- pytest.param("opsgenie", {"apiKey": "og-api-key"}, ["message", "description"], id="opsgenie"),
- pytest.param("msteams", {"webhookUrl": "https://teams.test/webhook/abc"}, ["title", "text"], id="msteams"),
- pytest.param("googlechat", {"webhookUrl": "https://chat.googleapis.com/v1/spaces/A/messages?key=k&token=t"}, ["title", "text"], id="googlechat"),
- pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token"}, ["summary", "description"], id="jira"),
- pytest.param("jsmops", {"apiKey": "jsm-api-key"}, ["message", "description"], id="jsmops"),
- pytest.param("incidentio", {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF", "token": "incidentio-token"}, ["title", "description"], id="incidentio"),
+ pytest.param(
+ "slack",
+ {"apiUrl": "https://hooks.slack.test/services/T/B/X"},
+ {
+ "sendResolved": False,
+ "title": '{{ template "slack.default.title" . }}',
+ "text": '{{ template "slack.default.text" . }}',
+ "color": '{{ if eq .Status "firing" }}danger{{ else }}good{{ end }}',
+ "titleLink": '{{ template "slack.default.titlelink" . }}',
+ "pretext": '{{ template "slack.default.pretext" . }}',
+ "fallback": '{{ template "slack.default.fallback" . }}',
+ "footer": '{{ template "slack.default.footer" . }}',
+ },
+ ["channel"],
+ ["fields", "actions"],
+ id="slack",
+ ),
+ pytest.param(
+ "email",
+ {"to": "[email protected]"},
+ {
+ "sendResolved": False,
+ "html": '{{ template "email.default.html" . }}',
+ },
+ [],
+ ["headers"],
+ id="email",
+ ),
+ pytest.param(
+ "webhook",
+ {"url": "https://webhook.test/hook"},
+ {
+ "sendResolved": True,
+ },
+ ["username", "password", "bearerToken"],
+ [],
+ id="webhook",
+ ),
+ pytest.param(
+ "pagerduty",
+ {"routingKey": "pd-routing-key"},
+ {
+ "sendResolved": True,
+ "source": '{{ template "pagerduty.default.client" . }}',
+ "client": '{{ template "pagerduty.default.client" . }}',
+ "clientUrl": '{{ template "pagerduty.default.clientURL" . }}',
+ "description": '{{ template "pagerduty.default.description" .}}',
+ "details": {
+ "firing": "{{ .Alerts.Firing | toJson }}",
+ "num_firing": "{{ .Alerts.Firing | len }}",
+ "num_resolved": "{{ .Alerts.Resolved | len }}",
+ "resolved": "{{ .Alerts.Resolved | toJson }}",
+ },
+ },
+ ["url", "severity", "component", "group", "class"],
+ [],
+ id="pagerduty",
+ ),
+ pytest.param(
+ "opsgenie",
+ {"apiKey": "og-api-key"},
+ {
+ "sendResolved": True,
+ "message": '{{ template "opsgenie.default.message" . }}',
+ "description": '{{ template "opsgenie.default.description" . }}',
+ "source": '{{ template "opsgenie.default.source" . }}',
+ },
+ ["apiUrl", "priority"],
+ ["details"],
+ id="opsgenie",
+ ),
+ pytest.param(
+ "msteams",
+ {"webhookUrl": "https://teams.test/webhook/abc"},
+ {
+ "sendResolved": True,
+ "title": '{{ template "msteamsv2.default.title" . }}',
+ "text": '{{ template "msteamsv2.default.text" . }}',
+ },
+ [],
+ [],
+ id="msteams",
+ ),
+ pytest.param(
+ "googlechat",
+ {"webhookUrl": "https://chat.googleapis.com/v1/spaces/A/messages?key=k&token=t"},
+ {
+ "sendResolved": False,
+ "title": '[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}',
+ "text": (
+ "{{ range .Alerts -}}\n**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}{{ if .Annotations.summary }}\n**Summary:** {{ .Annotations.summary }}{{ end }}{{ if .Annotations.description }}\n**Description:** {{ .Annotations.description }}{{ end }}\n{{ end }}"
+ ),
+ },
+ [],
+ [],
+ id="googlechat",
+ ),
+ pytest.param(
+ "jira",
+ {
+ "site": "https://acme.atlassian.net",
+ "project": "OPS",
+ "issueType": "Bug",
+ "email": "[email protected]",
+ "apiToken": "jira-api-token",
+ },
+ {
+ "sendResolved": False,
+ "summary": '[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}',
+ "description": (
+ "{{ range .Alerts -}}\n"
+ "**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}\n"
+ "{{ if .Annotations.summary }}\n"
+ "**Summary:** {{ .Annotations.summary }}\n"
+ "{{ end }}{{ if .Annotations.description }}\n"
+ "**Description:** {{ .Annotations.description }}\n"
+ "{{ end }}\n"
+ "{{ end }}"
+ ),
+ "reopenDuration": "3d",
+ },
+ ["priority", "resolveTransition", "reopenTransition", "wontFixResolution"],
+ ["labels", "customFields"],
+ id="jira",
+ ),
+ pytest.param(
+ "jsmops",
+ {"apiKey": "jsm-api-key"},
+ {
+ "sendResolved": False,
+ "message": '[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}',
+ "description": (
+ "{{ range .Alerts -}}\n"
+ "**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}\n"
+ "\n"
+ "{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}\n"
+ "\n"
+ "{{ end }}{{ if .Annotations.description }}**Description:** {{ .Annotations.description }}\n"
+ "\n"
+ "{{ end }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})\n"
+ "\n"
+ "{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})\n"
+ "\n"
+ "{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})\n"
+ "\n"
+ "{{ end }}{{ end }}"
+ ),
+ "tags": "signoz",
+ },
+ ["priority"],
+ [],
+ id="jsmops",
+ ),
+ pytest.param(
+ "incidentio",
+ {
+ "url": "https://api.incident.io/v2/alert_events/http/01ABCDEF",
+ "token": "incidentio-token",
+ },
+ {
+ "sendResolved": False,
+ "title": '[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}',
+ "description": (
+ "{{ range .Alerts -}}\n"
+ "**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}\n"
+ "\n"
+ "{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}\n"
+ "\n"
+ "{{ end }}{{ if .Annotations.description }}**Description:** {{ .Annotations.description }}\n"
+ "\n"
+ "{{ end }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})\n"
+ "\n"
+ "{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})\n"
+ "\n"
+ "{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})\n"
+ "\n"
+ "{{ end }}{{ end }}"
+ ),
+ },
+ [],
+ ["metadata"],
+ id="incidentio",
+ ),
],
)
-def test_create_without_templates_returns_the_notifier_defaults( # pylint: disable=too-many-arguments,too-many-positional-arguments
+def test_create_minimal_channel( # pylint: disable=too-many-arguments,too-many-positional-arguments
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
cleanup_notification_channels: list[str],
kind: str,
- spec: dict,
- template_fields: list[str],
+ request_spec: dict,
+ expected_defaults: dict,
+ fields_without_default: list[str],
+ fields_read_as_null: list[str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- name = f"v2-templates-{kind}-{uuid.uuid4().hex[:8]}"
response = requests.post(
signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": name, "config": {"kind": kind, "spec": spec}},
+ json={"name": f"v2-minimal-{kind}-{uuid.uuid4().hex[:8]}", "config": {"kind": kind, "spec": request_spec}},
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
)
assert response.status_code == HTTPStatus.CREATED, response.text
-
created = response.json()["data"]
cleanup_notification_channels.append(created["id"])
- for field in template_fields:
- assert "{{" in created["config"]["spec"][field], f"{field} should come back carrying the notifier's default template"
-
-
-def test_create_defaults_display_name_to_name(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- cleanup_notification_channels: list[str],
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- name = f"v2-nodisplay-{uuid.uuid4().hex[:8]}"
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": name, "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{created['id']}"),
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
)
- assert response.status_code == HTTPStatus.CREATED, response.text
-
- created = response.json()["data"]
- cleanup_notification_channels.append(created["id"])
+ assert response.status_code == HTTPStatus.OK, response.text
+ fetched = response.json()["data"]
- assert created["name"] == name
- assert created["displayName"] == name
+ # Omitted fields read back as their default, as "" when they have none, and
+ # as null when they are collections.
+ expected_spec = {**request_spec, **expected_defaults, **dict.fromkeys(fields_without_default, ""), **dict.fromkeys(fields_read_as_null, None)}
+ assert created["config"]["spec"] == expected_spec
+ assert fetched["config"]["spec"] == expected_spec
-def test_create_with_generate_name_derives_a_dns1123_name(
+def test_create_with_generate_name_derives_a_distinct_dns1123_name(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
@@ -202,47 +509,17 @@ def test_create_with_generate_name_derives_a_dns1123_name(
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
display_name = f"On Call Escalation {uuid.uuid4().hex[:8]}"
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={
- "generateName": True,
- "displayName": display_name,
- "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
- },
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.CREATED, response.text
-
- created = response.json()["data"]
- cleanup_notification_channels.append(created["id"])
-
- assert created["displayName"] == display_name
- assert DNS1123_LABEL.match(created["name"]), created["name"]
- assert created["name"].startswith("on-call-escalation-")
- assert created["name"] != display_name
-
-
-def test_create_generates_a_distinct_name_for_the_same_display_name(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- cleanup_notification_channels: list[str],
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- display_name = f"Duplicate Display {uuid.uuid4().hex[:8]}"
names = []
- for suffix in ("a", "b"):
+ # Both display names slugify to the same prefix, so only the random suffix
+ # keeps the generated names apart.
+ for variant in (display_name, display_name.upper()):
response = requests.post(
signoz.self.host_configs["8080"].get(V2_BASE_URL),
json={
"generateName": True,
- # The display name has to differ, because it is still the
- # receiver name in the alertmanager config and must be unique.
- "displayName": f"{display_name} {suffix}",
- "config": {"kind": "email", "spec": {"to": f"{suffix}@integration.test", "html": "<p>body</p>"}},
+ "displayName": variant,
+ "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
},
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
@@ -250,206 +527,94 @@ def test_create_generates_a_distinct_name_for_the_same_display_name(
assert response.status_code == HTTPStatus.CREATED, response.text
created = response.json()["data"]
cleanup_notification_channels.append(created["id"])
+
+ assert created["displayName"] == variant
+ assert DNS1123_LABEL.match(created["name"]), created["name"]
+ assert created["name"].startswith("on-call-escalation-")
names.append(created["name"])
assert names[0] != names[1]
-def test_create_rejects_a_duplicate_name_with_conflict(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- cleanup_notification_channels: list[str],
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- name = f"v2-dupname-{uuid.uuid4().hex[:8]}"
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": name, "displayName": f"{name} first", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.CREATED, response.text
- cleanup_notification_channels.append(response.json()["data"]["id"])
-
- # Same name, different display name: only the unique index on
- # (org_id, name) can catch this one.
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": name, "displayName": f"{name} second", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.CONFLICT, response.text
-
-
-def test_create_rejects_a_duplicate_display_name(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- cleanup_notification_channels: list[str],
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- display_name = f"v2-dupdisplay-{uuid.uuid4().hex[:8]}"
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": f"{display_name}-one", "displayName": display_name, "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.CREATED, response.text
- cleanup_notification_channels.append(response.json()["data"]["id"])
-
- # The display name is the receiver name in the alertmanager config, which
- # rejects duplicates before the row is ever written.
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": f"{display_name}-two", "displayName": display_name, "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.CONFLICT, response.text
- # Both v2 conflicts share a status and an error code, so only the message
- # separates a clashing display name from a clashing name.
- assert "display name" in response.text
-
-
- "body",
- [
- pytest.param({"name": "Not_A_Label", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="name_not_dns1123_label"),
- pytest.param({"config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="no_name_and_no_generate_name"),
- pytest.param({"name": "explicit", "generateName": True, "displayName": "Explicit", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="name_with_generate_name"),
- pytest.param({"generateName": True, "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="generate_name_without_display_name"),
- pytest.param({"name": "default-receiver", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="reserved_receiver_name"),
- pytest.param({"name": "no-config"}, id="no_config"),
- pytest.param({"name": "telegram-kind", "config": {"kind": "telegram", "spec": {"chatId": 1}}}, id="unmodelled_kind"),
- pytest.param({"name": "slack-unknown-field", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "channel": "#a", "text": "body", "iconEmoji": ":tada:"}}}, id="unknown_spec_field"),
- pytest.param({"name": "slack-with-email-spec", "config": {"kind": "slack", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="spec_of_another_kind"),
- pytest.param({"name": "slack-field-without-value", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "fields": [{"title": "Severity"}]}}}, id="slack_field_without_value"),
- pytest.param({"name": "slack-action-without-text", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "actions": [{"type": "button", "url": "https://signoz.test"}]}}}, id="slack_action_without_text"),
- pytest.param({"name": "slack-action-without-target", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "actions": [{"type": "button", "text": "Open"}]}}}, id="slack_action_without_url_or_name"),
- pytest.param({"name": "slack-confirm-without-text", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "actions": [{"type": "button", "text": "Ack", "name": "ack", "confirm": {"title": "Sure?"}}]}}}, id="slack_action_confirm_without_text"),
- pytest.param({"name": "extra-field", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}, "type": "email"}, id="unknown_envelope_field"),
- pytest.param({"name": "webhook-both-auth", "config": {"kind": "webhook", "spec": {"url": "https://webhook.test/hook", "username": "u", "password": "p", "bearerToken": "t"}}}, id="webhook_basic_auth_with_bearer_token"),
- # The last three reach the notifier's own validation rather than the
- # spec's, so they assert it still surfaces as a 400 through v2.
- pytest.param({"name": "jira-short-reopen", "config": {"kind": "jira", "spec": {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "t", "summary": "Alert", "description": "body", "reopenDuration": "30s"}}}, id="jira_reopen_duration_below_a_minute"),
- pytest.param({"name": "incidentio-bearer", "config": {"kind": "incidentio", "spec": {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF", "token": "Bearer incidentio-token", "title": "Alert", "description": "body"}}}, id="incidentio_token_with_bearer_prefix"),
- pytest.param({"name": "slack-empty-title", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "title": ""}}}, id="empty_string_on_a_defaulted_field"),
- pytest.param({"name": "jsmops-empty-tags", "config": {"kind": "jsmops", "spec": {"apiKey": "jsm-api-key", "tags": ""}}}, id="empty_string_on_a_defaulted_signoz_field"),
- pytest.param({"name": "jira-noncanonical-reopen", "config": {"kind": "jira", "spec": {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "t", "reopenDuration": "72h"}}}, id="jira_reopen_duration_not_as_reported"),
- pytest.param({"name": "email-lowercase-header", "config": {"kind": "email", "spec": {"to": "[email protected]", "headers": {"subject": "Alert"}}}}, id="email_header_name_not_as_reported"),
- ],
-)
-def test_create_rejects_invalid_bodies(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- body: dict,
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json=body,
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
-
-
@pytest.mark.parametrize(
- "kind,spec",
+ "create_spec,update_spec,expected_values_after_update,fields_read_as_null_after_update",
[
- pytest.param("slack", {"channel": "#alerts", "title": "Alert", "text": "body"}, id="slack_without_api_url"),
- pytest.param("email", {"html": "<p>body</p>"}, id="email_without_to"),
- pytest.param("webhook", {}, id="webhook_without_url"),
- pytest.param("pagerduty", {"description": "body"}, id="pagerduty_without_routing_key"),
- pytest.param("opsgenie", {"message": "subject", "description": "body"}, id="opsgenie_without_api_key"),
- pytest.param("msteams", {"title": "Alert", "text": "body"}, id="msteams_without_webhook_url"),
- pytest.param("googlechat", {"title": "Alert", "text": "body"}, id="googlechat_without_webhook_url"),
- pytest.param("jira", {"project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token"}, id="jira_without_site"),
- pytest.param("jira", {"site": "https://acme.atlassian.net", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token"}, id="jira_without_project"),
- pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "email": "[email protected]", "apiToken": "jira-api-token"}, id="jira_without_issue_type"),
- pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "apiToken": "jira-api-token"}, id="jira_without_email"),
- pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]"}, id="jira_without_api_token"),
- pytest.param("jsmops", {}, id="jsmops_without_api_key"),
- pytest.param("incidentio", {"token": "incidentio-token"}, id="incidentio_without_url"),
- pytest.param("incidentio", {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF"}, id="incidentio_without_token"),
+ pytest.param(
+ {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "fields": [{"title": "Severity", "value": "{{ .CommonLabels.severity }}"}],
+ "actions": [{"type": "button", "text": "Open", "url": "{{ .CommonLabels.ruleSource }}", "style": "primary", "name": "open", "value": "signoz"}],
+ },
+ {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "fields": [],
+ },
+ {"fields": []},
+ ["actions"],
+ id="list_sent_empty_and_list_omitted",
+ ),
+ pytest.param(
+ {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "channel": "#alerts",
+ "fields": [{"title": "Severity", "value": "{{ .CommonLabels.severity }}"}],
+ },
+ {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ },
+ {"channel": ""},
+ ["fields"],
+ id="string_and_list_omitted",
+ ),
],
)
-def test_create_rejects_a_spec_missing_a_required_field(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- kind: str,
- spec: dict,
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": f"v2-missing-{uuid.uuid4().hex[:8]}", "config": {"kind": kind, "spec": spec}},
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
-
-
-def test_create_accepts_an_opsgenie_channel_without_a_priority(
+def test_update_replaces_the_whole_spec( # pylint: disable=too-many-arguments,too-many-positional-arguments
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
cleanup_notification_channels: list[str],
+ create_spec: dict,
+ update_spec: dict,
+ expected_values_after_update: dict,
+ fields_read_as_null_after_update: list[str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- # Nothing seeds priority, so v1 channels created without one hold an empty
- # value; requiring it here would make those rows unsaveable through v2.
response = requests.post(
signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={
- "name": f"v2-og-nopriority-{uuid.uuid4().hex[:8]}",
- "config": {"kind": "opsgenie", "spec": {"apiKey": "og-api-key", "message": "subject", "description": "body"}},
- },
+ json={"name": f"v2-update-{uuid.uuid4().hex[:8]}", "config": {"kind": "slack", "spec": create_spec}},
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
)
assert response.status_code == HTTPStatus.CREATED, response.text
-
created = response.json()["data"]
cleanup_notification_channels.append(created["id"])
+ for field, value in create_spec.items():
+ assert created["config"]["spec"][field] == value, field
- assert created["config"]["spec"]["priority"] == ""
-
-
-def test_create_echoes_an_empty_value_on_a_field_with_no_default(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- cleanup_notification_channels: list[str],
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={
- "name": f"v2-pd-empty-{uuid.uuid4().hex[:8]}",
- "config": {"kind": "pagerduty", "spec": {"routingKey": "pd-routing-key", "severity": "", "class": ""}},
- },
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{created['id']}"),
+ json={"config": {"kind": "slack", "spec": update_spec}},
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
)
- assert response.status_code == HTTPStatus.CREATED, response.text
+ assert response.status_code == HTTPStatus.OK, response.text
+ updated = response.json()["data"]
- created = response.json()["data"]
- cleanup_notification_channels.append(created["id"])
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{created['id']}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ fetched = response.json()["data"]
- assert created["config"]["spec"]["severity"] == ""
- assert created["config"]["spec"]["class"] == ""
+ # Nothing from the create survives unless the update sends it again.
+ for spec_read in (updated["config"]["spec"], fetched["config"]["spec"]):
+ for field, value in expected_values_after_update.items():
+ assert spec_read[field] == value, field
+ for field in fields_read_as_null_after_update:
+ assert spec_read[field] is None, field
def test_notification_channel_v2_lifecycle( # pylint: disable=too-many-statements
@@ -510,6 +675,7 @@ def test_notification_channel_v2_lifecycle( # pylint: disable=too-many-statemen
updated = response.json()["data"]
assert updated["name"] == f"v2-list-alpha-{token_hex}"
assert updated["displayName"] == f"Alpha Overview {token_hex}"
+ assert updated["config"]["spec"]["apiUrl"] == "https://hooks.slack.test/services/T/B/Z"
assert updated["config"]["spec"]["channel"] == "#incidents"
response = requests.get(
@@ -539,8 +705,8 @@ def test_notification_channel_v2_lifecycle( # pylint: disable=too-many-statemen
assert {channel["displayName"] for channel in listed["channels"]} == {f"Alpha Overview {token_hex}", f"Gamma Overview {token_hex}"}
# ── stage 5: filter by kind ───────────────────────────────────────────────
- # msteams is stored as msteamsv2, so the filter has to translate the api kind
- # rather than match Channel.Type directly.
+ # msteams is the one kind whose name differs from its v1 type, so it is the
+ # filter case that can go wrong.
response = requests.get(
signoz.self.host_configs["8080"].get(V2_BASE_URL),
params={"query": token_hex, "kind": "msteams"},
@@ -627,151 +793,3 @@ def test_notification_channel_v2_lifecycle( # pylint: disable=too-many-statemen
)
assert response.status_code == HTTPStatus.OK, response.text
assert response.json()["data"]["total"] == 2
-
-
- "params",
- [
- pytest.param({"sort": "data"}, id="sort_outside_the_enum"),
- pytest.param({"order": "sideways"}, id="order_outside_the_enum"),
- pytest.param({"kind": "telegram"}, id="kind_outside_the_enum"),
- pytest.param({"limit": -1}, id="negative_limit"),
- pytest.param({"offset": -1}, id="negative_offset"),
- ],
-)
-def test_list_rejects_invalid_params(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- params: dict,
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
-
- response = requests.get(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- params=params,
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
-
-
-def test_get_unknown_id(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
-
- response = requests.get(
- signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/0199a1b2-c3d4-7000-8000-000000000000"),
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.NOT_FOUND, response.text
-
-
-def test_list_and_get_a_v1_channel_of_an_unmodelled_kind(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- cleanup_notification_channels: list[str],
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- name = f"v1-telegram-{uuid.uuid4().hex[:8]}"
-
- # telegram is a kind v1 accepts and v2 does not model, so it can only be
- # written through v1.
- response = requests.post(
- signoz.self.host_configs["8080"].get("/api/v1/channels"),
- json={"name": name, "telegram_configs": [{"chat": 12345, "token": "telegram-bot-token"}]},
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.CREATED, response.text
- channel_id = response.json()["data"]["id"]
- cleanup_notification_channels.append(channel_id)
-
- response = requests.get(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- params={"query": name},
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.OK, response.text
-
- listed = response.json()["data"]
- assert listed["total"] == 1
- assert listed["channels"][0]["displayName"] == name
- assert listed["channels"][0]["kind"] == ""
-
- response = requests.get(
- signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
-
-
- "body",
- [
- pytest.param({"name": "renamed", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}}, id="name_in_body"),
- pytest.param({"displayName": "Renamed", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}}, id="display_name_in_body"),
- pytest.param({"config": {"kind": "slack", "spec": {}}}, id="spec_missing_required_field"),
- pytest.param({}, id="no_config"),
- ],
-)
-def test_update_rejects_invalid_bodies( # pylint: disable=too-many-arguments,too-many-positional-arguments
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- cleanup_notification_channels: list[str],
- body: dict,
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- name = f"v2-badupdate-{uuid.uuid4().hex[:8]}"
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(V2_BASE_URL),
- json={"name": name, "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}},
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.CREATED, response.text
- channel_id = response.json()["data"]["id"]
- cleanup_notification_channels.append(channel_id)
-
- response = requests.put(
- signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
- json=body,
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
-
-
- "body",
- [
- pytest.param({"name": "test-send", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}}, id="name_in_body"),
- pytest.param({"config": {"kind": "slack", "spec": {}}}, id="spec_missing_required_field"),
- pytest.param({"config": {"kind": "telegram", "spec": {"chatId": 1}}}, id="unmodelled_kind"),
- pytest.param({}, id="no_config"),
- ],
-)
-def test_test_rejects_invalid_bodies(
- signoz: types.SigNoz,
- create_user_admin: None, # pylint: disable=unused-argument
- get_token: Callable[[str, str], str],
- body: dict,
-) -> None:
- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
-
- response = requests.post(
- signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/test"),
- json=body,
- headers={"Authorization": f"Bearer {token}"},
- timeout=TIMEOUT,
- )
- assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
diff --git a/tests/integration/tests/alertmanager/05_notification_channel_repair.py b/tests/integration/tests/alertmanager/05_notification_channel_repair.py
index 7990ae6761..2c8950188e 100644
--- a/tests/integration/tests/alertmanager/05_notification_channel_repair.py
+++ b/tests/integration/tests/alertmanager/05_notification_channel_repair.py
@@ -9,6 +9,7 @@ from fixtures.auth import (
USER_ADMIN_EMAIL,
USER_ADMIN_PASSWORD,
)
+from fixtures.notification_channel import rewrite_channel_as_legacy_receiver
TIMEOUT = 10
@@ -49,24 +50,45 @@ def test_repair_reports_nothing_for_a_readable_channel(
assert [channel["id"] for channel in repair["channels"]] == [channel_id]
-def test_repair_deletes_a_v1_channel_of_an_unmodelled_kind(
+def test_repair_deletes_a_legacy_channel_of_an_unmodelled_kind(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
cleanup_notification_channels: list[str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- name = f"v1-telegram-{uuid.uuid4().hex[:8]}"
+ name = f"legacy-telegram-{uuid.uuid4().hex[:8]}"
response = requests.post(
- signoz.self.host_configs["8080"].get("/api/v1/channels"),
- json={"name": name, "telegram_configs": [{"chat": 12345, "token": "telegram-bot-token"}]},
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}},
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
)
assert response.status_code == HTTPStatus.CREATED, response.text
channel_id = response.json()["data"]["id"]
cleanup_notification_channels.append(channel_id)
+ rewrite_channel_as_legacy_receiver(signoz, channel_id, {"name": name, "telegram_configs": [{"chat": 12345, "token": "telegram-bot-token"}]})
+
+ # v2 lists the row with an empty kind and refuses to read it.
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ params={"query": name},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ listed = response.json()["data"]
+ assert listed["total"] == 1
+ assert listed["channels"][0]["displayName"] == name
+ assert listed["channels"][0]["kind"] == ""
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
response = requests.post(
signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}/repair"),
@@ -111,29 +133,33 @@ def test_repair_deletes_a_v1_channel_of_an_unmodelled_kind(
assert response.json()["data"]["total"] == 0
-def test_repair_splits_a_v1_channel_carrying_several_notifiers(
+def test_repair_splits_a_legacy_channel_carrying_several_notifiers(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
cleanup_notification_channels: list[str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
- name = f"v1-fanout-{uuid.uuid4().hex[:8]}"
+ name = f"legacy-fanout-{uuid.uuid4().hex[:8]}"
- # Only v1 accepts a receiver with more than one notifier configuration.
response = requests.post(
- signoz.self.host_configs["8080"].get("/api/v1/channels"),
- json={
- "name": name,
- "slack_configs": [{"api_url": "https://hooks.slack.test/services/T/B/X", "channel": "#alerts"}],
- "webhook_configs": [{"url": "https://webhook.test/hook"}],
- },
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "channel": "#alerts"}}},
headers={"Authorization": f"Bearer {token}"},
timeout=TIMEOUT,
)
assert response.status_code == HTTPStatus.CREATED, response.text
channel_id = response.json()["data"]["id"]
cleanup_notification_channels.append(channel_id)
+ rewrite_channel_as_legacy_receiver(
+ signoz,
+ channel_id,
+ {
+ "name": name,
+ "slack_configs": [{"api_url": "https://hooks.slack.test/services/T/B/X", "channel": "#alerts"}],
+ "webhook_configs": [{"url": "https://webhook.test/hook"}],
+ },
+ )
response = requests.post(
signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}/repair"),
@@ -189,3 +215,65 @@ def test_repair_splits_a_v1_channel_carrying_several_notifiers(
)
assert response.status_code == HTTPStatus.OK, response.text
assert response.json()["data"]["config"]["kind"] == "slack"
+
+
+def test_repair_splits_off_an_unmodelled_notifier_for_its_own_delete(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"legacy-mixed-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "channel": "#alerts"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ channel_id = response.json()["data"]["id"]
+ cleanup_notification_channels.append(channel_id)
+ rewrite_channel_as_legacy_receiver(
+ signoz,
+ channel_id,
+ {
+ "name": name,
+ "slack_configs": [{"api_url": "https://hooks.slack.test/services/T/B/X", "channel": "#alerts"}],
+ "telegram_configs": [{"chat": 12345, "token": "telegram-bot-token"}],
+ },
+ )
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}/repair"),
+ params={"apply": "true"},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ repair = response.json()["data"]
+ assert repair["defect"] == "multiple_notifiers"
+ assert repair["applied"] is True
+ assert [channel["displayName"] for channel in repair["channels"]] == [name, f"{name} (2)"]
+ assert [channel["kind"] for channel in repair["channels"]] == ["slack", ""]
+ telegram_id = repair["channels"][1]["id"]
+ cleanup_notification_channels.append(telegram_id)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert response.json()["data"]["config"]["kind"] == "slack"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{telegram_id}/repair"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ repair = response.json()["data"]
+ assert repair["defect"] == "unsupported_notifier"
+ assert repair["action"] == "delete"
diff --git a/tests/integration/tests/alertmanager/07_notification_channels_v2_rejections.py b/tests/integration/tests/alertmanager/07_notification_channels_v2_rejections.py
new file mode 100644
index 0000000000..6d587ca1a3
--- /dev/null
+++ b/tests/integration/tests/alertmanager/07_notification_channels_v2_rejections.py
@@ -0,0 +1,555 @@
+import uuid
+from collections.abc import Callable
+from http import HTTPStatus
+
+import pytest
+import requests
+
+from fixtures import types
+from fixtures.auth import (
+ USER_ADMIN_EMAIL,
+ USER_ADMIN_PASSWORD,
+)
+
+TIMEOUT = 10
+
+V2_BASE_URL = "/api/v2/notification_channels"
+
+
+ "clashing_field,message_fragment",
+ [
+ pytest.param("name", "with name", id="name"),
+ pytest.param("displayName", "with display name", id="display_name"),
+ ],
+)
+def test_create_rejects_a_duplicate_with_conflict( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+ clashing_field: str,
+ message_fragment: str,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ shared = f"v2-dup-{uuid.uuid4().hex[:8]}"
+
+ first = {"name": f"{shared}-first", "displayName": f"{shared} first", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}
+ first[clashing_field] = shared
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json=first,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ cleanup_notification_channels.append(response.json()["data"]["id"])
+
+ second = {"name": f"{shared}-second", "displayName": f"{shared} second", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}
+ second[clashing_field] = shared
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json=second,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CONFLICT, response.text
+ # Both v2 conflicts share a status and an error code, so only the message
+ # separates a clashing display name from a clashing name.
+ assert message_fragment in response.text
+
+
+ "body",
+ [
+ pytest.param(
+ {
+ "name": "Not_A_Label",
+ "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
+ },
+ id="name_not_dns1123_label",
+ ),
+ pytest.param(
+ {"config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
+ id="no_name_and_no_generate_name",
+ ),
+ pytest.param(
+ {
+ "name": "explicit",
+ "generateName": True,
+ "displayName": "Explicit",
+ "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
+ },
+ id="name_with_generate_name",
+ ),
+ pytest.param(
+ {
+ "generateName": True,
+ "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
+ },
+ id="generate_name_without_display_name",
+ ),
+ pytest.param(
+ {
+ "name": "default-receiver",
+ "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
+ },
+ id="reserved_receiver_name",
+ ),
+ pytest.param({"name": "rejected"}, id="no_config"),
+ pytest.param(
+ {"name": "rejected", "config": {"kind": "telegram", "spec": {"chatId": 1}}},
+ id="unmodelled_kind",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "slack",
+ "spec": {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "channel": "#a",
+ "text": "body",
+ "iconEmoji": ":tada:",
+ },
+ },
+ },
+ id="unknown_spec_field",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "slack", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
+ },
+ id="spec_of_another_kind",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "slack", "spec": {"channel": "#alerts", "title": "Alert", "text": "body"}},
+ },
+ id="slack_without_api_url",
+ ),
+ pytest.param(
+ {"name": "rejected", "config": {"kind": "email", "spec": {"html": "<p>body</p>"}}},
+ id="email_without_to",
+ ),
+ pytest.param(
+ {"name": "rejected", "config": {"kind": "webhook", "spec": {}}},
+ id="webhook_without_url",
+ ),
+ pytest.param(
+ {"name": "rejected", "config": {"kind": "pagerduty", "spec": {"description": "body"}}},
+ id="pagerduty_without_routing_key",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "opsgenie", "spec": {"message": "subject", "description": "body"}},
+ },
+ id="opsgenie_without_api_key",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "msteams", "spec": {"title": "Alert", "text": "body"}},
+ },
+ id="msteams_without_webhook_url",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "googlechat", "spec": {"title": "Alert", "text": "body"}},
+ },
+ id="googlechat_without_webhook_url",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "jira",
+ "spec": {
+ "project": "OPS",
+ "issueType": "Bug",
+ "email": "[email protected]",
+ "apiToken": "jira-api-token",
+ },
+ },
+ },
+ id="jira_without_site",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "jira",
+ "spec": {
+ "site": "https://acme.atlassian.net",
+ "issueType": "Bug",
+ "email": "[email protected]",
+ "apiToken": "jira-api-token",
+ },
+ },
+ },
+ id="jira_without_project",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "jira",
+ "spec": {
+ "site": "https://acme.atlassian.net",
+ "project": "OPS",
+ "email": "[email protected]",
+ "apiToken": "jira-api-token",
+ },
+ },
+ },
+ id="jira_without_issue_type",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "jira",
+ "spec": {
+ "site": "https://acme.atlassian.net",
+ "project": "OPS",
+ "issueType": "Bug",
+ "apiToken": "jira-api-token",
+ },
+ },
+ },
+ id="jira_without_email",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "jira",
+ "spec": {
+ "site": "https://acme.atlassian.net",
+ "project": "OPS",
+ "issueType": "Bug",
+ "email": "[email protected]",
+ },
+ },
+ },
+ id="jira_without_api_token",
+ ),
+ pytest.param(
+ {"name": "rejected", "config": {"kind": "jsmops", "spec": {}}},
+ id="jsmops_without_api_key",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "incidentio", "spec": {"token": "incidentio-token"}},
+ },
+ id="incidentio_without_url",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "incidentio",
+ "spec": {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF"},
+ },
+ },
+ id="incidentio_without_token",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "slack",
+ "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "fields": [{"title": "Severity"}]},
+ },
+ },
+ id="slack_field_without_value",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "slack",
+ "spec": {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "actions": [{"type": "button", "url": "https://signoz.test"}],
+ },
+ },
+ },
+ id="slack_action_without_text",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "slack",
+ "spec": {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "actions": [{"type": "button", "text": "Open"}],
+ },
+ },
+ },
+ id="slack_action_without_url_or_name",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "slack",
+ "spec": {
+ "apiUrl": "https://hooks.slack.test/services/T/B/X",
+ "actions": [{"type": "button", "text": "Ack", "name": "ack", "confirm": {"title": "Sure?"}}],
+ },
+ },
+ },
+ id="slack_action_confirm_without_text",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
+ "type": "this key is not a valid",
+ },
+ id="unknown_envelope_field",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "webhook",
+ "spec": {"url": "https://webhook.test/hook", "username": "u", "password": "p", "bearerToken": "t"},
+ },
+ },
+ id="webhook_basic_auth_with_bearer_token",
+ ),
+ # The next two break a rule of the notifier rather than of the request
+ # shape, and still surface as a 400.
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "jira",
+ "spec": {
+ "site": "https://acme.atlassian.net",
+ "project": "OPS",
+ "issueType": "Bug",
+ "email": "[email protected]",
+ "apiToken": "t",
+ "summary": "Alert",
+ "description": "body",
+ "reopenDuration": "30s",
+ },
+ },
+ },
+ id="jira_reopen_duration_below_a_minute",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "incidentio",
+ "spec": {
+ "url": "https://api.incident.io/v2/alert_events/http/01ABCDEF",
+ "token": "Bearer incidentio-token",
+ "title": "Alert",
+ "description": "body",
+ },
+ },
+ },
+ id="incidentio_token_with_bearer_prefix",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "slack",
+ "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "title": ""},
+ },
+ },
+ id="slack_title_empty_instead_of_omitted",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "jsmops", "spec": {"apiKey": "jsm-api-key", "tags": ""}},
+ },
+ id="jsmops_tags_empty_instead_of_omitted",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {
+ "kind": "jira",
+ "spec": {
+ "site": "https://acme.atlassian.net",
+ "project": "OPS",
+ "issueType": "Bug",
+ "email": "[email protected]",
+ "apiToken": "t",
+ "reopenDuration": "72h",
+ },
+ },
+ },
+ id="jira_reopen_duration_not_as_reported",
+ ),
+ pytest.param(
+ {
+ "name": "rejected",
+ "config": {"kind": "email", "spec": {"to": "[email protected]", "headers": {"subject": "must be written in canonical form, Subject"}}},
+ },
+ id="email_header_name_not_canonical",
+ ),
+ ],
+)
+def test_create_rejects_invalid_bodies(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ body: dict,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json=body,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+
+ "params",
+ [
+ pytest.param({"sort": "data"}, id="sort_outside_the_enum"),
+ pytest.param({"order": "sideways"}, id="order_outside_the_enum"),
+ pytest.param({"kind": "telegram"}, id="kind_outside_the_enum"),
+ pytest.param({"limit": -1}, id="negative_limit"),
+ pytest.param({"offset": -1}, id="negative_offset"),
+ ],
+)
+def test_list_rejects_invalid_params(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ params: dict,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ params=params,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+
+def test_get_unknown_id(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/0199a1b2-c3d4-7000-8000-000000000000"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.NOT_FOUND, response.text
+
+
+ "body",
+ [
+ pytest.param(
+ {
+ "name": "renamed",
+ "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}},
+ },
+ id="name_in_body",
+ ),
+ pytest.param(
+ {
+ "displayName": "Renamed",
+ "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}},
+ },
+ id="display_name_in_body",
+ ),
+ pytest.param(
+ {"config": {"kind": "slack", "spec": {}}},
+ id="spec_missing_required_field",
+ ),
+ pytest.param({}, id="no_config"),
+ ],
+)
+def test_update_rejects_invalid_bodies( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+ body: dict,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"v2-badupdate-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ channel_id = response.json()["data"]["id"]
+ cleanup_notification_channels.append(channel_id)
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ json=body,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+
+ "body",
+ [
+ pytest.param(
+ {
+ "name": "test-send",
+ "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}},
+ },
+ id="name_in_body",
+ ),
+ pytest.param(
+ {"config": {"kind": "slack", "spec": {}}},
+ id="spec_missing_required_field",
+ ),
+ pytest.param(
+ {"config": {"kind": "telegram", "spec": {"chatId": 1}}},
+ id="unmodelled_kind",
+ ),
+ pytest.param({}, id="no_config"),
+ ],
+)
+def test_test_rejects_invalid_bodies(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ body: dict,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/test"),
+ json=body,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
diff --git a/tests/integration/tests/alertmanager/08_notification_channels_v1_v2.py b/tests/integration/tests/alertmanager/08_notification_channels_v1_v2.py
new file mode 100644
index 0000000000..4ec336c82b
--- /dev/null
+++ b/tests/integration/tests/alertmanager/08_notification_channels_v1_v2.py
@@ -0,0 +1,239 @@
+import json
+import time
+import uuid
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+from http import HTTPStatus
+
+import pytest
+import requests
+from wiremock.client import HttpMethods, Mapping, MappingRequest, MappingResponse
+
+from fixtures import types
+from fixtures.alerts import update_rule_channel_name, verify_notification_expectation
+from fixtures.auth import (
+ USER_ADMIN_EMAIL,
+ USER_ADMIN_PASSWORD,
+)
+from fixtures.fs import get_testdata_file_path
+from fixtures.notification_channel import rewrite_channel_as_legacy_receiver
+
+TIMEOUT = 10
+
+V2_BASE_URL = "/api/v2/notification_channels"
+
+
+def test_get_reflects_a_v2_update_after_a_v1_create(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ display_name = f"V1 then V2 {uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v1/channels"),
+ json={"name": display_name, "slack_configs": [{"api_url": "https://hooks.slack.test/services/T/B/V1", "channel": "#from-v1"}]},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ channel_id = response.json()["data"]["id"]
+ cleanup_notification_channels.append(channel_id)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert response.json()["data"]["config"]["spec"]["channel"] == "#from-v1"
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ json={"config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/V2", "channel": "#from-v2"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert response.json()["data"]["config"]["spec"]["channel"] == "#from-v2"
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ fetched = response.json()["data"]
+ assert fetched["displayName"] == display_name
+ assert fetched["config"]["spec"]["apiUrl"] == "https://hooks.slack.test/services/T/B/V2"
+ assert fetched["config"]["spec"]["channel"] == "#from-v2"
+
+
+ "receiver",
+ [
+ pytest.param(
+ {"telegram_configs": [{"chat": 12345, "token": "telegram-bot-token"}]},
+ id="kind_v2_does_not_model",
+ ),
+ pytest.param(
+ {
+ "slack_configs": [{"api_url": "https://hooks.slack.test/services/T/B/X", "channel": "#alerts"}],
+ "webhook_configs": [{"url": "https://webhook.test/hook"}],
+ },
+ id="several_notifiers",
+ ),
+ pytest.param(
+ {"webhook_configs": [{"url": "https://webhook.test/hook", "http_config": {"proxy_url": "http://proxy.test:3128"}}]},
+ id="unsupported_http_config",
+ ),
+ ],
+)
+def test_v1_rejects_a_receiver_v2_cannot_represent(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ receiver: dict,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v1/channels"),
+ json={"name": f"v1-rejected-{uuid.uuid4().hex[:8]}", **receiver},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+
+def test_update_retypes_a_legacy_channel_of_an_unmodelled_kind(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"legacy-telegram-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ channel_id = response.json()["data"]["id"]
+ cleanup_notification_channels.append(channel_id)
+ rewrite_channel_as_legacy_receiver(signoz, channel_id, {"name": name, "telegram_configs": [{"chat": 12345, "token": "telegram-bot-token"}]})
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+ # A v2 update needs nothing from the stored config, so it can rewrite a
+ # channel v2 cannot read.
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ json={"config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "channel": "#retyped"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert response.json()["data"]["config"]["kind"] == "slack"
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ fetched = response.json()["data"]
+ assert fetched["displayName"] == name
+ assert fetched["config"]["kind"] == "slack"
+ assert fetched["config"]["spec"]["channel"] == "#retyped"
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ params={"query": name},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert response.json()["data"]["channels"][0]["kind"] == "slack"
+
+
+def test_alerts_still_reach_a_legacy_channel_v2_cannot_read( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ notification_channel: types.TestContainerDocker,
+ make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
+ cleanup_notification_channels: list[str],
+ create_alert_rule: Callable[[dict], str],
+ insert_alert_data: Callable[[list[types.AlertData], datetime], None],
+ maildev: types.TestContainerDocker,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"legacy-delivery-{uuid.uuid4().hex[:8]}"
+ slack_path = f"/services/T/B/{name}"
+ webhook_path = f"/webhook/{name}"
+ make_http_mocks(
+ notification_channel,
+ [Mapping(request=MappingRequest(method=HttpMethods.POST, url=path), response=MappingResponse(status=200, json_body={}), persistent=False) for path in (slack_path, webhook_path)],
+ )
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": "webhook", "spec": {"url": notification_channel.container_configs["8080"].get(webhook_path)}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ channel_id = response.json()["data"]["id"]
+ cleanup_notification_channels.append(channel_id)
+ rewrite_channel_as_legacy_receiver(
+ signoz,
+ channel_id,
+ {
+ "name": name,
+ "slack_configs": [{"api_url": notification_channel.container_configs["8080"].get(slack_path), "channel": "#legacy"}],
+ "webhook_configs": [{"url": notification_channel.container_configs["8080"].get(webhook_path)}],
+ },
+ )
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+ # The rule must not fire before the alertmanager has polled the swapped receiver.
+ time.sleep(12)
+
+ insert_alert_data(
+ [types.AlertData(type="metrics", data_path="ruler/test_scenarios/threshold_above_at_least_once/alert_data.jsonl")],
+ base_time=datetime.now(tz=UTC) - timedelta(minutes=5),
+ )
+ with open(get_testdata_file_path("ruler/test_scenarios/threshold_above_at_least_once/rule.json"), encoding="utf-8") as f:
+ rule_data = json.load(f)
+ update_rule_channel_name(rule_data, name)
+ create_alert_rule(rule_data)
+
+ verify_notification_expectation(
+ notification_channel,
+ maildev,
+ types.AMNotificationExpectation(
+ should_notify=True,
+ wait_time_seconds=120,
+ notification_validations=[
+ types.NotificationValidation(destination_type="webhook", validation_data={"path": slack_path, "json_body": {"channel": "#legacy"}}),
+ types.NotificationValidation(destination_type="webhook", validation_data={"path": webhook_path, "json_body": {"status": "firing", "receiver": name}}),
+ ],
+ ),
+ )